function display_content(&$a, $update = 0) { if (get_config('system', 'block_public') && !local_user() && !remote_user()) { notice(t('Public access denied.') . EOL); return; } require_once "include/bbcode.php"; require_once 'include/security.php'; require_once 'include/conversation.php'; require_once 'include/acl_selectors.php'; $o = ''; $a->page['htmlhead'] .= replace_macros(get_markup_template('display-head.tpl'), array()); if ($update) { $nick = $_REQUEST['nick']; } else { $nick = $a->argc > 1 ? $a->argv[1] : ''; } if ($update) { $item_id = $_REQUEST['item_id']; $a->profile = array('uid' => intval($update), 'profile_uid' => intval($update)); } else { $item_id = $a->argc > 2 ? $a->argv[2] : 0; if ($a->argc == 2) { $nick = ""; if (local_user()) { $r = q("SELECT `id` FROM `item`\n\t\t\t\t\tWHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t\t\t\tAND `guid` = '%s' AND `uid` = %d", $a->argv[1], local_user()); if (count($r)) { $item_id = $r[0]["id"]; $nick = $a->user["nickname"]; } } if ($nick == "") { $r = q("SELECT `user`.`nickname`, `item`.`id` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`\n\t\t\t\t\tWHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t\t\t\tAND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''\n\t\t\t\t\t\tAND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''\n\t\t\t\t\t\tAND `item`.`private` = 0 AND NOT `user`.`hidewall`\n\t\t\t\t\t\tAND `item`.`guid` = '%s'", $a->argv[1]); // AND `item`.`private` = 0 AND `item`.`wall` = 1 if (count($r)) { $item_id = $r[0]["id"]; $nick = $r[0]["nickname"]; } } if ($nick == "") { $r = q("SELECT `item`.`id` FROM `item`\n\t\t\t\t\tWHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0\n\t\t\t\t\t\tAND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''\n\t\t\t\t\t\tAND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''\n\t\t\t\t\t\tAND `item`.`private` = 0 AND `item`.`uid` = 0\n\t\t\t\t\t\tAND `item`.`guid` = '%s'", $a->argv[1]); // AND `item`.`private` = 0 AND `item`.`wall` = 1 if (count($r)) { $item_id = $r[0]["id"]; } } } } if (!$item_id) { $a->error = 404; notice(t('Item not found.') . EOL); return; } $groups = array(); $contact = null; $remote_contact = false; $contact_id = 0; if (is_array($_SESSION['remote'])) { foreach ($_SESSION['remote'] as $v) { if ($v['uid'] == $a->profile['uid']) { $contact_id = $v['cid']; break; } } } if ($contact_id) { $groups = init_groups_visitor($contact_id); $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($contact_id), intval($a->profile['uid'])); if (count($r)) { $contact = $r[0]; $remote_contact = true; } } if (!$remote_contact) { if (local_user()) { $contact_id = $_SESSION['cid']; $contact = $a->contact; } } $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", intval($a->profile['uid'])); if (count($r)) { $a->page_contact = $r[0]; } $is_owner = local_user() && local_user() == $a->profile['profile_uid'] ? true : false; if ($a->profile['hidewall'] && !$is_owner && !$remote_contact) { notice(t('Access to this profile has been restricted.') . EOL); return; } if ($is_owner) { $celeb = $a->user['page-flags'] == PAGE_SOAPBOX || $a->user['page-flags'] == PAGE_COMMUNITY ? true : false; $x = array('is_owner' => true, 'allow_location' => $a->user['allow_location'], 'default_location' => $a->user['default-location'], 'nickname' => $a->user['nickname'], 'lockstate' => is_array($a->user) && (strlen($a->user['allow_cid']) || strlen($a->user['allow_gid']) || strlen($a->user['deny_cid']) || strlen($a->user['deny_gid'])) ? 'lock' : 'unlock', 'acl' => populate_acl($a->user, $celeb), 'bang' => '', 'visitor' => 'block', 'profile_uid' => local_user(), 'acl_data' => construct_acl_data($a, $a->user)); $o .= status_editor($a, $x, 0, true); } $sql_extra = item_permissions_sql($a->profile['uid'], $remote_contact, $groups); // AND `item`.`parent` = ( SELECT `parent` FROM `item` FORCE INDEX (PRIMARY, `uri`) WHERE ( `id` = '%s' OR `uri` = '%s' )) if ($update) { $r = q("SELECT id FROM item WHERE item.uid = %d\n\t\t AND `item`.`parent` = (SELECT `parent` FROM `item` WHERE (`id` = '%s' OR `uri` = '%s'))\n\t\t {$sql_extra} AND unseen = 1", intval($a->profile['uid']), dbesc($item_id), dbesc($item_id)); if (!$r) { return ''; } } // AND `item`.`parent` = ( SELECT `parent` FROM `item` FORCE INDEX (PRIMARY, `uri`) WHERE ( `id` = '%s' OR `uri` = '%s' ) $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\n\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\n\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,\n\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\tFROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\tand `item`.`moderated` = 0\n\t\tAND `item`.`parent` = (SELECT `parent` FROM `item` WHERE (`id` = '%s' OR `uri` = '%s')\n\t\tAND uid = %d)\n\t\t{$sql_extra}\n\t\tORDER BY `parent` DESC, `gravity` ASC, `id` ASC", intval($a->profile['uid']), dbesc($item_id), dbesc($item_id), intval($a->profile['uid'])); if (!$r && local_user()) { // Check if this is another person's link to a post that we have $r = q("SELECT `item`.uri FROM `item`\n\t\t\tWHERE (`item`.`id` = '%s' OR `item`.`uri` = '%s' )\n\t\t\tLIMIT 1", dbesc($item_id), dbesc($item_id)); if ($r) { $item_uri = $r[0]['uri']; // AND `item`.`parent` = ( SELECT `parent` FROM `item` FORCE INDEX (PRIMARY, `uri`) WHERE `uri` = '%s' AND uid = %d ) $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,\n\t\t\t\t`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,\n\t\t\t\t`contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`, \n\t\t\t\t`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`\n\t\t\t\tFROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`\n\t\t\t\tAND `contact`.`blocked` = 0 AND `contact`.`pending` = 0\n\t\t\t\tWHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`deleted` = 0\n\t\t\t\tand `item`.`moderated` = 0\n\t\t\t\tAND `item`.`parent` = (SELECT `parent` FROM `item` WHERE `uri` = '%s' AND uid = %d)\n\t\t\t\tORDER BY `parent` DESC, `gravity` ASC, `id` ASC ", intval(local_user()), dbesc($item_uri), intval(local_user())); } } if ($r) { if (local_user() && local_user() == $a->profile['uid']) { q("UPDATE `item` SET `unseen` = 0\n\t\t\t\tWHERE `parent` = %d AND `unseen` = 1", intval($r[0]['parent'])); } $items = conv_sort($r, "`commented`"); if (!$update) { $o .= "<script> var netargs = '?f=&nick=" . $nick . "&item_id=" . $item_id . "'; </script>"; } $o .= conversation($a, $items, 'display', $update); // Preparing the meta header require_once 'include/bbcode.php'; require_once "include/html2plain.php"; $description = trim(html2plain(bbcode($r[0]["body"], false, false), 0, true)); $title = trim(html2plain(bbcode($r[0]["title"], false, false), 0, true)); $author_name = $r[0]["author-name"]; $image = ""; if ($image == "") { $image = $r[0]["thumb"]; } if ($title == "") { $title = $author_name; } $description = htmlspecialchars($description, ENT_COMPAT, 'UTF-8', true); // allow double encoding here $title = htmlspecialchars($title, ENT_COMPAT, 'UTF-8', true); // allow double encoding here $author_name = htmlspecialchars($author_name, ENT_COMPAT, 'UTF-8', true); // allow double encoding here //<meta name="keywords" content=""> $a->page['htmlhead'] .= '<meta name="author" content="' . $author_name . '" />' . "\n"; $a->page['htmlhead'] .= '<meta name="title" content="' . $title . '" />' . "\n"; $a->page['htmlhead'] .= '<meta name="fulltitle" content="' . $title . '" />' . "\n"; $a->page['htmlhead'] .= '<meta name="description" content="' . $description . '" />' . "\n"; // Schema.org microdata $a->page['htmlhead'] .= '<meta itemprop="name" content="' . $title . '" />' . "\n"; $a->page['htmlhead'] .= '<meta itemprop="description" content="' . $description . '" />' . "\n"; $a->page['htmlhead'] .= '<meta itemprop="image" content="' . $image . '" />' . "\n"; $a->page['htmlhead'] .= '<meta itemprop="author" content="' . $author_name . '" />' . "\n"; // Twitter cards $a->page['htmlhead'] .= '<meta name="twitter:card" content="summary" />' . "\n"; $a->page['htmlhead'] .= '<meta name="twitter:title" content="' . $title . '" />' . "\n"; $a->page['htmlhead'] .= '<meta name="twitter:description" content="' . $description . '" />' . "\n"; $a->page['htmlhead'] .= '<meta name="twitter:image" content="' . $image . '" />' . "\n"; $a->page['htmlhead'] .= '<meta name="twitter:url" content="' . $r[0]["plink"] . '" />' . "\n"; // Dublin Core $a->page['htmlhead'] .= '<meta name="DC.title" content="' . $title . '" />' . "\n"; $a->page['htmlhead'] .= '<meta name="DC.description" content="' . $description . '" />' . "\n"; // Open Graph $a->page['htmlhead'] .= '<meta property="og:type" content="website" />' . "\n"; $a->page['htmlhead'] .= '<meta property="og:title" content="' . $title . '" />' . "\n"; $a->page['htmlhead'] .= '<meta property="og:image" content="' . $image . '" />' . "\n"; $a->page['htmlhead'] .= '<meta property="og:url" content="' . $r[0]["plink"] . '" />' . "\n"; $a->page['htmlhead'] .= '<meta property="og:description" content="' . $description . '" />' . "\n"; $a->page['htmlhead'] .= '<meta name="og:article:author" content="' . $author_name . '" />' . "\n"; // article:tag return $o; } $r = q("SELECT `id`,`deleted` FROM `item` WHERE `id` = '%s' OR `uri` = '%s' LIMIT 1", dbesc($item_id), dbesc($item_id)); if ($r) { if ($r[0]['deleted']) { notice(t('Item has been removed.') . EOL); } else { notice(t('Permission denied.') . EOL); } } else { notice(t('Item not found.') . EOL); } return $o; }
function item_post(&$a) { if (!local_user() && !remote_user() && !x($_REQUEST, 'commenter')) { return; } require_once 'include/security.php'; $uid = local_user(); if (x($_REQUEST, 'dropitems')) { $arr_drop = explode(',', $_REQUEST['dropitems']); drop_items($arr_drop); $json = array('success' => 1); echo json_encode($json); killme(); } call_hooks('post_local_start', $_REQUEST); // logger('postinput ' . file_get_contents('php://input')); logger('postvars ' . print_r($_REQUEST, true), LOGGER_DATA); $api_source = x($_REQUEST, 'api_source') && $_REQUEST['api_source'] ? true : false; $message_id = x($_REQUEST, 'message_id') && $api_source ? strip_tags($_REQUEST['message_id']) : ''; $return_path = x($_REQUEST, 'return') ? $_REQUEST['return'] : ''; $preview = x($_REQUEST, 'preview') ? intval($_REQUEST['preview']) : 0; // Check for doubly-submitted posts, and reject duplicates // Note that we have to ignore previews, otherwise nothing will post // after it's been previewed if (!$preview && x($_REQUEST['post_id_random'])) { if (x($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) { logger("item post: duplicate post", LOGGER_DEBUG); item_post_return($a->get_baseurl(), $api_source, $return_path); } else { $_SESSION['post-random'] = $_REQUEST['post_id_random']; } } /** * Is this a reply to something? */ $parent = x($_REQUEST, 'parent') ? intval($_REQUEST['parent']) : 0; $parent_uri = x($_REQUEST, 'parent_uri') ? trim($_REQUEST['parent_uri']) : ''; $parent_item = null; $parent_contact = null; $thr_parent = ''; $parid = 0; $r = false; $objecttype = null; if ($parent || $parent_uri) { $objecttype = ACTIVITY_OBJ_COMMENT; if (!x($_REQUEST, 'type')) { $_REQUEST['type'] = 'net-comment'; } if ($parent) { $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($parent)); } elseif ($parent_uri && local_user()) { // This is coming from an API source, and we are logged in $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($parent_uri), intval(local_user())); } // if this isn't the real parent of the conversation, find it if ($r !== false && count($r)) { $parid = $r[0]['parent']; $parent_uri = $r[0]['uri']; if ($r[0]['id'] != $r[0]['parent']) { $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1", intval($parid)); } } if ($r === false || !count($r)) { notice(t('Unable to locate original post.') . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } $parent_item = $r[0]; $parent = $r[0]['id']; // multi-level threading - preserve the info but re-parent to our single level threading //if(($parid) && ($parid != $parent)) $thr_parent = $parent_uri; if ($parent_item['contact-id'] && $uid) { $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($parent_item['contact-id']), intval($uid)); if (count($r)) { $parent_contact = $r[0]; // If the contact id doesn't fit with the contact, then set the contact to null $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($thr_parent)); if (count($thrparent) and $thrparent[0]["network"] === NETWORK_OSTATUS and normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"])) { $parent_contact = null; require_once "include/Scrape.php"; $probed_contact = probe_url($thrparent[0]["author-link"]); if ($probed_contact["network"] != NETWORK_FEED) { $parent_contact = $probed_contact; $parent_contact["nurl"] = normalise_link($probed_contact["url"]); $parent_contact["thumb"] = $probed_contact["photo"]; $parent_contact["micro"] = $probed_contact["photo"]; } logger('parent contact: ' . print_r($parent_contact, true), LOGGER_DEBUG); } else { logger('no contact found: ' . print_r($thrparent, true), LOGGER_DEBUG); } } } } if ($parent) { logger('mod_item: item_post parent=' . $parent); } $profile_uid = x($_REQUEST, 'profile_uid') ? intval($_REQUEST['profile_uid']) : 0; $post_id = x($_REQUEST, 'post_id') ? intval($_REQUEST['post_id']) : 0; $app = x($_REQUEST, 'source') ? strip_tags($_REQUEST['source']) : ''; $extid = x($_REQUEST, 'extid') ? strip_tags($_REQUEST['extid']) : ''; $allow_moderated = false; // here is where we are going to check for permission to post a moderated comment. // First check that the parent exists and it is a wall item. if (x($_REQUEST, 'commenter') && (!$parent || !$parent_item['wall'])) { notice(t('Permission denied.') . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } // Now check that it is a page_type of PAGE_BLOG, and that valid personal details // have been provided, and run any anti-spam plugins // TODO if (!can_write_wall($a, $profile_uid) && !$allow_moderated) { notice(t('Permission denied.') . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } // is this an edited post? $orig_post = null; if ($post_id) { $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval($profile_uid), intval($post_id)); if (!count($i)) { killme(); } $orig_post = $i[0]; } $user = null; $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($profile_uid)); if (count($r)) { $user = $r[0]; } if ($orig_post) { $str_group_allow = $orig_post['allow_gid']; $str_contact_allow = $orig_post['allow_cid']; $str_group_deny = $orig_post['deny_gid']; $str_contact_deny = $orig_post['deny_cid']; $location = $orig_post['location']; $coord = $orig_post['coord']; $verb = $orig_post['verb']; $objecttype = $orig_post['object-type']; $emailcc = $orig_post['emailcc']; $app = $orig_post['app']; $categories = $orig_post['file']; $title = notags(trim($_REQUEST['title'])); $body = escape_tags(trim($_REQUEST['body'])); $private = $orig_post['private']; $pubmail_enable = $orig_post['pubmail']; $network = $orig_post['network']; $guid = $orig_post['guid']; $extid = $orig_post['extid']; } else { // if coming from the API and no privacy settings are set, // use the user default permissions - as they won't have // been supplied via a form. if ($api_source && !array_key_exists('contact_allow', $_REQUEST) && !array_key_exists('group_allow', $_REQUEST) && !array_key_exists('contact_deny', $_REQUEST) && !array_key_exists('group_deny', $_REQUEST)) { $str_group_allow = $user['allow_gid']; $str_contact_allow = $user['allow_cid']; $str_group_deny = $user['deny_gid']; $str_contact_deny = $user['deny_cid']; } else { // use the posted permissions $str_group_allow = perms2str($_REQUEST['group_allow']); $str_contact_allow = perms2str($_REQUEST['contact_allow']); $str_group_deny = perms2str($_REQUEST['group_deny']); $str_contact_deny = perms2str($_REQUEST['contact_deny']); } $title = notags(trim($_REQUEST['title'])); $location = notags(trim($_REQUEST['location'])); $coord = notags(trim($_REQUEST['coord'])); $verb = notags(trim($_REQUEST['verb'])); $emailcc = notags(trim($_REQUEST['emailcc'])); $body = escape_tags(trim($_REQUEST['body'])); $network = notags(trim($_REQUEST['network'])); $guid = get_guid(32); $naked_body = preg_replace('/\\[(.+?)\\]/', '', $body); if (version_compare(PHP_VERSION, '5.3.0', '>=')) { $l = new Text_LanguageDetect(); //$lng = $l->detectConfidence($naked_body); //$postopts = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : ''); $lng = $l->detect($naked_body, 3); if (sizeof($lng) > 0) { $postopts = ""; foreach ($lng as $language => $score) { if ($postopts == "") { $postopts = "lang="; } else { $postopts .= ":"; } $postopts .= $language . ";" . $score; } } logger('mod_item: detect language' . print_r($lng, true) . $naked_body, LOGGER_DATA); } else { $postopts = ''; } $private = strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny) ? 1 : 0; if ($user['hidewall']) { $private = 2; } // If this is a comment, set the permissions from the parent. if ($parent_item) { $private = 0; // for non native networks use the network of the original post as network of the item if ($parent_item['network'] != NETWORK_DIASPORA and $parent_item['network'] != NETWORK_OSTATUS and $network == "") { $network = $parent_item['network']; } if ($parent_item['private'] || strlen($parent_item['allow_cid']) || strlen($parent_item['allow_gid']) || strlen($parent_item['deny_cid']) || strlen($parent_item['deny_gid'])) { $private = $parent_item['private'] ? $parent_item['private'] : 1; } $str_contact_allow = $parent_item['allow_cid']; $str_group_allow = $parent_item['allow_gid']; $str_contact_deny = $parent_item['deny_cid']; $str_group_deny = $parent_item['deny_gid']; } $pubmail_enable = x($_REQUEST, 'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && !$private ? 1 : 0; // if using the API, we won't see pubmail_enable - figure out if it should be set if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) { $mail_disabled = function_exists('imap_open') && !get_config('system', 'imap_disabled') ? 0 : 1; if (!$mail_disabled) { $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1", intval(local_user())); if (count($r) && intval($r[0]['pubmail'])) { $pubmail_enabled = true; } } } if (!strlen($body)) { if ($preview) { killme(); } info(t('Empty post discarded.') . EOL); if (x($_REQUEST, 'return')) { goaway($a->get_baseurl() . "/" . $return_path); } killme(); } } if (strlen($categories)) { // get the "fileas" tags for this post $filedas = file_tag_file_to_list($categories, 'file'); } // save old and new categories, so we can determine what needs to be deleted from pconfig $categories_old = $categories; $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category'); $categories_new = $categories; if (strlen($filedas)) { // append the fileas stuff to the new categories list $categories .= file_tag_list_to_file($filedas, 'file'); } // Work around doubled linefeeds in Tinymce 3.5b2 // First figure out if it's a status post that would've been // created using tinymce. Otherwise leave it alone. /* $plaintext = (local_user() ? intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled($profile_uid,'richtext') : 0); if((! $parent) && (! $api_source) && (! $plaintext)) { $body = fix_mce_lf($body); }*/ $plaintext = local_user() ? !feature_enabled($profile_uid, 'richtext') : 0; if (!$parent && !$api_source && !$plaintext) { $body = fix_mce_lf($body); } // get contact info for poster $author = null; $self = false; $contact_id = 0; if (local_user() && local_user() == $profile_uid) { $self = true; $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", intval($_SESSION['uid'])); } elseif (remote_user()) { if (is_array($_SESSION['remote'])) { foreach ($_SESSION['remote'] as $v) { if ($v['uid'] == $profile_uid) { $contact_id = $v['cid']; break; } } } if ($contact_id) { $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($contact_id)); } } if (count($r)) { $author = $r[0]; $contact_id = $author['id']; } // get contact info for owner if ($profile_uid == local_user()) { $contact_record = $author; } else { $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", intval($profile_uid)); if (count($r)) { $contact_record = $r[0]; } } $post_type = notags(trim($_REQUEST['type'])); if ($post_type === 'net-comment') { if ($parent_item !== null) { if ($parent_item['wall'] == 1) { $post_type = 'wall-comment'; } else { $post_type = 'remote-comment'; } } } /** * * When a photo was uploaded into the message using the (profile wall) ajax * uploader, The permissions are initially set to disallow anybody but the * owner from seeing it. This is because the permissions may not yet have been * set for the post. If it's private, the photo permissions should be set * appropriately. But we didn't know the final permissions on the post until * now. So now we'll look for links of uploaded messages that are in the * post and set them to the same permissions as the post itself. * */ $match = null; if (!$preview && preg_match_all("/\\[img([\\=0-9x]*?)\\](.*?)\\[\\/img\\]/", $body, $match)) { $images = $match[2]; if (count($images)) { $objecttype = ACTIVITY_OBJ_IMAGE; foreach ($images as $image) { if (!stristr($image, $a->get_baseurl() . '/photo/')) { continue; } $image_uri = substr($image, strrpos($image, '/') + 1); $image_uri = substr($image_uri, 0, strpos($image_uri, '-')); if (!strlen($image_uri)) { continue; } $srch = '<' . intval($contact_id) . '>'; $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''\n\t\t\t\t\tAND `resource-id` = '%s' AND `uid` = %d LIMIT 1", dbesc($srch), dbesc($image_uri), intval($profile_uid)); if (!count($r)) { continue; } $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'\n\t\t\t\t\tWHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ", dbesc($str_contact_allow), dbesc($str_group_allow), dbesc($str_contact_deny), dbesc($str_group_deny), dbesc($image_uri), intval($profile_uid), dbesc(t('Wall Photos'))); } } } /** * Next link in any attachment references we find in the post. */ $match = false; if (!$preview && preg_match_all("/\\[attachment\\](.*?)\\[\\/attachment\\]/", $body, $match)) { $attaches = $match[1]; if (count($attaches)) { foreach ($attaches as $attach) { $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval($profile_uid), intval($attach)); if (count($r)) { $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'\n\t\t\t\t\t\tWHERE `uid` = %d AND `id` = %d", dbesc($str_contact_allow), dbesc($str_group_allow), dbesc($str_contact_deny), dbesc($str_group_deny), intval($profile_uid), intval($attach)); } } } } // embedded bookmark in post? set bookmark flag $bookmark = 0; if (preg_match_all("/\\[bookmark\\=([^\\]]*)\\](.*?)\\[\\/bookmark\\]/ism", $body, $match, PREG_SET_ORDER)) { $objecttype = ACTIVITY_OBJ_BOOKMARK; $bookmark = 1; } $body = bb_translate_video($body); /** * Fold multi-line [code] sequences */ $body = preg_replace('/\\[\\/code\\]\\s*\\[code\\]/ism', "\n", $body); $body = scale_external_images($body, false); // Setting the object type if not defined before if (!$objecttype) { $objecttype = ACTIVITY_OBJ_NOTE; // Default value require_once "include/plaintext.php"; $objectdata = get_attached_data($body); if ($post["type"] == "link") { $objecttype = ACTIVITY_OBJ_BOOKMARK; } elseif ($post["type"] == "video") { $objecttype = ACTIVITY_OBJ_VIDEO; } elseif ($post["type"] == "photo") { $objecttype = ACTIVITY_OBJ_IMAGE; } } /** * Look for any tags and linkify them */ $str_tags = ''; $inform = ''; $tags = get_tags($body); /** * add a statusnet style reply tag if the original post was from there * and we are replying, and there isn't one already */ if ($parent_contact && $parent_contact['network'] === NETWORK_OSTATUS && $parent_contact['nick'] && !in_array('@' . $parent_contact['nick'], $tags)) { $body = '@' . $parent_contact['nick'] . ' ' . $body; $tags[] = '@' . $parent_contact['nick']; } $tagged = array(); $private_forum = false; if (count($tags)) { foreach ($tags as $tag) { if (strpos($tag, '#') === 0) { continue; } // If we already tagged 'Robert Johnson', don't try and tag 'Robert'. // Robert Johnson should be first in the $tags array $fullnametagged = false; for ($x = 0; $x < count($tagged); $x++) { if (stristr($tagged[$x], $tag . ' ')) { $fullnametagged = true; break; } } if ($fullnametagged) { continue; } $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network); if ($success['replaced']) { $tagged[] = $tag; } if (is_array($success['contact']) && intval($success['contact']['prv'])) { $private_forum = true; $private_id = $success['contact']['id']; } } } if ($private_forum && !$parent && !$private) { // we tagged a private forum in a top level post and the message was public. // Restrict it. $private = 1; $str_contact_allow = '<' . $private_id . '>'; } $attachments = ''; $match = false; if (preg_match_all('/(\\[attachment\\]([0-9]+)\\[\\/attachment\\])/', $body, $match)) { foreach ($match[2] as $mtch) { $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1", intval($profile_uid), intval($mtch)); if (count($r)) { if (strlen($attachments)) { $attachments .= ','; } $attachments .= '[attach]href="' . $a->get_baseurl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . ($r[0]['filename'] ? $r[0]['filename'] : '') . '"[/attach]'; } $body = str_replace($match[1], '', $body); } } $wall = 0; if ($post_type === 'wall' || $post_type === 'wall-comment') { $wall = 1; } if (!strlen($verb)) { $verb = ACTIVITY_POST; } if ($network == "") { $network = NETWORK_DFRN; } $gravity = $parent ? 6 : 0; // even if the post arrived via API we are considering that it // originated on this site by default for determining relayability. $origin = x($_REQUEST, 'origin') ? intval($_REQUEST['origin']) : 1; $notify_type = $parent ? 'comment-new' : 'wall-new'; $uri = $message_id ? $message_id : item_new_uri($a->get_hostname(), $profile_uid); // Fallback so that we alway have a thr-parent if (!$thr_parent) { $thr_parent = $uri; } $datarray = array(); $datarray['uid'] = $profile_uid; $datarray['type'] = $post_type; $datarray['wall'] = $wall; $datarray['gravity'] = $gravity; $datarray['network'] = $network; $datarray['contact-id'] = $contact_id; $datarray['owner-name'] = $contact_record['name']; $datarray['owner-link'] = $contact_record['url']; $datarray['owner-avatar'] = $contact_record['thumb']; $datarray['author-name'] = $author['name']; $datarray['author-link'] = $author['url']; $datarray['author-avatar'] = $author['thumb']; $datarray['created'] = datetime_convert(); $datarray['edited'] = datetime_convert(); $datarray['commented'] = datetime_convert(); $datarray['received'] = datetime_convert(); $datarray['changed'] = datetime_convert(); $datarray['extid'] = $extid; $datarray['guid'] = $guid; $datarray['uri'] = $uri; $datarray['title'] = $title; $datarray['body'] = $body; $datarray['app'] = $app; $datarray['location'] = $location; $datarray['coord'] = $coord; $datarray['tag'] = $str_tags; $datarray['file'] = $categories; $datarray['inform'] = $inform; $datarray['verb'] = $verb; $datarray['object-type'] = $objecttype; $datarray['allow_cid'] = $str_contact_allow; $datarray['allow_gid'] = $str_group_allow; $datarray['deny_cid'] = $str_contact_deny; $datarray['deny_gid'] = $str_group_deny; $datarray['private'] = $private; $datarray['pubmail'] = $pubmail_enable; $datarray['attach'] = $attachments; $datarray['bookmark'] = intval($bookmark); $datarray['thr-parent'] = $thr_parent; $datarray['postopts'] = $postopts; $datarray['origin'] = $origin; $datarray['moderated'] = $allow_moderated; /** * These fields are for the convenience of plugins... * 'self' if true indicates the owner is posting on their own wall * If parent is 0 it is a top-level post. */ $datarray['parent'] = $parent; $datarray['self'] = $self; // $datarray['prvnets'] = $user['prvnets']; if ($orig_post) { $datarray['edit'] = true; } // Search for hashtags item_body_set_hashtags($datarray); // preview mode - prepare the body for display and send it via json if ($preview) { require_once 'include/conversation.php'; $o = conversation($a, array(array_merge($contact_record, $datarray)), 'search', false, true); logger('preview: ' . $o); echo json_encode(array('preview' => $o)); killme(); } call_hooks('post_local', $datarray); if (x($datarray, 'cancel')) { logger('mod_item: post cancelled by plugin.'); if ($return_path) { goaway($a->get_baseurl() . "/" . $return_path); } $json = array('cancel' => 1); if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) { $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload']; } echo json_encode($json); killme(); } // Fill the cache field put_item_in_cache($datarray); if ($orig_post) { $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", dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['tag']), dbesc($datarray['attach']), dbesc($datarray['file']), dbesc($datarray['rendered-html']), dbesc($datarray['rendered-hash']), dbesc(datetime_convert()), dbesc(datetime_convert()), intval($post_id), intval($profile_uid)); create_tags_from_item($post_id); create_files_from_item($post_id); update_thread($post_id); // update filetags in pconfig file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category'); proc_run('php', "include/notifier.php", 'edit_post', "{$post_id}"); if (x($_REQUEST, 'return') && strlen($return_path)) { logger('return: ' . $return_path); goaway($a->get_baseurl() . "/" . $return_path); } killme(); } else { $post_id = 0; } $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,`owner-name`,`owner-link`,`owner-avatar`, `author-name`, `author-link`, `author-avatar`,\n\t\t`created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`, `tag`, `inform`, `verb`, `object-type`, `postopts`,\n\t\t`allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file`, `rendered-html`, `rendered-hash`)\n\t\tVALUES( '%s', '%s', %d, '%s', %d, %d, '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, %d, '%s', '%s', '%s')", dbesc($datarray['guid']), dbesc($datarray['extid']), intval($datarray['uid']), dbesc($datarray['type']), intval($datarray['wall']), intval($datarray['gravity']), dbesc($datarray['network']), intval($datarray['contact-id']), dbesc($datarray['owner-name']), dbesc($datarray['owner-link']), dbesc($datarray['owner-avatar']), dbesc($datarray['author-name']), dbesc($datarray['author-link']), dbesc($datarray['author-avatar']), dbesc($datarray['created']), dbesc($datarray['edited']), dbesc($datarray['commented']), dbesc($datarray['received']), dbesc($datarray['changed']), dbesc($datarray['uri']), dbesc($datarray['thr-parent']), dbesc($datarray['title']), dbesc($datarray['body']), dbesc($datarray['app']), dbesc($datarray['location']), dbesc($datarray['coord']), dbesc($datarray['tag']), dbesc($datarray['inform']), dbesc($datarray['verb']), dbesc($datarray['object-type']), dbesc($datarray['postopts']), dbesc($datarray['allow_cid']), dbesc($datarray['allow_gid']), dbesc($datarray['deny_cid']), dbesc($datarray['deny_gid']), intval($datarray['private']), intval($datarray['pubmail']), dbesc($datarray['attach']), intval($datarray['bookmark']), intval($datarray['origin']), intval($datarray['moderated']), dbesc($datarray['file']), dbesc($datarray['rendered-html']), dbesc($datarray['rendered-hash'])); $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($datarray['uri'])); if (!count($r)) { logger('mod_item: unable to retrieve post that was just stored.'); notice(t('System error. Post not saved.') . EOL); goaway($a->get_baseurl() . "/" . $return_path); // NOTREACHED } $post_id = $r[0]['id']; logger('mod_item: saved item ' . $post_id); $datarray["id"] = $post_id; $datarray["plink"] = $a->get_baseurl() . '/display/' . urlencode($datarray["guid"]); // update filetags in pconfig file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category'); if ($parent) { // This item is the last leaf and gets the comment box, clear any ancestors $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ", dbesc(datetime_convert()), intval($parent)); update_thread($parent, true); // Inherit ACLs from the parent item. $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d\n\t\t\tWHERE `id` = %d", dbesc($parent_item['allow_cid']), dbesc($parent_item['allow_gid']), dbesc($parent_item['deny_cid']), dbesc($parent_item['deny_gid']), intval($parent_item['private']), intval($post_id)); if ($contact_record != $author) { notification(array('type' => NOTIFY_COMMENT, 'notify_flags' => $user['notify-flags'], 'language' => $user['language'], 'to_name' => $user['username'], 'to_email' => $user['email'], 'uid' => $user['uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . urlencode($datarray['guid']), 'source_name' => $datarray['author-name'], 'source_link' => $datarray['author-link'], 'source_photo' => $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $parent, 'parent_uri' => $parent_item['uri'])); } // Store the comment signature information in case we need to relay to Diaspora store_diaspora_comment_sig($datarray, $author, $self ? $a->user['prvkey'] : false, $parent_item, $post_id); } else { $parent = $post_id; if ($contact_record != $author) { notification(array('type' => NOTIFY_WALL, 'notify_flags' => $user['notify-flags'], 'language' => $user['language'], 'to_name' => $user['username'], 'to_email' => $user['email'], 'uid' => $user['uid'], 'item' => $datarray, 'link' => $a->get_baseurl() . '/display/' . urlencode($datarray['guid']), 'source_name' => $datarray['author-name'], 'source_link' => $datarray['author-link'], 'source_photo' => $datarray['author-avatar'], 'verb' => ACTIVITY_POST, 'otype' => 'item')); } } // fallback so that parent always gets set to non-zero. if (!$parent) { $parent = $post_id; } $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1\n\t\tWHERE `id` = %d", intval($parent), dbesc($parent == $post_id ? $uri : $parent_item['uri']), dbesc($a->get_baseurl() . '/display/' . urlencode($datarray['guid'])), dbesc(datetime_convert()), intval($post_id)); // photo comments turn the corresponding item visible to the profile wall // This way we don't see every picture in your new photo album posted to your wall at once. // They will show up as people comment on them. if (!$parent_item['visible']) { $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d", intval($parent_item['id'])); update_thread($parent_item['id']); } // update the commented timestamp on the parent q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d", dbesc(datetime_convert()), dbesc(datetime_convert()), intval($parent)); if ($post_id != $parent) { update_thread($parent); } call_hooks('post_local_end', $datarray); if (strlen($emailcc) && $profile_uid == local_user()) { $erecips = explode(',', $emailcc); if (count($erecips)) { foreach ($erecips as $recip) { $addr = trim($recip); if (!strlen($addr)) { continue; } $disclaimer = '<hr />' . sprintf(t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username']) . '<br />'; $disclaimer .= sprintf(t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL; $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL; if (!$datarray['title'] == '') { $subject = email_header_encode($datarray['title'], 'UTF-8'); } else { $subject = email_header_encode('[Friendica]' . ' ' . sprintf(t('%s posted an update.'), $a->user['username']), 'UTF-8'); } $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />'; $html = prepare_body($datarray); $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>'; include_once 'include/html2plain.php'; $params = array('fromName' => $a->user['username'], 'fromEmail' => $a->user['email'], 'toEmail' => $addr, 'replyTo' => $a->user['email'], 'messageSubject' => $subject, 'htmlVersion' => $message, 'textVersion' => html2plain($html . $disclaimer)); Emailer::send($params); } } } create_tags_from_item($post_id); create_files_from_item($post_id); if ($post_id == $parent) { add_thread($post_id); } // This is a real juggling act on shared hosting services which kill your processes // e.g. dreamhost. We used to start delivery to our native delivery agents in the background // and then run our plugin delivery from the foreground. We're now doing plugin delivery first, // because as soon as you start loading up a bunch of remote delivey processes, *this* page is // likely to get killed off. If you end up looking at an /item URL and a blank page, // it's very likely the delivery got killed before all your friends could be notified. // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting, // or cut back on plugins which do remote deliveries. proc_run('php', "include/notifier.php", $notify_type, "{$post_id}"); logger('post_complete'); item_post_return($a->get_baseurl(), $api_source, $return_path); // NOTREACHED }
function format_ical_text($s) { require_once 'include/bbcode.php'; require_once 'include/html2plain.php'; return wordwrap(str_replace(',', '\\,', html2plain(bbcode($s))), 72, "\n ", true); }
function wppost_send(&$a, &$b) { if ($b['deleted'] || $b['private'] || $b['created'] !== $b['edited']) { return; } if (!strstr($b['postopts'], 'wppost')) { return; } if ($b['parent'] != $b['id']) { return; } $wp_username = xmlify(get_pconfig($b['uid'], 'wppost', 'wp_username')); $wp_password = xmlify(get_pconfig($b['uid'], 'wppost', 'wp_password')); $wp_blog = get_pconfig($b['uid'], 'wppost', 'wp_blog'); if ($wp_username && $wp_password && $wp_blog) { require_once 'include/bbcode.php'; require_once 'include/html2plain.php'; // If the title is empty then try to guess if ($b['title'] == '') { // Take the description from the bookmark if (preg_match("/\\[bookmark\\=([^\\]]*)\\](.*?)\\[\\/bookmark\\]/is", $b['body'], $matches)) { $b['title'] = $matches[2]; } // If no bookmark is found then take the first line if ($b['title'] == '') { $title = html2plain(bbcode($b['body']), 0, true); $pos = strpos($title, "\n"); if ($pos == 0 or $pos > 60) { $pos = 60; } $b['title'] = substr($title, 0, $pos); } } $title = '<title>' . ($b['title'] ? $b['title'] : t('Post from Friendica')) . '</title>'; $post = $title . bbcode($b['body']); $wp_backlink = intval(get_pconfig($b['uid'], 'wppost', 'backlink')); if ($wp_backlink && $b['plink']) { $post .= EOL . EOL . '<a href="' . $b['plink'] . '">' . t('Read the original post and comment stream on Friendica') . '</a>' . EOL . EOL; } $post = xmlify($post); $xml = <<<EOT <?xml version=\\"1.0\\" encoding=\\"utf-8\\"?> <methodCall> <methodName>blogger.newPost</methodName> <params> <param><value><string/></value></param> <param><value><string/></value></param> <param><value><string>{$wp_username}</string></value></param> <param><value><string>{$wp_password}</string></value></param> <param><value><string>{$post}</string></value></param> <param><value><int>1</int></value></param> </params> </methodCall> EOT; logger('wppost: data: ' . $xml, LOGGER_DATA); if ($wp_blog !== 'test') { $x = post_url($wp_blog, $xml); } logger('posted to wordpress: ' . ($x ? $x : ''), LOGGER_DEBUG); } }
function api_convert_item($item) { $body = $item['body']; $attachments = api_get_attachments($body); // Workaround for ostatus messages where the title is identically to the body $html = bbcode(api_clean_plain_items($body), false, false, 2, true); $statusbody = trim(html2plain($html, 0)); // handle data: images $statusbody = api_format_items_embeded_images($item, $statusbody); $statustitle = trim($item['title']); if ($statustitle != '' and strpos($statusbody, $statustitle) !== false) { $statustext = trim($statusbody); } else { $statustext = trim($statustitle . "\n\n" . $statusbody); } if ($item["network"] == NETWORK_FEED and strlen($statustext) > 1000) { $statustext = substr($statustext, 0, 1000) . "... \n" . $item["plink"]; } $statushtml = trim(bbcode($body, false, false)); if ($item['title'] != "") { $statushtml = "<h4>" . bbcode($item['title']) . "</h4>\n" . $statushtml; } $entities = api_get_entitities($statustext, $body); return array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities); }
function store_doc_file($s) { if (is_dir($s)) { return; } $item = array(); $sys = get_sys_channel(); $item['aid'] = 0; $item['uid'] = $sys['channel_id']; if (strpos($s, '.md')) { $mimetype = 'text/markdown'; } elseif (strpos($s, '.html')) { $mimetype = 'text/html'; } else { $mimetype = 'text/bbcode'; } require_once 'include/html2plain.php'; $item['body'] = html2plain(prepare_text(file_get_contents($s), $mimetype, true)); $item['mimetype'] = 'text/plain'; $item['plink'] = z_root() . '/' . str_replace('doc', 'help', $s); $item['owner_xchan'] = $item['author_xchan'] = $sys['channel_hash']; $item['item_type'] = ITEM_TYPE_DOC; $r = q("select item.* from item left join item_id on item.id = item_id.iid where service = 'docfile' and\n\t\tsid = '%s' and item_type = %d limit 1", dbesc($s), intval(ITEM_TYPE_DOC)); if ($r) { $item['id'] = $r[0]['id']; $item['mid'] = $item['parent_mid'] = $r[0]['mid']; $x = item_store_update($item); } else { $item['mid'] = $item['parent_mid'] = item_message_id(); $x = item_store($item); } if ($x['success']) { update_remote_id($sys, $x['item_id'], ITEM_TYPE_DOC, $s, 'docfile', 0, $item['mid']); } }
function api_format_items($r, $user_info, $filter_user = false) { $a = get_app(); $ret = array(); foreach ($r as $item) { api_share_as_retweet($a, api_user(), $item); localize_item($item); $status_user = api_item_get_user($a, $item); // Look if the posts are matching if they should be filtered by user id if ($filter_user and $status_user["id"] != $user_info["id"]) { continue; } if ($item['thr-parent'] != $item['uri']) { $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1", intval(api_user()), dbesc($item['thr-parent'])); if ($r) { $in_reply_to_status_id = intval($r[0]['id']); } else { $in_reply_to_status_id = intval($item['parent']); } $in_reply_to_status_id_str = (string) intval($item['parent']); $in_reply_to_screen_name = NULL; $in_reply_to_user_id = NULL; $in_reply_to_user_id_str = NULL; $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1", intval(api_user()), intval($in_reply_to_status_id)); if ($r) { $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link']))); if ($r) { if ($r[0]['nick'] == "") { $r[0]['nick'] = api_get_nick($r[0]["url"]); } $in_reply_to_screen_name = $r[0]['nick'] ? $r[0]['nick'] : $r[0]['name']; $in_reply_to_user_id = intval($r[0]['id']); $in_reply_to_user_id_str = (string) intval($r[0]['id']); } } } else { $in_reply_to_screen_name = NULL; $in_reply_to_user_id = NULL; $in_reply_to_status_id = NULL; $in_reply_to_user_id_str = NULL; $in_reply_to_status_id_str = NULL; } // Workaround for ostatus messages where the title is identically to the body //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0)); $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true); $statusbody = trim(html2plain($html, 0)); $statustitle = trim($item['title']); if ($statustitle != '' and strpos($statusbody, $statustitle) !== false) { $statustext = trim($statusbody); } else { $statustext = trim($statustitle . "\n\n" . $statusbody); } if ($item["network"] == NETWORK_FEED and strlen($statustext) > 1000) { $statustext = substr($statustext, 0, 1000) . "... \n" . $item["plink"]; } $status = array('text' => $statustext, 'truncated' => False, 'created_at' => api_date($item['created']), 'in_reply_to_status_id' => $in_reply_to_status_id, 'in_reply_to_status_id_str' => $in_reply_to_status_id_str, 'source' => $item['app'] ? $item['app'] : 'web', 'id' => intval($item['id']), 'id_str' => (string) intval($item['id']), 'in_reply_to_user_id' => $in_reply_to_user_id, 'in_reply_to_user_id_str' => $in_reply_to_user_id_str, 'in_reply_to_screen_name' => $in_reply_to_screen_name, 'geo' => NULL, 'favorited' => $item['starred'] ? true : false, 'user' => $status_user, 'statusnet_html' => trim(bbcode($item['body'], false, false)), 'statusnet_conversation_id' => $item['parent']); if ($item['title'] != "") { $status['statusnet_html'] = "<h4>" . bbcode($item['title']) . "</h4>\n" . $status['statusnet_html']; } $entities = api_get_entitities($status['text'], $item['body']); if (count($entities) > 0) { $status['entities'] = $entities; } if ($item['item_network'] != "" and $status["source"] == 'web') { $status["source"] = network_to_name($item['item_network']); } else { if ($item['item_network'] != "" and network_to_name($item['item_network']) != $status["source"]) { $status["source"] = trim($status["source"] . ' (' . network_to_name($item['item_network']) . ')'); } } // Retweets are only valid for top postings // It doesn't work reliable with the link if its a feed $IsRetweet = $item['owner-link'] != $item['author-link']; if ($IsRetweet) { $IsRetweet = ($item['owner-name'] != $item['author-name'] or $item['owner-avatar'] != $item['author-avatar']); } if ($IsRetweet and $item["id"] == $item["parent"]) { $retweeted_status = $status; $retweeted_status["user"] = api_get_user($a, $item["author-link"]); $status["retweeted_status"] = $retweeted_status; } // "uid" and "self" are only needed for some internal stuff, so remove it from here unset($status["user"]["uid"]); unset($status["user"]["self"]); // 'geo' => array('type' => 'Point', // 'coordinates' => array((float) $notice->lat, // (float) $notice->lon)); $ret[] = $status; } return $ret; }
function email_send($addr, $subject, $headers, $item) { //$headers .= 'MIME-Version: 1.0' . "\n"; //$headers .= 'Content-Type: text/html; charset=UTF-8' . "\n"; //$headers .= 'Content-Type: text/plain; charset=UTF-8' . "\n"; //$headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n"; $part = uniqid("", true); $html = prepare_body($item); $headers .= "Mime-Version: 1.0\n"; $headers .= 'Content-Type: multipart/alternative; boundary="=_' . $part . '"' . "\n\n"; $body = "\n--=_" . $part . "\n"; $body .= "Content-Transfer-Encoding: 8bit\n"; $body .= "Content-Type: text/plain; charset=utf-8; format=flowed\n\n"; $body .= html2plain($html) . "\n"; $body .= "--=_" . $part . "\n"; $body .= "Content-Transfer-Encoding: 8bit\n"; $body .= "Content-Type: text/html; charset=utf-8\n\n"; $body .= '<html><head></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; ">' . $html . "</body></html>\n"; $body .= "--=_" . $part . "--"; //$message = '<html><body>' . $html . '</body></html>'; //$message = html2plain($html); logger('notifier: email delivery to ' . $addr); mail($addr, $subject, $body, $headers); }
function plaintext($a, $b, $limit = 0, $includedlinks = false, $htmlmode = 2) { require_once "include/bbcode.php"; require_once "include/html2plain.php"; require_once "include/network.php"; // At first look at data that is attached via "type-..." stuff // This will hopefully replaced with a dedicated bbcode later $post = get_attached_data($b["body"]); if ($b["title"] != "" and $post["text"] != "") { $post["text"] = trim($b["title"] . "\n\n" . $post["text"]); } elseif ($b["title"] != "") { $post["text"] = trim($b["title"]); } $html = bbcode($post["text"], false, false, $htmlmode); $msg = html2plain($html, 0, true); $msg = trim(html_entity_decode($msg, ENT_QUOTES, 'UTF-8')); $link = ""; if ($includedlinks) { if ($post["type"] == "link") { $link = $post["url"]; } elseif ($post["type"] == "video") { $link = $post["url"]; } elseif ($post["type"] == "photo") { $link = $post["image"]; } if ($msg == "" and isset($post["title"])) { $msg = trim($post["title"]); } if ($msg == "" and isset($post["description"])) { $msg = trim($post["description"]); } // If the link is already contained in the post, then it neeedn't to be added again // But: if the link is beyond the limit, then it has to be added. if ($link != "" and strstr($msg, $link)) { $pos = strpos($msg, $link); if ($limit == 0 or $pos < $limit) { $link = ""; } } } if ($limit > 0) { // Reduce multiple spaces // When posted to a network with limited space, we try to gain space where possible while (strpos($msg, " ") !== false) { $msg = str_replace(" ", " ", $msg); } // Twitter is using its own limiter, so we always assume that shortened links will have this length if (iconv_strlen($link, "UTF-8") > 0) { $limit = $limit - 23; } if (iconv_strlen($msg, "UTF-8") > $limit) { if (!isset($post["url"])) { $limit = $limit - 23; $post["url"] = $b["plink"]; } elseif (strpos($b["body"], "[share") !== false) { $post["url"] = $b["plink"]; } elseif (get_pconfig($b["uid"], "system", "no_intelligent_shortening")) { $post["url"] = $b["plink"]; } $msg = shortenmsg($msg, $limit); } } $post["text"] = trim($msg); return $post; }
function format_ical_text($s) { require_once 'include/bbcode.php'; require_once 'include/html2plain.php'; $s = html2plain(bbcode($s)); $s = str_replace(["\r\n", "\n"], ["", ""], $s); return wordwrap(str_replace(['\\', ',', ';'], ['\\\\', '\\,', '\\;'], $s), 72, "\r\n ", true); }
function wppost_send(&$a, &$b) { if ($b['deleted'] || $b['private'] || $b['created'] !== $b['edited']) { return; } if (!strstr($b['postopts'], 'wppost')) { return; } if ($b['parent'] != $b['id']) { return; } $wp_username = xmlify(get_pconfig($b['uid'], 'wppost', 'wp_username')); $wp_password = xmlify(get_pconfig($b['uid'], 'wppost', 'wp_password')); $wp_blog = get_pconfig($b['uid'], 'wppost', 'wp_blog'); if ($wp_username && $wp_password && $wp_blog) { require_once 'include/bbcode.php'; require_once 'include/html2plain.php'; require_once 'include/plaintext.php'; $wptitle = trim($b['title']); if (intval(get_pconfig($b['uid'], 'wppost', 'shortcheck'))) { // Checking, if its a post that is worth a blog post $postentry = false; $siteinfo = get_attached_data($b["body"]); // Is it a link to an aricle, a video or a photo? if (isset($siteinfo["type"])) { if (in_array($siteinfo["type"], array("link", "audio", "video", "photo"))) { $postentry = true; } } // Does it have a title? if ($wptitle != "") { $postentry = true; } // Is it larger than 500 characters? if (strlen($b['body']) > 500) { $postentry = true; } if (!$postentry) { return; } } // If the title is empty then try to guess if ($wptitle == '') { // Fetch information about the post $siteinfo = get_attached_data($b["body"]); if (isset($siteinfo["title"])) { $wptitle = $siteinfo["title"]; } // If no bookmark is found then take the first line if ($wptitle == '') { // Remove the share element before fetching the first line $title = trim(preg_replace("/\\[share.*?\\](.*?)\\[\\/share\\]/ism", "\n\$1\n", $b['body'])); $title = html2plain(bbcode($title, false, false), 0, true) . "\n"; $pos = strpos($title, "\n"); $trailer = ""; if ($pos == 0 or $pos > 100) { $pos = 100; $trailer = "..."; } $wptitle = substr($title, 0, $pos) . $trailer; } } $title = '<title>' . ($wptitle ? $wptitle : t('Post from Friendica')) . '</title>'; $post = bbcode($b['body'], false, false, 4); // If a link goes to youtube then remove the stuff around it. Wordpress detects youtube links and embeds it $post = preg_replace('/<a.*?href="(https?:\\/\\/www.youtube.com\\/.*?)".*?>(.*?)<\\/a>/ism', "\n\$1\n", $post); $post = preg_replace('/<a.*?href="(https?:\\/\\/youtu.be\\/.*?)".*?>(.*?)<\\/a>/ism', "\n\$1\n", $post); $post = $title . $post; $wp_backlink = intval(get_pconfig($b['uid'], 'wppost', 'backlink')); if ($wp_backlink && $b['plink']) { $post .= EOL . EOL . '<a href="' . $b['plink'] . '">' . t('Read the original post and comment stream on Friendica') . '</a>' . EOL . EOL; } $post = xmlify($post); $xml = <<<EOT <?xml version=\\"1.0\\" encoding=\\"utf-8\\"?> <methodCall> <methodName>blogger.newPost</methodName> <params> <param><value><string/></value></param> <param><value><string/></value></param> <param><value><string>{$wp_username}</string></value></param> <param><value><string>{$wp_password}</string></value></param> <param><value><string>{$post}</string></value></param> <param><value><int>1</int></value></param> </params> </methodCall> EOT; logger('wppost: data: ' . $xml, LOGGER_DATA); if ($wp_blog !== 'test') { $x = post_url($wp_blog, $xml); } logger('posted to wordpress: ' . ($x ? $x : ''), LOGGER_DEBUG); } }
/** * @param App $a * @param object $b * @return mixed */ function facebook_post_hook(&$a, &$b) { if ($b['deleted'] || $b['created'] !== $b['edited']) { return; } /** * Post to Facebook stream */ require_once 'include/group.php'; require_once 'include/html2plain.php'; logger('Facebook post'); $reply = false; $likes = false; $deny_arr = array(); $allow_arr = array(); $toplevel = $b['id'] == $b['parent'] ? true : false; $linking = get_pconfig($b['uid'], 'facebook', 'no_linking') ? 0 : 1; if (!$toplevel && $linking) { $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($b['parent']), intval($b['uid'])); if (count($r) && substr($r[0]['uri'], 0, 4) === 'fb::') { $reply = substr($r[0]['uri'], 4); } elseif (count($r) && substr($r[0]['extid'], 0, 4) === 'fb::') { $reply = substr($r[0]['extid'], 4); } else { return; } $u = q("SELECT * FROM user where uid = %d limit 1", intval($b['uid'])); if (!count($u)) { return; } // only accept comments from the item owner. Other contacts are unknown to FB. if (!link_compare($b['author-link'], $a->get_baseurl() . '/profile/' . $u[0]['nickname'])) { return; } logger('facebook reply id=' . $reply); } if (strstr($b['postopts'], 'facebook') || $b['private'] || $reply) { if ($b['private'] && $reply === false) { $allow_people = expand_acl($b['allow_cid']); $allow_groups = expand_groups(expand_acl($b['allow_gid'])); $deny_people = expand_acl($b['deny_cid']); $deny_groups = expand_groups(expand_acl($b['deny_gid'])); $recipients = array_unique(array_merge($allow_people, $allow_groups)); $deny = array_unique(array_merge($deny_people, $deny_groups)); $allow_str = dbesc(implode(', ', $recipients)); if ($allow_str) { $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( {$allow_str} ) AND `network` = 'face'"); if (count($r)) { foreach ($r as $rr) { $allow_arr[] = $rr['notify']; } } } $deny_str = dbesc(implode(', ', $deny)); if ($deny_str) { $r = q("SELECT `notify` FROM `contact` WHERE `id` IN ( {$deny_str} ) AND `network` = 'face'"); if (count($r)) { foreach ($r as $rr) { $deny_arr[] = $rr['notify']; } } } if (count($deny_arr) && !count($allow_arr)) { // One or more FB folks were denied access but nobody on FB was specifically allowed access. // This might cause the post to be open to public on Facebook, but only to selected members // on another network. Since this could potentially leak a post to somebody who was denied, // we will skip posting it to Facebook with a slightly vague but relevant message that will // hopefully lead somebody to this code comment for a better explanation of what went wrong. notice(t('Post to Facebook cancelled because of multi-network access permission conflict.') . EOL); return; } // if it's a private message but no Facebook members are allowed or denied, skip Facebook post if (!count($allow_arr) && !count($deny_arr)) { return; } } if ($b['verb'] == ACTIVITY_LIKE) { $likes = true; } $appid = get_config('facebook', 'appid'); $secret = get_config('facebook', 'appsecret'); if ($appid && $secret) { logger('facebook: have appid+secret'); $fb_token = get_pconfig($b['uid'], 'facebook', 'access_token'); // post to facebook if it's a public post and we've ticked the 'post to Facebook' box, // or it's a private message with facebook participants // or it's a reply or likes action to an existing facebook post if ($fb_token && ($toplevel || $b['private'] || $reply)) { logger('facebook: able to post'); require_once 'library/facebook.php'; require_once 'include/bbcode.php'; $msg = $b['body']; logger('Facebook post: original msg=' . $msg, LOGGER_DATA); // make links readable before we strip the code // unless it's a dislike - just send the text as a comment // if($b['verb'] == ACTIVITY_DISLIKE) // $msg = trim(strip_tags(bbcode($msg))); // Old code /*$search_str = $a->get_baseurl() . '/search'; if(preg_match("/\[url=(.*?)\](.*?)\[\/url\]/is",$msg,$matches)) { // don't use hashtags for message link if(strpos($matches[2],$search_str) === false) { $link = $matches[1]; if(substr($matches[2],0,5) != '[img]') $linkname = $matches[2]; } } // strip tag links to avoid link clutter, this really should be // configurable because we're losing information $msg = preg_replace("/\#\[url=(.*?)\](.*?)\[\/url\]/is",'#$2',$msg); // provide the link separately for normal links $msg = preg_replace("/\[url=(.*?)\](.*?)\[\/url\]/is",'$2 $1',$msg); if(preg_match("/\[img\](.*?)\[\/img\]/is",$msg,$matches)) $image = $matches[1]; $msg = preg_replace("/\[img\](.*?)\[\/img\]/is", t('Image: ') . '$1', $msg); if((strpos($link,z_root()) !== false) && (! $image)) $image = $a->get_baseurl() . '/images/friendica-64.jpg'; $msg = trim(strip_tags(bbcode($msg)));*/ // New code // Looking for the first image $image = ''; if (preg_match("/\\[img\\=([0-9]*)x([0-9]*)\\](.*?)\\[\\/img\\]/is", $b['body'], $matches)) { $image = $matches[3]; } if ($image == '') { if (preg_match("/\\[img\\](.*?)\\[\\/img\\]/is", $b['body'], $matches)) { $image = $matches[1]; } } // Checking for a bookmark element $body = $b['body']; if (strpos($body, "[bookmark") !== false) { // splitting the text in two parts: // before and after the bookmark $pos = strpos($body, "[bookmark"); $body1 = substr($body, 0, $pos); $body2 = substr($body, $pos); // Removing the bookmark and all quotes after the bookmark // they are mostly only the content after the bookmark. $body2 = preg_replace("/\\[bookmark\\=([^\\]]*)\\](.*?)\\[\\/bookmark\\]/ism", '', $body2); $body2 = preg_replace("/\\[quote\\=([^\\]]*)\\](.*?)\\[\\/quote\\]/ism", '', $body2); $body2 = preg_replace("/\\[quote\\](.*?)\\[\\/quote\\]/ism", '', $body2); $body = $body1 . $body2; } // At first convert the text to html $html = bbcode($body); // Then convert it to plain text $msg = trim($b['title'] . " \n\n" . html2plain($html, 0, true)); $msg = html_entity_decode($msg, ENT_QUOTES, 'UTF-8'); // Removing multiple newlines while (strpos($msg, "\n\n\n") !== false) { $msg = str_replace("\n\n\n", "\n\n", $msg); } // add any attachments as text urls $arr = explode(',', $b['attach']); if (count($arr)) { $msg .= "\n"; foreach ($arr as $r) { $matches = false; $cnt = preg_match('|\\[attach\\]href=\\"(.*?)\\" size=\\"(.*?)\\" type=\\"(.*?)\\" title=\\"(.*?)\\"\\[\\/attach\\]|', $r, $matches); if ($cnt) { $msg .= "\n" . $matches[1]; } } } $link = ''; $linkname = ''; // look for bookmark-bbcode and handle it with priority if (preg_match("/\\[bookmark\\=([^\\]]*)\\](.*?)\\[\\/bookmark\\]/is", $b['body'], $matches)) { $link = $matches[1]; $linkname = $matches[2]; } // If there is no bookmark element then take the first link if ($link == '') { $links = collecturls($html); if (sizeof($links) > 0) { reset($links); $link = current($links); } } // Remove trailing and leading spaces $msg = trim($msg); // Since facebook increased the maxpostlen massively this never should happen again :) if (strlen($msg) > FACEBOOK_MAXPOSTLEN) { require_once 'library/slinky.php'; $display_url = $b['plink']; $slinky = new Slinky($display_url); // setup a cascade of shortening services // try to get a short link from these services // in the order ur1.ca, trim, id.gd, tinyurl $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL())); $shortlink = $slinky->short(); // the new message will be shortened such that "... $shortlink" // will fit into the character limit $msg = substr($msg, 0, FACEBOOK_MAXPOSTLEN - strlen($shortlink) - 4); $msg .= '... ' . $shortlink; } // Fallback - if message is empty if (!strlen($msg)) { $msg = $link; } if (!strlen($msg)) { $msg = $image; } if (!strlen($msg)) { $msg = $linkname; } // If there is nothing to post then exit if (!strlen($msg)) { return; } logger('Facebook post: msg=' . $msg, LOGGER_DATA); if ($likes) { $postvars = array('access_token' => $fb_token); } else { $postvars = array('access_token' => $fb_token, 'message' => $msg); if (isset($image)) { $postvars['picture'] = $image; //$postvars['type'] = "photo"; } if (isset($link)) { $postvars['link'] = $link; //$postvars['type'] = "link"; } if (isset($linkname)) { $postvars['name'] = $linkname; } } if ($b['private'] && $toplevel) { $postvars['privacy'] = '{"value": "CUSTOM", "friends": "SOME_FRIENDS"'; if (count($allow_arr)) { $postvars['privacy'] .= ',"allow": "' . implode(',', $allow_arr) . '"'; } if (count($deny_arr)) { $postvars['privacy'] .= ',"deny": "' . implode(',', $deny_arr) . '"'; } $postvars['privacy'] .= '}'; } if ($reply) { $url = 'https://graph.facebook.com/' . $reply . '/' . ($likes ? 'likes' : 'comments'); } else { if ($link != "" or $image != "" or $b['title'] == '' or strlen($msg) < 500) { $url = 'https://graph.facebook.com/me/feed'; if ($b['plink']) { $postvars['actions'] = '{"name": "' . t('View on Friendica') . '", "link": "' . $b['plink'] . '"}'; } } else { // if its only a message and a subject and the message is larger than 500 characters then post it as note $postvars = array('access_token' => $fb_token, 'message' => bbcode($b['body']), 'subject' => $b['title']); $url = 'https://graph.facebook.com/me/notes'; } } logger('facebook: post to ' . $url); logger('facebook: postvars: ' . print_r($postvars, true)); // "test_mode" prevents anything from actually being posted. // Otherwise, let's do it. if (!get_config('facebook', 'test_mode')) { $x = post_url($url, $postvars); logger('Facebook post returns: ' . $x, LOGGER_DEBUG); $retj = json_decode($x); if ($retj->id) { q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d LIMIT 1", dbesc('fb::' . $retj->id), intval($b['id'])); } else { if (!$likes) { $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars)); require_once 'include/queue_fn.php'; add_to_queue($a->contact, NETWORK_FACEBOOK, $s); notice(t('Facebook post failed. Queued for retry.') . EOL); } if (isset($retj->error) && $retj->error->type == "OAuthException" && $retj->error->code == 190) { logger('Facebook session has expired due to changed password.', LOGGER_DEBUG); $last_notification = get_pconfig($b['uid'], 'facebook', 'session_expired_mailsent'); if (!$last_notification || $last_notification < time() - FACEBOOK_SESSION_ERR_NOTIFICATION_INTERVAL) { require_once 'include/enotify.php'; $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($b['uid'])); notification(array('uid' => $b['uid'], 'type' => NOTIFY_SYSTEM, 'system_type' => 'facebook_connection_invalid', 'language' => $r[0]['language'], 'to_name' => $r[0]['username'], 'to_email' => $r[0]['email'], 'source_name' => t('Administrator'), 'source_link' => $a->config["system"]["url"], 'source_photo' => $a->config["system"]["url"] . '/images/person-80.jpg')); set_pconfig($b['uid'], 'facebook', 'session_expired_mailsent', time()); } else { logger('Facebook: No notification, as the last one was sent on ' . $last_notification, LOGGER_DEBUG); } } } } } } } }
/** * * Cron function used to regularly check all users on the server with active windowsphonepushplugin and send * notifications to the Microsoft servers and consequently to the Windows Phone device * */ function windowsphonepush_cron() { // retrieve all UID's for which the plugin windowsphonepush is enabled and loop through every user $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'windowsphonepush' AND `k` = 'enable' AND `v` = 1"); if (count($r)) { foreach ($r as $rr) { // load stored information for the user-id of the current loop $device_url = get_pconfig($rr['uid'], 'windowsphonepush', 'device_url'); $lastpushid = get_pconfig($rr['uid'], 'windowsphonepush', 'lastpushid'); // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent // by app if user has switched the server setting in app - sending blank not possible as this would return an update error) if ($device_url == "" || $device_url == "NA") { // no Device-URL for the user availabe, but plugin is enabled --> write info to Logger logger("WARN: windowsphonepush is enable for user " . $rr['uid'] . ", but no Device-URL is specified for the user."); } else { // retrieve the number of unseen items and the id of the latest one (if there are more than // one new entries since last poller run, only the latest one will be pushed) $count = q("SELECT count(`id`) as count, max(`id`) as max FROM `item` WHERE `unseen` = 1 AND `type` <> 'activity' AND `uid` = %d", intval($rr['uid'])); // send number of unseen items to the device (the number will be displayed on Start screen until // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if // user has loaded the timeline through app or website $res_tile = send_tile_update($device_url, "", $count[0]['count'], ""); switch (trim($res_tile)) { case "Received": // ok, count has been pushed, let's save it in personal settings set_pconfig($rr['uid'], 'windowsphonepush', 'counterunseen', $count[0]['count']); break; case "QueueFull": // maximum of 30 messages reached, server rejects any further push notification until device reconnects logger("INFO: Device-URL '" . $device_url . "' returns a QueueFull."); break; case "Suppressed": // notification received and dropped as something in app was not enabled logger("WARN. Device-URL '" . $device_url . "' returns a Suppressed. Unexpected error in Mobile App?"); break; case "Dropped": // mostly combines with Expired, in that case Device-URL will be deleted from pconfig (function send_push) break; default: // error, mostly called by "" which means that the url (not "" which has been checked) // didn't not received Microsoft Notification Server -> wrong url logger("ERROR: specified Device-URL '" . $device_url . "' didn't produced any response."); } // additionally user receives the text of the newest item (function checks against last successfully pushed item) if (intval($count[0]['max']) > intval($lastpushid)) { // user can define if he wants to see the text of the item in the push notification // this has been implemented as the device_url is not a https uri (not so secure) $senditemtext = get_pconfig($rr['uid'], 'windowsphonepush', 'senditemtext'); if ($senditemtext == 1) { // load item with the max id $item = q("SELECT `author-name` as author, `body` as body FROM `item` where `id` = %d", intval($count[0]['max'])); // as user allows to send the item, we want to show the sender of the item in the toast // toasts are limited to one line, therefore place is limited - author shall be in // max. 15 chars (incl. dots); author is displayed in bold font $author = $item[0]['author']; $author = strlen($author) > 12 ? substr($author, 0, 12) . "..." : $author; // normally we show the body of the item, however if it is an url or an image we cannot // show this in the toast (only test), therefore changing to an alternate text // Otherwise BBcode-Tags will be eliminated and plain text cutted to 140 chars (incl. dots) // BTW: information only possible in English $body = $item[0]['body']; if (substr($body, 0, 4) == "[url") { $body = "URL/Image ..."; } else { require_once 'include/bbcode.php'; require_once "include/html2plain.php"; $body = bbcode($body, false, false, 2, true); $body = html2plain($body, 0); $body = strlen($body) > 137 ? substr($body, 0, 137) . "..." : $body; } } else { // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived" $author = "Friendica"; $body = "New timeline entry arrived ..."; } // only if toast push notification returns the Notification status "Received" we will update th settings with the // new indicator max-id is checked against (QueueFull, Suppressed, N/A, Dropped shall qualify to resend // the push notification some minutes later (BTW: if resulting in Expired for subscription status the // device_url will be deleted (no further try on this url, see send_push) // further log information done on count pushing with send_tile (see above) $res_toast = send_toast($device_url, $author, $body); if (trim($res_toast) === 'Received') { set_pconfig($rr['uid'], 'windowsphonepush', 'lastpushid', $count[0]['max']); } } } } } }
/** * @function check_item_source($uid,$item) * @param $uid * @param $item * * @description * Checks to see if this item owner is referenced as a source for this channel and if the post * matches the rules for inclusion in this channel. Returns true if we should create a second delivery * chain and false if none of the rules apply, or if the item is private. */ function check_item_source($uid, $item) { $r = q("select * from source where src_channel_id = %d and ( src_xchan = '%s' || src_xchan = '*' ) limit 1", intval($uid), dbesc($item['source_xchan'] ? $item['source_xchan'] : $item['owner_xchan'])); if (!$r) { return false; } $x = q("select abook_their_perms, abook_flags from abook where abook_channel = %d and abook_xchan = '%s' limit 1", intval($uid), dbesc($item['owner_xchan'])); if (!$x) { return false; } if (!($x[0]['abook_their_perms'] & PERMS_A_REPUBLISH)) { return false; } if ($item['item_private'] && !($x[0]['abook_flags'] & ABOOK_FLAG_FEED)) { return false; } if ($r[0]['src_channel_xchan'] === $item['owner_xchan']) { return false; } if (!$r[0]['src_patt']) { return true; } require_once 'include/html2plain.php'; $text = prepare_text($item['body'], $item['mimetype']); $text = html2plain($text); $tags = count($items['term']) ? $items['term'] : false; $words = explode("\n", $r[0]['src_patt']); if ($words) { foreach ($words as $word) { if (substr($word, 0, 1) === '#' && $tags) { foreach ($tags as $t) { if ($t['type'] == TERM_HASHTAG && (substr($t, 1) === substr($word, 1) || substr($word, 1) === '*')) { return true; } } } if (stristr($text, $word) !== false) { return true; } } } return false; }
function fbpost_prepare_body(&$a, &$b) { if ($b["item"]["network"] != NETWORK_FACEBOOK) { return; } if ($b["preview"]) { $msg = $b["item"]["body"]; require_once "include/bbcode.php"; require_once "include/html2plain.php"; $msg = bb_CleanPictureLinks($msg); $msg = bbcode($msg, false, false, 2, true); $msg = trim(html2plain($msg, 0)); $b['html'] = nl2br(htmlspecialchars($msg)); } }
function store_doc_file($s) { if (is_dir($s)) { return; } $item = array(); $sys = get_sys_channel(); $item['aid'] = 0; $item['uid'] = $sys['channel_id']; if (strpos($s, '.md')) { $mimetype = 'text/markdown'; } elseif (strpos($s, '.html')) { $mimetype = 'text/html'; } else { $mimetype = 'text/bbcode'; } require_once 'include/html2plain.php'; $item['body'] = html2plain(prepare_text(file_get_contents($s), $mimetype, true)); $item['mimetype'] = 'text/plain'; $item['plink'] = z_root() . '/' . str_replace('doc', 'help', $s); $item['owner_xchan'] = $item['author_xchan'] = $sys['channel_hash']; $item['item_type'] = ITEM_TYPE_DOC; $r = q("select item.* from item left join iconfig on item.id = iconfig.iid \n\t\twhere iconfig.cat = 'system' and iconfig.k = 'docfile' and\n\t\ticonfig.v = '%s' and item_type = %d limit 1", dbesc($s), intval(ITEM_TYPE_DOC)); \Zotlabs\Lib\IConfig::Set($item, 'system', 'docfile', $s); if ($r) { $item['id'] = $r[0]['id']; $item['mid'] = $item['parent_mid'] = $r[0]['mid']; $x = item_store_update($item); } else { $item['mid'] = $item['parent_mid'] = item_message_id(); $x = item_store($item); } return $x; }
function api_format_items($r, $user_info) { //logger('api_format_items: ' . print_r($r,true)); //logger('api_format_items: ' . print_r($user_info,true)); $a = get_app(); $ret = array(); foreach ($r as $item) { localize_item($item); $status_user = $item['cid'] == $user_info['id'] ? $user_info : api_item_get_user($a, $item); if ($item['parent'] != $item['id']) { $r = q("select id from item where parent=%s and id<%s order by id desc limit 1", intval($item['parent']), intval($item['id'])); if ($r) { $in_reply_to_status_id = $r[0]['id']; } else { $in_reply_to_status_id = $item['parent']; } $r = q("select `item`.`contact-id`, `contact`.nick, `item`.`author-name` from item, contact\n\t\t\t\t\twhere `contact`.`id` = `item`.`contact-id` and `item`.id=%d", intval($in_reply_to_status_id)); $in_reply_to_screen_name = $r[0]['author-name']; $in_reply_to_user_id = $r[0]['contact-id']; } else { $in_reply_to_screen_name = ''; $in_reply_to_user_id = 0; $in_reply_to_status_id = 0; } // Workaround for ostatus messages where the title is identically to the body $statusbody = trim(html2plain(bbcode($item['body'], false, false, true), 0)); $statustitle = trim($item['title']); if ($statustitle != '' and strpos($statusbody, $statustitle) !== false) { $statustext = trim($statusbody); } else { $statustext = trim($statustitle . "\n\n" . $statusbody); } if ($item["network"] == NETWORK_FEED and strlen($statustext) > 1000) { $statustext = substr($statustext, 0, 1000) . "... \n" . $item["plink"]; } $status = array('text' => $statustext, 'truncated' => False, 'created_at' => api_date($item['created']), 'in_reply_to_status_id' => $in_reply_to_status_id, 'source' => $item['app'] ? $item['app'] : 'web', 'id' => intval($item['id']), 'in_reply_to_user_id' => $in_reply_to_user_id, 'in_reply_to_screen_name' => $in_reply_to_screen_name, 'geo' => '', 'favorited' => $item['starred'] ? true : false, 'user' => $status_user, 'statusnet_html' => trim(bbcode($item['body'])), 'statusnet_conversation_id' => $item['parent']); // Seesmic doesn't like the following content if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') { $status2 = array('updated' => api_date($item['edited']), 'published' => api_date($item['created']), 'message_id' => $item['uri'], 'url' => $item['plink'] != '' ? $item['plink'] : $item['author-link'], 'coordinates' => $item['coord'], 'place' => $item['location'], 'contributors' => '', 'annotations' => '', 'entities' => '', 'objecttype' => $item['object-type'] ? $item['object-type'] : ACTIVITY_OBJ_NOTE, 'verb' => $item['verb'] ? $item['verb'] : ACTIVITY_POST, 'self' => $a->get_baseurl() . "/api/statuses/show/" . $item['id'] . "." . $type, 'edit' => $a->get_baseurl() . "/api/statuses/show/" . $item['id'] . "." . $type); $status = array_merge($status, $status2); } $ret[] = $status; } return $ret; }
function gpluspost_feeditem($pid, $uid) { global $a; require_once 'include/api.php'; require_once 'include/bbcode.php'; require_once "include/html2plain.php"; require_once "include/network.php"; $skipwithoutlink = get_pconfig($uid, 'gpluspost', 'skip_without_link'); $items = q("SELECT `uri`, `plink`, `author-link`, `author-name`, `created`, `edited`, `id`, `title`, `body` from `item` WHERE id=%d", intval($pid)); foreach ($items as $item) { $item['body'] = bb_CleanPictureLinks($item['body']); $item['body'] = bb_remove_share_information($item['body'], true); if ($item["title"] != "") { $item['body'] = "*" . $item["title"] . "*\n\n" . $item['body']; } // Looking for the first image $image = ''; if (preg_match("/\\[img\\=([0-9]*)x([0-9]*)\\](.*?)\\[\\/img\\]/is", $item['body'], $matches)) { $image = $matches[3]; } if ($image == '') { if (preg_match("/\\[img\\](.*?)\\[\\/img\\]/is", $item['body'], $matches)) { $image = $matches[1]; } } $multipleimages = strpos($item['body'], "[img") != strrpos($item['body'], "[img"); // When saved into the database the content is sent through htmlspecialchars // That means that we have to decode all image-urls $image = htmlspecialchars_decode($image); $link = ''; // look for bookmark-bbcode and handle it with priority if (preg_match("/\\[bookmark\\=([^\\]]*)\\](.*?)\\[\\/bookmark\\]/is", $item['body'], $matches)) { $link = $matches[1]; } $multiplelinks = strpos($item['body'], "[bookmark") != strrpos($item['body'], "[bookmark"); $body = $item['body']; $body = preg_replace("(\\[b\\](.*?)\\[\\/b\\])ism", '*$1*', $body); $body = preg_replace("(\\[i\\](.*?)\\[\\/i\\])ism", '_$1_', $body); $body = preg_replace("(\\[s\\](.*?)\\[\\/s\\])ism", '-$1-', $body); // At first convert the text to html $html = bbcode(api_clean_plain_items($body), false, false, 2); // Then convert it to plain text $msg = trim(html2plain($html, 0, true)); $msg = html_entity_decode($msg, ENT_QUOTES, 'UTF-8'); // If there is no bookmark element then take the first link if ($link == '') { $links = collecturls($html); if (sizeof($links) > 0) { reset($links); $link = current($links); } $multiplelinks = sizeof($links) > 1; if ($multiplelinks) { $html2 = bbcode($msg, false, false); $links2 = collecturls($html2); if (sizeof($links2) > 0) { reset($links2); $link = current($links2); $multiplelinks = sizeof($links2) > 1; } } } $msglink = ""; if ($multiplelinks) { $msglink = $item["plink"]; } else { if ($link != "") { $msglink = $link; } else { if ($multipleimages) { $msglink = $item["plink"]; } else { if ($image != "") { $msglink = $image; } } } } if ($msglink == "" and $skipwithoutlink) { continue; } else { if ($msglink == "") { $msglink = $item["plink"]; } } // Fetching the title - or the first line if ($item["title"] != "") { $title = $item["title"]; } else { $lines = explode("\n", $msg); $title = $lines[0]; } //if ($image != $msglink) // $html = trim(str_replace($msglink, "", $html)); $title = trim(str_replace($msglink, "", $title)); $msglink = original_url($msglink); if ($uid == 0) { $title = $item["author-name"] . ": " . $title; } $msglink = htmlspecialchars(html_entity_decode($msglink)); if (strpos($msg, $msglink) == 0) { $msg .= "\n" . $msglink; } $msg = nl2br($msg); $title = str_replace("&", "&", $title); //$html = str_replace("&", "&", $html); echo "\t" . '<entry xmlns="http://www.w3.org/2005/Atom">' . "\n"; echo "\t\t" . '<title type="html" xml:space="preserve"><![CDATA[' . $title . "]]></title>\n"; echo "\t\t" . '<link rel="alternate" type="text/html" href="' . $msglink . '" />' . "\n"; // <link rel="enclosure" type="audio/mpeg" length="1337" href="http://example.org/audio/ph34r_my_podcast.mp3"/> echo "\t\t<id>" . $item["uri"] . "</id>\n"; echo "\t\t<updated>" . date("c", strtotime($item["edited"])) . "</updated>\n"; echo "\t\t<published>" . date("c", strtotime($item["created"])) . "</published>\n"; echo "\t\t<author>\n\t\t\t<name><![CDATA[" . $item["author-name"] . "]]></name>\n"; echo "\t\t\t<uri>" . $item["author-link"] . "</uri>\n\t\t</author>\n"; //echo '<content type="image/png" src="http://media.example.org/the_beach.png"/>'; echo "\t\t" . '<content type="html" xml:space="preserve" xml:base="' . $item["plink"] . '"><![CDATA[' . $msg . "]]></content>\n"; echo "\t</entry>\n"; } }
function statusnet_shortenmsg($b, $max_char) { require_once "include/bbcode.php"; require_once "include/html2plain.php"; // Looking for the first image $image = ''; if (preg_match("/\\[[zi]mg\\=([0-9]*)x([0-9]*)\\](.*?)\\[\\/[zi]mg\\]/is", $b['body'], $matches)) { $image = $matches[3]; } if ($image == '') { if (preg_match("/\\[[zi]mg\\](.*?)\\[\\/[zi]mg\\]/is", $b['body'], $matches)) { $image = $matches[1]; } } // @fixme for zmg $multipleimages = strpos($b['body'], "[img") != strrpos($b['body'], "[img"); // When saved into the database the content is sent through htmlspecialchars // That means that we have to decode all image-urls $image = htmlspecialchars_decode($image); $body = $b["body"]; if ($b["title"] != "") { $body = $b["title"] . "\n\n" . $body; } if (strpos($body, "[bookmark") !== false) { // splitting the text in two parts: // before and after the bookmark $pos = strpos($body, "[bookmark"); $body1 = substr($body, 0, $pos); $body2 = substr($body, $pos); // Removing all quotes after the bookmark // they are mostly only the content after the bookmark. $body2 = preg_replace("/\\[quote\\=([^\\]]*)\\](.*?)\\[\\/quote\\]/ism", '', $body2); $body2 = preg_replace("/\\[quote\\](.*?)\\[\\/quote\\]/ism", '', $body2); $body = $body1 . $body2; } // Add some newlines so that the message could be cut better $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"), array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body); // remove the recycle signs and the names since they aren't helpful on twitter // recycle 1 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8'); $body = preg_replace('/' . $recycle . '\\[url\\=(\\w+.*?)\\](\\w+.*?)\\[\\/url\\]/i', "\n", $body); // recycle 2 (Test) $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8'); $body = preg_replace('/' . $recycle . '\\[url\\=(\\w+.*?)\\](\\w+.*?)\\[\\/url\\]/i', "\n", $body); // remove the share element $body = preg_replace("/\\[share(.*?)\\](.*?)\\[\\/share\\]/ism", "\n\n\$2\n\n", $body); // At first convert the text to html $html = bbcode($body, false, false); // Then convert it to plain text //$msg = trim($b['title']." \n\n".html2plain($html, 0, true)); $msg = trim(html2plain($html, 0, true)); $msg = html_entity_decode($msg, ENT_QUOTES, 'UTF-8'); // Removing multiple newlines while (strpos($msg, "\n\n\n") !== false) { $msg = str_replace("\n\n\n", "\n\n", $msg); } // Removing multiple spaces while (strpos($msg, " ") !== false) { $msg = str_replace(" ", " ", $msg); } $msg = str_replace('#^http', 'http', $msg); $origmsg = $msg; // Removing URLs $msg = preg_replace('/(https?\\:\\/\\/[a-zA-Z0-9\\:\\/\\-\\?\\&\\;\\.\\=\\_\\~\\#\\%\\$\\!\\+\\,]+)/i', "", $msg); $msg = trim($msg); $link = ''; // look for bookmark-bbcode and handle it with priority if (preg_match("/\\[bookmark\\=([^\\]]*)\\](.*?)\\[\\/bookmark\\]/is", $b['body'], $matches)) { $link = $matches[1]; } $multiplelinks = strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"); // If there is no bookmark element then take the first link if ($link == '') { $links = collecturls($html); if (sizeof($links) > 0) { reset($links); $link = current($links); } $multiplelinks = sizeof($links) > 1; } $msglink = ""; if ($multiplelinks) { $msglink = $b["plink"]; } else { if ($link != "") { $msglink = $link; } else { if ($multipleimages) { $msglink = $b["plink"]; } else { if ($image != "") { $msglink = $image; } } } } if ($msglink == "" and strlen($msg) > $max_char) { $msglink = $b["plink"]; } // If the message is short enough then don't modify it. (if the link exists in the original message) if (strlen(trim($origmsg)) <= $max_char and (strpos($origmsg, $msglink) or $msglink == "")) { return array("msg" => trim($origmsg), "image" => ""); } if (strlen($msglink) > 20) { $msglink = short_link($msglink); } if (strlen(trim($msg . " " . $msglink)) > $max_char) { $msg = substr($msg, 0, $max_char - strlen($msglink)); $lastchar = substr($msg, -1); $msg = substr($msg, 0, -1); $pos = strrpos($msg, "\n"); if ($pos > 0) { $msg = substr($msg, 0, $pos); } else { if ($lastchar != "\n") { $msg = substr($msg, 0, -3) . "..."; } } } $msg = str_replace("\n", " ", $msg); // Removing multiple spaces - again while (strpos($msg, " ") !== false) { $msg = str_replace(" ", " ", $msg); } return array("msg" => trim($msg . " " . $msglink), "image" => $image); }
function post_is_importable($item, $abook) { if (!$abook) { return true; } if ($abook['abook_channel'] && !feature_enabled($abook['abook_channel'], 'connfilter')) { return true; } if (!$item) { return false; } if (!$abook['abook_incl'] && !$abook['abook_excl']) { return true; } require_once 'include/html2plain.php'; $text = prepare_text($item['body'], $item['mimetype']); $text = html2plain($text); $lang = null; if (strpos($abook['abook_incl'], 'lang=') !== false || strpos($abook['abook_excl'], 'lang=') !== false) { $lang = detect_language($text); } $tags = count($item['term']) ? $item['term'] : false; // exclude always has priority $exclude = $abook['abook_excl'] ? explode("\n", $abook['abook_excl']) : null; if ($exclude) { foreach ($exclude as $word) { $word = trim($word); if (substr($word, 0, 1) === '#' && $tags) { foreach ($tags as $t) { if ($t['type'] == TERM_HASHTAG && (substr($t, 1) === substr($word, 1) || substr($word, 1) === '*')) { return false; } } } elseif (strpos($word, '/') === 0 && preg_match($word, $body)) { return false; } elseif (strpos($word, 'lang=') === 0 && $lang && strcasecmp($lang, trim(substr($word, 5))) == 0) { return false; } elseif (stristr($text, $word) !== false) { return false; } } } $include = $abook['abook_incl'] ? explode("\n", $abook['abook_incl']) : null; if ($include) { foreach ($include as $word) { $word = trim($word); if (substr($word, 0, 1) === '#' && $tags) { foreach ($tags as $t) { if ($t['type'] == TERM_HASHTAG && (substr($t, 1) === substr($word, 1) || substr($word, 1) === '*')) { return true; } } } elseif (strpos($word, '/') === 0 && preg_match($word, $body)) { return true; } elseif (strpos($word, 'lang=') === 0 && $lang && strcasecmp($lang, trim(substr($word, 5))) == 0) { return true; } elseif (stristr($text, $word) !== false) { return true; } } } else { return true; } return false; }
function appnet_create_entities($a, $b, $postdata) { require_once "include/bbcode.php"; require_once "include/plaintext.php"; $bbcode = $b["body"]; $bbcode = bb_remove_share_information($bbcode, false, true); // Change pure links in text to bbcode uris $bbcode = preg_replace("/([^\\]\\='" . '"' . "]|^)(https?\\:\\/\\/[a-zA-Z0-9\\:\\/\\-\\?\\&\\;\\.\\=\\_\\~\\#\\%\$\\!\\+\\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode); $URLSearchString = "^\\[\\]"; $bbcode = preg_replace("/#\\[url\\=([{$URLSearchString}]*)\\](.*?)\\[\\/url\\]/ism", '#$2', $bbcode); $bbcode = preg_replace("/@\\[url\\=([{$URLSearchString}]*)\\](.*?)\\[\\/url\\]/ism", '@$2', $bbcode); $bbcode = preg_replace("/\\[bookmark\\=([{$URLSearchString}]*)\\](.*?)\\[\\/bookmark\\]/ism", '[url=$1]$2[/url]', $bbcode); $bbcode = preg_replace("/\\[video\\](.*?)\\[\\/video\\]/ism", '[url=$1]$1[/url]', $bbcode); $bbcode = preg_replace("/\\[youtube\\]https?:\\/\\/(.*?)\\[\\/youtube\\]/ism", '[url=https://$1]https://$1[/url]', $bbcode); $bbcode = preg_replace("/\\[youtube\\]([A-Za-z0-9\\-_=]+)(.*?)\\[\\/youtube\\]/ism", '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode); $bbcode = preg_replace("/\\[vimeo\\]https?:\\/\\/(.*?)\\[\\/vimeo\\]/ism", '[url=https://$1]https://$1[/url]', $bbcode); $bbcode = preg_replace("/\\[vimeo\\]([0-9]+)(.*?)\\[\\/vimeo\\]/ism", '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode); //$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode); $bbcode = preg_replace("/\\[img\\=([0-9]*)x([0-9]*)\\](.*?)\\[\\/img\\]/ism", '[img]$3[/img]', $bbcode); preg_match_all("/\\[url\\=([{$URLSearchString}]*)\\](.*?)\\[\\/url\\]/ism", $bbcode, $urls, PREG_SET_ORDER); $bbcode = preg_replace("/\\[url\\=([{$URLSearchString}]*)\\](.*?)\\[\\/url\\]/ism", '$1', $bbcode); $b["body"] = $bbcode; // To-Do: // Bilder // https://alpha.app.net/heluecht/post/32424376 // https://alpha.app.net/heluecht/post/32424307 $plaintext = plaintext($a, $b, 0, false, 6); $text = $plaintext["text"]; $start = 0; $entities = array(); foreach ($urls as $url) { $lenurl = iconv_strlen($url[1], "UTF-8"); $len = iconv_strlen($url[2], "UTF-8"); $pos = iconv_strpos($text, $url[1], $start, "UTF-8"); $pre = iconv_substr($text, 0, $pos, "UTF-8"); $post = iconv_substr($text, $pos + $lenurl, 1000000, "UTF-8"); $mid = $url[2]; $html = bbcode($mid, false, false, 6); $mid = html2plain($html, 0, true); $mid = trim(html_entity_decode($mid, ENT_QUOTES, 'UTF-8')); $text = $pre . $mid . $post; if ($mid != "") { $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid); } $start = $pos + 1; } if (isset($postdata["url"]) and isset($postdata["title"]) and $postdata["type"] != "photo") { $postdata["title"] = shortenmsg($postdata["title"], 90); $max = 256 - strlen($postdata["title"]); $text = shortenmsg($text, $max); $text .= "\n[" . $postdata["title"] . "](" . $postdata["url"] . ")"; } elseif (isset($postdata["url"]) and $postdata["type"] != "photo") { $postdata["url"] = short_link($postdata["url"]); $max = 240; $text = shortenmsg($text, $max); $text .= " [" . $postdata["url"] . "](" . $postdata["url"] . ")"; } else { $max = 256; $text = shortenmsg($text, $max); } if (iconv_strlen($text, "UTF-8") < $max) { $max = iconv_strlen($text, "UTF-8"); } krsort($entities); foreach ($entities as $entity) { //if (iconv_strlen($text, "UTF-8") >= $entity["pos"] + $entity["len"]) { if ($entity["pos"] + $entity["len"] <= $max) { $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8"); $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8"); $text = $pre . "[" . $entity["text"] . "](" . $entity["url"] . ")" . $post; } } return $text; }
function randpost_enotify_store(&$a, &$b) { if (!($b['ntype'] == NOTIFY_COMMENT || $b['ntype'] == NOTIFY_TAGSELF)) { return; } if (!get_pconfig($b['uid'], 'randpost', 'enable')) { return; } $fort_server = get_config('fortunate', 'server'); if (!$fort_server) { return; } $c = q("select * from channel where channel_id = %d limit 1", intval($b['uid'])); if (!$c) { return; } $my_conversation = false; $p = q("select id, item_flags, author_xchan from item where parent_mid = mid and parent_mid = '%s' and uid = %d limit 1", dbesc($b['item']['parent_mid']), intval($b['uid'])); if (!$p) { return; } $p = fetch_post_tags($p, true); if (intval($p[0]['item_obscured'])) { return; } if ($b['ntype'] == NOTIFY_TAGSELF) { $my_conversation = true; } elseif ($p[0]['author_xchan'] === $c[0]['channel_hash']) { $my_conversation = true; } elseif ($p[0]['term']) { $v = get_terms_oftype($p[0]['term'], TERM_MENTION); $link = normalise_link(z_root() . '/channel/' . $c[0]['channel_address']); if ($v) { foreach ($v as $vv) { if (link_compare($vv['url'], $link)) { $my_conversation = true; break; } } } } // don't hijack somebody else's conversation, but respond (once) if invited to. if (!$my_conversation) { return; } // This conversation is boring me. $limit = mt_rand(5, 20); $h = q("select id, body from item where author_xchan = '%s' and parent_mid = '%s' and uid = %d", dbesc($c[0]['channel_hash']), dbesc($b['item']['parent_mid']), intval($b['uid'])); if ($h && count($h) > $limit) { return; } // Be gracious and not obnoxious if thanked $replies = array(t('You\'re welcome.'), t('Ah shucks...'), t('Don\'t mention it.'), t('<blush>'), ':like'); // TODO: if you really want to freak somebody out, add a relevance search function to mod_zotfeed and // use somebody's own words from long ago to craft a reply to them.... require_once 'include/bbcode.php'; require_once 'include/html2plain.php'; if ($b['item'] && $b['item']['body']) { if (stristr($b['item']['body'], 'nocomment')) { return; } $txt = preg_replace('/\\@\\[z(.*?)\\[\\/zrl\\]/', '', $b['item']['body']); $txt = html2plain(bbcode($txt)); $pattern = substr($txt, 0, 255); } if ($b['item']['author_xchan']) { $z = q("select * from xchan where xchan_hash = '%s' limit 1", dbesc($b['item']['author_xchan'])); if ($z) { $mention = '@' . '[zrl=' . $z[0]['xchan_url'] . ']' . $z[0]['xchan_name'] . '[/zrl]' . "\n\n"; } } if (stristr($b['item']['body'], $c[0]['channel_name']) && mb_strlen($pattern) < 36 && stristr($pattern, 'thank')) { $reply = $replies[mt_rand(0, count($replies) - 1)]; } $x = array(); if ($reply) { $x['body'] = $mention . $reply; } else { require_once 'include/html2bbcode.php'; $valid = false; do { $url = 'http://' . $fort_server . '/cookie.php?f=&lang=any&off=a&pattern=' . urlencode($pattern); $s = z_fetch_url($url); if ($s['success'] && !$s['body']) { $s = z_fetch_url('http://' . $fort_server . '/cookie.php'); } if (!$s['success'] || !$s['body']) { return; } // if it might be a quote make it a quote if (strpos($s['body'], '--')) { $x['body'] = '[quote]' . html2bbcode($s['body']) . '[/quote]'; } else { $x['body'] = html2bbcode($s['body']); } $found_text = false; if ($h) { foreach ($h as $hh) { if (stripos($hh['body'], $x['body']) !== false) { $pattern = ''; $found_text = true; break; } } } if (!$found_text) { $valid = true; } } while (!$valid); } if ($mention) { $x['body'] = $mention . $x['body']; $x['term'] = array(array('uid' => $c[0]['channel_id'], 'type' => TERM_MENTION, 'otype' => TERM_OBJ_POST, 'term' => $z[0]['xchan_name'], 'url' => $z[0]['xchan_url'])); } $x['uid'] = $c[0]['channel_id']; $x['aid'] = $c[0]['channel_account_id']; $x['mid'] = item_message_id(); $x['parent'] = $p[0]['id']; $x['parent_mid'] = $b['item']['parent_mid']; $x['author_xchan'] = $c[0]['channel_hash']; $x['owner_xchan'] = $b['item']['owner_xchan']; $x['item_origin'] = 1; $x['item_verified'] = 1; // You can't pass a Turing test if you reply in milliseconds. // Also I believe we've got ten minutes fudge before we declare a post as time traveling. // Otherwise we'll just set it to now and it will still go out in milliseconds. // So set the reply to post sometime in the next 15-45 minutes (depends on poller interval) $fudge = mt_rand(15, 30); $x['created'] = $x['edited'] = datetime_convert('UTC', 'UTC', 'now + ' . $fudge . ' minutes'); $x['body'] = trim($x['body']); $x['sig'] = base64url_encode(rsa_sign($x['body'], $c[0]['channel_prvkey'])); $post = item_store($x); $post_id = $post['item_id']; $x['id'] = $post_id; call_hooks('post_local_end', $x); Zotlabs\Daemon\Master::Summon(array('Notifier', 'comment-new', $post_id)); }
function twitter_shortenmsg($b, $shortlink = false) { require_once "include/api.php"; require_once "include/bbcode.php"; require_once "include/html2plain.php"; $max_char = 140; // $b['body'] = bb_CleanPictureLinks($b['body']); // Looking for the first image // $cleaned_body = api_clean_plain_items($b['body']); $cleaned_body = $b['body']; $image = ''; if (preg_match("/\\[img\\=([0-9]*)x([0-9]*)\\](.*?)\\[\\/img\\]/is", $cleaned_body, $matches)) { $image = $matches[3]; } if ($image == '') { if (preg_match("/\\[img\\](.*?)\\[\\/img\\]/is", $cleaned_body, $matches)) { $image = $matches[1]; } } $multipleimages = strpos($cleaned_body, "[img") != strrpos($cleaned_body, "[img"); // When saved into the database the content is sent through htmlspecialchars // That means that we have to decode all image-urls $image = htmlspecialchars_decode($image); $body = $b["body"]; if ($b["title"] != "") { $body = $b["title"] . "\n\n" . $body; } if (strpos($body, "[bookmark") !== false) { // splitting the text in two parts: // before and after the bookmark $pos = strpos($body, "[bookmark"); $body1 = substr($body, 0, $pos); $body2 = substr($body, $pos); // Removing all quotes after the bookmark // they are mostly only the content after the bookmark. $body2 = preg_replace("/\\[quote\\=([^\\]]*)\\](.*?)\\[\\/quote\\]/ism", '', $body2); $body2 = preg_replace("/\\[quote\\](.*?)\\[\\/quote\\]/ism", '', $body2); $body = $body1 . $body2; } // Add some newlines so that the message could be cut better $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"), array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body); // remove the recycle signs and the names since they aren't helpful on twitter // recycle 1 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8'); $body = preg_replace('/' . $recycle . '\\[url\\=(\\w+.*?)\\](\\w+.*?)\\[\\/url\\]/i', "\n", $body); // recycle 2 (Test) $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8'); $body = preg_replace('/' . $recycle . '\\[url\\=(\\w+.*?)\\](\\w+.*?)\\[\\/url\\]/i', "\n", $body); // remove the share element //$body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body); // At first convert the text to html $html = bbcode($body, false, false); // Then convert it to plain text $msg = trim(html2plain($html, 0, true)); $msg = html_entity_decode($msg, ENT_QUOTES, 'UTF-8'); // Removing multiple newlines while (strpos($msg, "\n\n\n") !== false) { $msg = str_replace("\n\n\n", "\n\n", $msg); } // Removing multiple spaces while (strpos($msg, " ") !== false) { $msg = str_replace(" ", " ", $msg); } $origmsg = trim($msg); // Removing URLs $msg = preg_replace('/(https?\\:\\/\\/[a-zA-Z0-9\\:\\/\\-\\?\\&\\;\\.\\=\\_\\~\\#\\%\\$\\!\\+\\,]+)/i', "", $msg); $msg = trim($msg); $link = ''; // look for bookmark-bbcode and handle it with priority if (preg_match("/\\[bookmark\\=([^\\]]*)\\](.*?)\\[\\/bookmark\\]/is", $b['body'], $matches)) { $link = $matches[1]; } $multiplelinks = strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"); // If there is no bookmark element then take the first link // if ($link == '') { // $links = collecturls($html); // foreach($links AS $singlelink) { // $img_str = fetch_url($singlelink); // $tempfile = tempnam(get_config("system","temppath"), "cache"); // file_put_contents($tempfile, $img_str); // $mime = image_type_to_mime_type(exif_imagetype($tempfile)); // unlink($tempfile); // if (substr($mime, 0, 6) == "image/") { // $image = $singlelink; // unset($links[$singlelink]); // } // } // if (sizeof($links) > 0) { // reset($links); // $link = current($links); // } // $multiplelinks = (sizeof($links) > 1); // } $msglink = ""; if ($multiplelinks) { $msglink = $b["plink"]; } else { if ($link != "") { $msglink = $link; } else { if ($multipleimages) { $msglink = $b["plink"]; } else { if ($image != "") { $msglink = $image; } } } } if ($msglink == "" and strlen($msg) > $max_char) { $msglink = $b["plink"]; } // If the message is short enough then don't modify it. if (strlen($origmsg) <= $max_char and $msglink == "") { return array("msg" => $origmsg, "image" => ""); } // If the message is short enough and contains a picture then post the picture as well if (strlen($origmsg) <= $max_char - 23 and strpos($origmsg, $msglink)) { return array("msg" => $origmsg, "image" => $image); } // If the message is short enough and the link exists in the original message don't modify it as well // -3 because of the bad shortener of twitter if (strlen($origmsg) <= $max_char - 3 and strpos($origmsg, $msglink)) { return array("msg" => $origmsg, "image" => ""); } // Preserve the unshortened link $orig_link = $msglink; // Just replace the message link with a 22 character long string // Twitter calculates with this length if (trim($msglink) != '') { $msglink = "1234567890123456789012"; } if (strlen(trim($msg . " " . $msglink)) > $max_char) { $msg = substr($msg, 0, $max_char - strlen($msglink)); $lastchar = substr($msg, -1); $msg = substr($msg, 0, -1); $pos = strrpos($msg, "\n"); if ($pos > 0) { $msg = substr($msg, 0, $pos); } else { if ($lastchar != "\n") { $msg = substr($msg, 0, -3) . "..."; } } // if the post contains a picture and a link then the system tries to cut the post earlier. // So the link and the picture can be posted. if ($image != "" and $orig_link != $image) { $msg2 = substr($msg, 0, $max_char - 20 - strlen($msglink)); $lastchar = substr($msg2, -1); $msg2 = substr($msg2, 0, -1); $pos = strrpos($msg2, "\n"); if ($pos > 0) { $msg = substr($msg2, 0, $pos); } else { if ($lastchar == "\n") { $msg = trim($msg2); } } } } // Removing multiple spaces - again while (strpos($msg, " ") !== false) { $msg = str_replace(" ", " ", $msg); } $msg = trim($msg); // Removing multiple newlines //while (strpos($msg, "\n\n") !== false) // $msg = str_replace("\n\n", "\n", $msg); // Looking if the link points to an image $img_str = fetch_url($orig_link); // $tempfile = tempnam(get_config("system","temppath"), "cache"); // file_put_contents($tempfile, $img_str); // $mime = image_type_to_mime_type(exif_imagetype($tempfile)); // unlink($tempfile); if ($image == $orig_link or substr($mime, 0, 6) == "image/") { return array("msg" => $msg, "image" => $orig_link); } else { if ($image != $orig_link and $image != "" and strlen($msg . " " . $msglink) <= $max_char - 23) { if ($shortlink) { $orig_link = short_link($orig_link); } return array("msg" => $msg . " " . $orig_link, "image" => $image); } else { if ($shortlink) { $orig_link = short_link($orig_link); } return array("msg" => $msg . " " . $orig_link, "image" => ""); } } }
function api_format_items($r, $user_info) { //logger('api_format_items: ' . print_r($r,true)); //logger('api_format_items: ' . print_r($user_info,true)); $a = get_app(); $ret = array(); if (!$r) { return $ret; } foreach ($r as $item) { localize_item($item); $status_user = $item['author_xchan'] == $user_info['guid'] ? $user_info : api_item_get_user($a, $item); if (array_key_exists('status', $status_user)) { unset($status_user['status']); } if ($item['parent'] != $item['id']) { $r = q("select id from item where parent= %d and id < %d order by id desc limit 1", intval($item['parent']), intval($item['id'])); if ($r) { $in_reply_to_status_id = $r[0]['id']; } else { $in_reply_to_status_id = $item['parent']; } xchan_query($r, true); $in_reply_to_screen_name = $r[0]['author']['xchan_name']; $in_reply_to_user_id = $r[0]['author']['abook_id']; } else { $in_reply_to_screen_name = ''; $in_reply_to_user_id = 0; $in_reply_to_status_id = 0; } unobscure($item); // Workaround for ostatus messages where the title is identically to the body $statusbody = trim(html2plain(prepare_text($item['body'], $item['mimetype']), 0)); $statustitle = trim($item['title']); if ($statustitle != '' and strpos($statusbody, $statustitle) !== false) { $statustext = trim($statusbody); } else { $statustext = trim($statustitle . "\n\n" . $statusbody); } $status = array('text' => $statustext, 'truncated' => False, 'created_at' => api_date($item['created']), 'in_reply_to_status_id' => $in_reply_to_status_id, 'source' => $item['app'] ? $item['app'] : 'web', 'id' => intval($item['id']), 'in_reply_to_user_id' => $in_reply_to_user_id, 'in_reply_to_screen_name' => $in_reply_to_screen_name, 'geo' => '', 'favorited' => intval($item['item_starred']) ? true : false, 'user' => $status_user, 'statusnet_html' => trim(prepare_text($item['body'], $item['mimetype'])), 'statusnet_conversation_id' => $item['parent']); // Seesmic doesn't like the following content if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') { $status2 = array('updated' => api_date($item['edited']), 'published' => api_date($item['created']), 'message_id' => $item['mid'], 'url' => $item['plink'], 'coordinates' => $item['coord'], 'place' => $item['location'], 'contributors' => '', 'annotations' => '', 'entities' => '', 'objecttype' => $item['obj_type'] ? $item['obj_type'] : ACTIVITY_OBJ_NOTE, 'verb' => $item['verb'] ? $item['verb'] : ACTIVITY_POST, 'self' => $a->get_baseurl() . "/api/statuses/show/" . $item['id'] . "." . $type, 'edit' => $a->get_baseurl() . "/api/statuses/show/" . $item['id'] . "." . $type); $status = array_merge($status, $status2); } $ret[] = $status; } return $ret; }
function api_direct_messages_box(&$a, $type, $box) { if (local_user() === false) { return false; } $user_info = api_get_user($a); // params $count = x($_GET, 'count') ? $_GET['count'] : 20; $page = x($_REQUEST, 'page') ? $_REQUEST['page'] - 1 : 0; if ($page < 0) { $page = 0; } $start = $page * $count; if ($box == "sentbox") { $sql_extra = "`from-url`='%s'"; } else { $sql_extra = "`from-url`!='%s'"; } $r = q("SELECT * FROM `mail` WHERE uid=%d AND {$sql_extra} ORDER BY created DESC LIMIT %d,%d", intval(local_user()), dbesc($a->get_baseurl() . '/profile/' . $a->user['nickname']), intval($start), intval($count)); $ret = array(); foreach ($r as $item) { switch ($box) { case "inbox": $recipient = $user_info; $sender = api_get_user($a, $item['contact-id']); break; case "sentbox": $recipient = api_get_user($a, $item['contact-id']); $sender = $user_info; break; } $ret[] = array('id' => $item['id'], 'created_at' => api_date($item['created']), 'sender_id' => $sender['id'], 'sender_screen_name' => $sender['screen_name'], 'sender' => $sender, 'recipient_id' => $recipient['id'], 'recipient_screen_name' => $recipient['screen_name'], 'recipient' => $recipient, 'text' => $item['title'] . "\n" . html2plain(bbcode($item['body']), 0)); } $data = array('$messages' => $ret); switch ($type) { case "atom": case "rss": $data = api_rss_extra($a, $data, $user_info); } return api_apply_template("direct_messages", $type, $data); }