Jira Groovy script in script runner - groovy

I'm trying to get users not in the jira-users group with email addresses not equal to: email#email.com. I can get the users not in the jira-users group(see below) but not sure how to complete the if statement to show "users email address not equal to email#email.com. I tried user.getEmail but couldn't get that to work. Would someone be able to make a suggestion with this?
Thanks.
for ( user in crowdService.search(query) ) {
if (!crowdService.isUserMemberOfGroup(user.getName(), "jira-users")) {
body = body + user.getName() + "\n"
}
}

The User object implementation depends on your particular Atlassian setup.
Try calling user.getEmailAddress():
for ( user in crowdService.search(query) ) {
if (!crowdService.isUserMemberOfGroup(user.getName(), "jira-users")
&& !user.getEmailAddress().equals("email#email.com")) {
body = body + user.getName() + "\n"
}
}

Related

When I make an e-mail intent in kotlin, the recipient mail is not added directly

binding.navView.setNavigationItemSelectedListener {
when(it.itemId){
R.id.requestWallpaper->{
val emailIntent=Intent().apply {
action=Intent.ACTION_SEND
data= Uri.parse("mailto:")
type="text/plain"
putExtra(Intent.EXTRA_EMAIL,"test#gmail.com")
putExtra(Intent.EXTRA_SUBJECT,"request wallpaper")
putExtra(Intent.EXTRA_TEXT,"request wallpaper")
}
if (emailIntent.resolveActivity(this!!.packageManager) !=null){
emailIntent.setPackage("com.google.android.gm")
startActivity(emailIntent)
}else{
Toast.makeText(this#MainActivity,"No app available to send email!!",Toast.LENGTH_SHORT).show()
}
}
When the navigation drawer opens, the user will want to make a wallpaper request and when he presses the imagebutton, I want him to send an e-mail to test#gmail.com via gmail for now, but test#gmail.com is not added directly to the "to" part of gmail.When I run it on the emulator, the email subject and e-mail text are added, but the recipient e-mail is not added, why?
You're so close here, the only thing that's missing is the Intent.EXTRA_EMAIL extra. That property is expecting an array of String values rather than a single String.
binding.navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.requestWallpaper -> {
val emailIntent = Intent().apply {
action = Intent.ACTION_SEND
data = Uri.parse("mailto:")
type = "text/plain"
putExtra(Intent.EXTRA_EMAIL, arrayOf("test#gmail.com"))
putExtra(Intent.EXTRA_SUBJECT, "request wallpaper")
putExtra(Intent.EXTRA_TEXT, "request wallpaper")
}
if (emailIntent.resolveActivity(this.packageManager) != null) {
emailIntent.setPackage("com.google.android.gm")
startActivity(emailIntent)
} else {
Toast.makeText(
this#MainActivity,
"No app available to send email!!",
Toast.LENGTH_SHORT
).show()
}
}
}
}
I don't know that you need the type="text/plain" property either, but it shouldn't hurt anything. Also, if you skip the setPackage step it'll allow the OS to ask which email app to use.

Unban command JDA 4.1.1_101, can't make it work and I don't know why

i'm coding a Discord bot with JDA 4.1.1_101. I created the "ban" command, but i can't make the unban command work. I can't really understand why... Thank you for your help.
if (args[0].equalsIgnoreCase(Main.prefix + "unban")) {
if(event.getGuild().getSelfMember().hasPermission(Permission.BAN_MEMBERS)) {
if (args.length > 0 && args.length < 3) {
try {
event.getMessage().delete().queue();
User member = event.getMessage().getMentionedMembers().get(0).getUser();
String id = member.getId();
event.getGuild().unban(id).queue();
EmbedBuilder ban = new EmbedBuilder();
ban.setColor(Color.GREEN);
ban.setTitle("UnBan");
ban.setDescription("UnBan Report");
ban.addField("Staffer: ", event.getMessage().getAuthor().getName(), true);
ban.addField("Unban: ", member.getName(), true);
logs.sendMessage(ban.build()).queue();
} catch (IndexOutOfBoundsException exx) {
EmbedBuilder error = new EmbedBuilder();
error.setColor(0xff3923);
error.setTitle("Error: User");
error.setDescription("Invalid user.");
event.getChannel().sendMessage(error.build()).queue(message -> {
message.delete().queueAfter(5, TimeUnit.SECONDS);
});
}
} else {
EmbedBuilder error = new EmbedBuilder();
error.setColor(0xff3923);
error.setTitle("Error: Wrong usage.");
error.setDescription("Use: .unban [#user].");
event.getChannel().sendMessage(error.build()).queue(message -> {
message.delete().queueAfter(5, TimeUnit.SECONDS);
});
}
}
}
The problem is, that you are trying to retrieve the user from the mention in the message.
Since the user isn't part of the guild anymore, it seems like this doesn't work.
In order to work around this issue, you have to retrieve the ID manually.
A mention is always in the format <#userid> or <!#userid>.
To get the ID you could just split the message and replace the unnecessary parts, e.g. String id = event.getMessage().getContentRaw().split("<")[1].split(">")[0].replace("!", "").replace("#", "");
I'm sure there are better and smoother ways for doing this. ;)
A better way of retrieving the ID would be using a regex such as <#!?(\d+)> as mentioned by Minn.
In order to get the name of the user, you just need the ID via event.getJDA().getUserById(id).getName().
It's important to mention that you can't properly mention a user who isn't on the server (which is the case when they are banned).
(Addition: I tried using .getMentionedUsers() with the same result as OP.)

PHPmailer parseAddresses - How to get rid of "notice" messages

I'm trying to get rid of the following message in one of my scripts when using the PHPmailer parseAddresses function:
Notice: Unknown: Must use comma to separate addresses: xxx (errflg=3) in Unknown on line 0
$mailer = new PHPMailer(true);
try {
$a = $mailer->parseAddresses('aaa#aaa.aaa xxx');
}
finally {
...
}
I'm using PHP 7.0.8 with the following error handling presets:
declare(strict_types = 1);
error_reporting(E_ALL);
ini_set('display_errors', 'stdout');
I know that I can just stop the errors from being displayed but this doesn't seem to be the proper way to do. And of course I know that the provided email addresses in my example are not correct...
I'm not sure what you're complaining about: it's telling you you have malformed input when you provide malformed input! The way to avoid the error is not to pass in malformed input!
As the error says, it's expecting one or more addresses in comma-delimited RFC822 format (not what you provided), which might be something like:
xxx <aaa#aaa.aaa>, yyy <bbb#aaa.aaa>
If you don't provide data in that format, it will complain, as you're seeing. This is covered in the docs on the parseAddress method.
Are you expecting it to do something else?
PHPMailer writes notices to output, so you could start an output buffer and just flush it after your call. Something like:
$mailer = new PHPMailer(true);
try {
ob_start();
$a = $mailer->parseAddresses('aaa#aaa.aaa xxx');
//$notices = ob_get_contents();
ob_end_clean();
}
finally {
...
}
I had to deal with the same issues. Simply created a homemade solution that does mostly the same thing in a more flexible way. For anyone that is interested:
/**
* split_addresses Split a list of email addresses with potential validation
* Similar concept as PHPMailer->parseAddresses, but more forgiving
* #param $list - a list of comma delimited email addresses in simple or RFC822 format
* #param $default_name an optional name to add if not present
* #param $validate logical var to indicate to only accept validated emails
* #author Jacques Amar
* #copyright 2019 Amar Micro Inc.
*/
function split_addresses($list, $default_name='', $validate=true) {
$valid_arr = [];
if (empty($list)) { return $valid_arr; }
$split_arr = preg_split('/\s*,\s*/', $list);
foreach ($split_arr as $email_candidate) {
// Validate email_candidate if the form "first last <adrs#email.com>"
$actual_name = $default_name;
$actual_email = $email_candidate;
if (preg_match('/\s*(.+)\s*\<\s*([^#]+#.+)\s*\>/', $email_candidate, $actual_emails) == 1) {
$actual_name = $actual_emails[1];
$actual_email = $actual_emails[2];
}
if ($validate) {
if (filter_var($actual_email, FILTER_VALIDATE_EMAIL)) {
$valid_arr[] = ['address' => $actual_email, 'name' => $actual_name];
}
} else {
$valid_arr[] = ['address' => $actual_email, 'name' => $actual_name];
}
}
return $valid_arr;
}
Should be self explanatory

Webmatrix starter site - new users require email confirmation

I have built my site based around the user management that comes with the starter site template. This works very well, except i need to modify it slightly for my use case. Let me explain:
Currently, when a new user registers, the user is created in the database, but does not let users access any pages that are secured using "WebSecurity.RequireAuthenticatedUser();" until they open and click a confirmation email....
I want to allow users access to certain parts of my site before they confirm their email, is this possible?
Should i be using a different method to WebSecurity.RequireAuthenticatedUser()?
Should i be removing the "requireEmailConfirmation" switch when creating the user??
Currently, it looks like this:
try {
bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
var token = WebSecurity.CreateAccount(email, password, requireEmailConfirmation);
if (requireEmailConfirmation) {
var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/owner/confirm?confirmationCode=" + HttpUtility.UrlEncode(token));
var details = "X-MC-MergeVars: {\"FIRSTNAME\": \"" + firstname + "\", \"LASTNAME\": \"" + lastname + "\", \"CONFIRMADDRESS\": \"" + confirmationUrl + "\"}";
var header = new[]{"X-MC-Template:registertemplate", "Reply-To:noreply#stayinflorida.co.uk", details};
WebMail.Send(
to: email,
subject: "Please confirm your account",
body: "Your confirmation code is: " + token + ". Visit " + confirmationUrl + " to activate your account.",
additionalHeaders: header
);
}
if (requireEmailConfirmation) {
// Thank the user for registering and let them know an email is on its way
Response.Redirect("~/owner/thanks");
} else {
// Navigate back to the homepage and exit
WebSecurity.Login(email, password);
Response.Redirect("~/");
}
} catch (System.Web.Security.MembershipCreateUserException e) {
ModelState.AddFormError(e.Message);
}
for pages they must be registered to use
This goes at the top
#{
if (!WebSecurity.IsAuthenticated) {
Response.Redirect("~/Account/Login?returnUrl="
+ "~/AllRaces.cshtml");
}
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Upcoming";
}
For pages anyone can look at
this goes at the top
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Contact";
}

Search Facebook using PHP SDK

In the last days, I'm working on the application which needs to search for users on Facebook. Since the FQL query for "username" was deprecated/canceled, I have decided to use common search API.
I use PHP so FB PHP SDK is the way I'd prefer. I have used it earlier for FQL queries, just like this:
// $api is already initialized, with access_key, app secret and so on
$users = $api(array(
'method' => 'fql.query',
'query' => "SELECT first_name,last_name FROM user WHERE uid='12345'",
));
I'd like to build the search query in the similar way. Especially, I don't want to urlencode the parameters, specify access key, app secret and all the stuff the SDK is supposed to do for me. However, I haven't been able to build this query using SDK yet. Is there any possibility to do it? If yes, how? I have found long list of sdk-supported "api calls" but I need to build the query for graph.facebook.com/search?arguments.
Thanks in advance.
EDIT: To make it clear, I don't want to build the string by myself. I know this solution works. But imho it's ugly when I have SDK:
$name = urlencode(trim($first_name . " " . $last_name_));
$users = $this->facebook->api("/search?q=$name&type=user&access_token=$key");
Searching User via Graph API using php-sdk 3.1.1
User will need to authorize your app before making a search for
users.
{
"error": {
"message": "A user access token is required to request this resource.",
"type": "OAuthException"
}
}
Php-skd 3.1.1 init.
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'your-app-id',
'secret' => 'your-app-secret',
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
/* */
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
Search includes, encoding search term, setting results limit, and
offset for paging.
<?php
/* Get Search parameter from url or post and urlencode it. */
$q = urlencode($_GET['qs']);
if(!$_GET['qs']){
$q = urlencode($_POST['qs']);
if(!$_POST['qs']){
/* Default Search Term */
$q = "Shawn+E+Carter";
}
}
/* Get Results Limit from url or set default. */
$limit = $_GET['limit'];
if (!$_GET['limit']){
$limit = 60;
}
/* Get Offset from url or set default for paging. */
$offset = $_GET['offset'];
if (!$_GET['offset']){
$offset = 0;
}
/* Make Graph API call to user */
$usersearch = 'search%3Fq='.$q.'%26type=user%26limit='.$limit.'%26offset='.$offset.'';
echo '<pre style="text-align: left;">';
print_r($usersearch);
echo '</pre>';
?>

Resources