Esempio n. 1
0
        /// <summary>
        /// Retweets Message thru the Twitter API
        /// </summary>
        /// <param name="sender">
        /// The source of the event. 
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data. 
        /// </param>
        protected void Retweet_Click(object sender, EventArgs e)
        {
            var twitterName = this.Get<YafBoardSettings>().TwitterUserName.IsSet()
                                  ? "@{0} ".FormatWith(this.Get<YafBoardSettings>().TwitterUserName)
                                  : string.Empty;

            // process message... clean html, strip html, remove bbcode, etc...
            var twitterMsg =
                StringExtensions.RemoveMultipleWhitespace(
                    BBCodeHelper.StripBBCode(
                        HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString((string)this.DataRow["Message"]))));

            var topicUrl = YafBuildLink.GetLinkNotEscaped(ForumPages.posts, true, "m={0}#post{0}", this.DataRow["MessageID"]);

            // Send Retweet Directlly thru the Twitter API if User is Twitter User
            if (Config.TwitterConsumerKey.IsSet() && Config.TwitterConsumerSecret.IsSet() &&
                this.Get<IYafSession>().TwitterToken.IsSet() && this.Get<IYafSession>().TwitterTokenSecret.IsSet() &&
                this.Get<IYafSession>().TwitterTokenSecret.IsSet() && this.PageContext.IsTwitterUser)
            {
                var oAuth = new OAuthTwitter
                {
                    ConsumerKey = Config.TwitterConsumerKey,
                    ConsumerSecret = Config.TwitterConsumerSecret,
                    Token = this.Get<IYafSession>().TwitterToken,
                    TokenSecret = this.Get<IYafSession>().TwitterTokenSecret
                };

                var tweets = new TweetAPI(oAuth);

                tweets.UpdateStatus(
                    TweetAPI.ResponseFormat.json,
                    this.Server.UrlEncode("RT {1}: {0} {2}".FormatWith(twitterMsg.Truncate(100), twitterName, topicUrl)),
                    string.Empty);
            }
            else
            {
                this.Get<HttpResponseBase>().Redirect(
                    "http://twitter.com/share?url={0}&text={1}".FormatWith(
                        this.Server.UrlEncode(this.Get<HttpRequestBase>().Url.ToString()),
                        this.Server.UrlEncode(
                            "RT {1}: {0} {2}".FormatWith(twitterMsg.Truncate(100), twitterName, topicUrl))));
            }
        }
        /// <summary>
        /// Logins/Registers the twitter user.
        /// </summary>
        /// <param name="request">
        /// The page request.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if the login was successfully or not.
        /// </returns>
        public static bool LoginTwitterUser(HttpRequest request, ref string message)
        {
            var oAuth = new OAuthTwitter
            {
                ConsumerKey = Config.TwitterConsumerKey,
                ConsumerSecret = Config.TwitterConsumerSecret
            };

            // Get the access token and secret.
            oAuth.AccessTokenGet(request["oauth_token"], request["oauth_verifier"]);

            if (oAuth.TokenSecret.Length > 0)
            {
                var tweetAPI = new TweetAPI(oAuth);

                var twitterUser = tweetAPI.GetUser();

                if (twitterUser.UserId > 0)
                {
                    // Check if user exists
                    var checkUser = YafContext.Current.Get<MembershipProvider>().GetUser(
                        twitterUser.UserName, false);

                    // Login user if exists
                    if (checkUser != null)
                    {
                        // LOGIN Existing User
                        var yafUser = YafUserProfile.GetProfile(checkUser.UserName);

                        var yafUserData = new CombinedUserDataHelper(checkUser);

                        if (!yafUserData.UseSingleSignOn)
                        {
                            message = YafContext.Current.Get<ILocalization>().GetText(
                                "LOGIN", "SSO_DEACTIVATED_BYUSER");

                            return false;
                        }

                        if (yafUser.Twitter.Equals(twitterUser.UserName) && yafUser.TwitterId.Equals(twitterUser.UserId.ToString()))
                        {
                            LoginTwitterSuccess(false, oAuth, yafUserData.UserID, checkUser);

                            return true;
                        }

                        message = YafContext.Current.Get<ILocalization>().GetText("LOGIN", "SSO_TWITTERID_NOTMATCH");

                        return false;
                    }

                    // Create User if not exists?! Doesnt work because there is no Email
                    var email = "{0}@twitter.com".FormatWith(twitterUser.UserName);

                    // Create User if not exists?!
                    if (YafContext.Current.Get<YafBoardSettings>().RegisterNewFacebookUser &&
                        !YafContext.Current.Get<YafBoardSettings>().DisableRegistrations)
                    {
                        MembershipCreateStatus status;

                        var pass = Membership.GeneratePassword(32, 16);
                        var securityAnswer = Membership.GeneratePassword(64, 30);

                        MembershipUser user = YafContext.Current.Get<MembershipProvider>().CreateUser(
                            twitterUser.UserName, pass, email, "Answer is a generated Pass", securityAnswer, true, null, out status);

                        // setup inital roles (if any) for this user
                        RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, twitterUser.UserName);

                        // create the user in the YAF DB as well as sync roles...
                        int? userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

                        // create empty profile just so they have one
                        YafUserProfile userProfile = YafUserProfile.GetProfile(twitterUser.UserName);

                        userProfile.TwitterId = twitterUser.UserId.ToString();
                        userProfile.Twitter = twitterUser.UserName;
                        userProfile.Homepage = !string.IsNullOrEmpty(twitterUser.Url)
                                                   ? twitterUser.Url
                                                   : "http://twitter.com/{0}".FormatWith(twitterUser.UserName);
                        userProfile.RealName = twitterUser.Name;
                        userProfile.Interests = twitterUser.Description;
                        userProfile.Location = twitterUser.Location;

                        userProfile.Save();

                        // setup their inital profile information
                        userProfile.Save();

                        if (userID == null)
                        {
                            // something is seriously wrong here -- redirect to failure...
                            message = YafContext.Current.Get<ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED");

                            return false;
                        }

                        if (YafContext.Current.Get<YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
                        {
                            // send user register notification to the following admin users...
                            SendRegistrationNotificationEmail(user);
                        }

                        // save the time zone...
                        int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

                        // send user register notification to the following admin users...
                        SendRegistrationMessageToUser(user, pass, securityAnswer, userId, oAuth);

                        LegacyDb.user_save(
                            userId,
                            YafContext.Current.PageBoardID,
                            twitterUser.UserName,
                            null,
                            email,
                            0,
                            null,
                            null,
                            null,
                            true,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null,
                            null);

                        bool autoWatchTopicsEnabled = YafContext.Current.Get<YafBoardSettings>().DefaultNotificationSetting ==
                                                      UserNotificationSetting.TopicsIPostToOrSubscribeTo;

                        // save the settings...
                        LegacyDb.user_savenotification(
                            userId,
                            true,
                            autoWatchTopicsEnabled,
                            YafContext.Current.Get<YafBoardSettings>().DefaultNotificationSetting,
                            YafContext.Current.Get<YafBoardSettings>().DefaultSendDigestEmail);

                        // save avatar
                        if (!string.IsNullOrEmpty(twitterUser.ProfileImageUrl))
                        {
                            LegacyDb.user_saveavatar(
                                userId,
                                twitterUser.ProfileImageUrl,
                                null,
                                null);
                        }

                        LoginTwitterSuccess(true, oAuth, userId, user);

                        message = YafContext.Current.Get<ILocalization>().GetText("LOGIN", "UPDATE_EMAIL");

                        return true;
                    }

                    message = YafContext.Current.Get<ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED");

                    return false;
                }
            }

            message = YafContext.Current.Get<ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED");

            return false;
        }
        /// <summary>
        /// Send an Private Message to the Newly Created User with
        /// his Account Info (Pass, Security Question and Answer)
        /// </summary>
        /// <param name="user">
        /// The user.
        /// </param>
        /// <param name="pass">
        /// The pass.
        /// </param>
        /// <param name="securityAnswer">
        /// The security answer.
        /// </param>
        /// <param name="userId">
        /// The user Id.
        /// </param>
        /// <param name="oAuth">
        /// The o Auth.
        /// </param>
        private static void SendRegistrationMessageToUser([NotNull] MembershipUser user, [NotNull] string pass, [NotNull] string securityAnswer, [NotNull] int userId, OAuthTwitter oAuth)
        {
            var notifyUser = new YafTemplateEmail();

            string subject =
                YafContext.Current.Get<ILocalization>().GetText("COMMON", "NOTIFICATION_ON_NEW_FACEBOOK_USER_SUBJECT").FormatWith(
                    YafContext.Current.Get<YafBoardSettings>().Name);

            notifyUser.TemplateParams["{user}"] = user.UserName;
            notifyUser.TemplateParams["{email}"] = user.Email;
            notifyUser.TemplateParams["{pass}"] = pass;
            notifyUser.TemplateParams["{answer}"] = securityAnswer;
            notifyUser.TemplateParams["{forumname}"] = YafContext.Current.Get<YafBoardSettings>().Name;

            string emailBody = notifyUser.ProcessTemplate("NOTIFICATION_ON_FACEBOOK_REGISTER");

            var messageFlags = new MessageFlags { IsHtml = false, IsBBCode = true };

            // Send Message also as DM to Twitter.
            var tweetApi = new TweetAPI(oAuth);

            if (YafContext.Current.Get<YafBoardSettings>().AllowPrivateMessages)
            {
                LegacyDb.pmessage_save(2, userId, subject, emailBody, messageFlags.BitValue);

                string message = "{0}. {1}".FormatWith(
                subject, YafContext.Current.Get<ILocalization>().GetText("LOGIN", "TWITTER_DM"));

                tweetApi.SendDirectMessage(TweetAPI.ResponseFormat.json, user.UserName, message.Truncate(140));
            }
            else
            {
                string message = YafContext.Current.Get<ILocalization>().GetTextFormatted(
                    "LOGIN", "TWITTER_DM", YafContext.Current.Get<YafBoardSettings>().Name, user.UserName, pass);

                tweetApi.SendDirectMessage(TweetAPI.ResponseFormat.json, user.UserName, message.Truncate(140));
            }
        }
		/// <summary>
		/// The options menu_ item click.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">
		/// The Pop Event Arguments.
		/// </param>
		private void ShareMenu_ItemClick([NotNull] object sender, [NotNull] PopEventArgs e)
		{
			var topicUrl = YafBuildLink.GetLinkNotEscaped(ForumPages.posts, true, "t={0}", this.PageContext.PageTopicID);
			switch (e.Item.ToLower())
			{
				case "email":
					this.EmailTopic_Click(sender, e);
					break;
				case "tumblr":
					{
						// process message... clean html, strip html, remove bbcode, etc...
						var tumblrMsg =
								StringExtensions.RemoveMultipleWhitespace(
										BBCodeHelper.StripBBCode(
												HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString((string)this._topic["Topic"]))));

						var meta = this.Page.Header.FindControlType<HtmlMeta>();

						string description = string.Empty;

						if (meta.Any(x => x.Name.Equals("description")))
						{
							var descriptionMeta = meta.FirstOrDefault(x => x.Name.Equals("description"));
							if (descriptionMeta != null)
							{
								description = "&description={0}".FormatWith(descriptionMeta.Content);
							}
						}

						var tumblrUrl =
								"http://www.tumblr.com/share/link?url={0}&name={1}{2}".FormatWith(
										this.Server.UrlEncode(topicUrl), tumblrMsg, description);

						this.Get<HttpResponseBase>().Redirect(tumblrUrl);
					}

					break;
				case "retweet":
					{
						var twitterName = this.Get<YafBoardSettings>().TwitterUserName.IsSet()
																	? "@{0} ".FormatWith(this.Get<YafBoardSettings>().TwitterUserName)
																	: string.Empty;

						// process message... clean html, strip html, remove bbcode, etc...
						var twitterMsg =
								StringExtensions.RemoveMultipleWhitespace(
										BBCodeHelper.StripBBCode(
												HtmlHelper.StripHtml(HtmlHelper.CleanHtmlString((string)this._topic["Topic"]))));

						var tweetUrl =
								"http://twitter.com/share?url={0}&text={1}".FormatWith(
										this.Server.UrlEncode(topicUrl),
										this.Server.UrlEncode(
												"RT {1}Thread: {0}".FormatWith(twitterMsg.Truncate(100), twitterName)));

						// Send Retweet Directlly thru the Twitter API if User is Twitter User
						if (Config.TwitterConsumerKey.IsSet() && Config.TwitterConsumerSecret.IsSet() &&
								this.Get<IYafSession>().TwitterToken.IsSet() &&
								this.Get<IYafSession>().TwitterTokenSecret.IsSet() && this.PageContext.IsTwitterUser)
						{
							var oAuth = new OAuthTwitter
									{
										ConsumerKey = Config.TwitterConsumerKey,
										ConsumerSecret = Config.TwitterConsumerSecret,
										Token = this.Get<IYafSession>().TwitterToken,
										TokenSecret = this.Get<IYafSession>().TwitterTokenSecret
									};

							var tweets = new TweetAPI(oAuth);

							tweets.UpdateStatus(
									TweetAPI.ResponseFormat.json,
									this.Server.UrlEncode(
											"RT {1}: {0} {2}".FormatWith(twitterMsg.Truncate(100), twitterName, topicUrl)),
									string.Empty);
						}
						else
						{
							this.Get<HttpResponseBase>().Redirect(tweetUrl);
						}
					}

					break;
				case "digg":
					{
						var diggUrl =
								"http://digg.com/submit?url={0}&title={1}".FormatWith(
										this.Server.UrlEncode(topicUrl), this.Server.UrlEncode((string)this._topic["Topic"]));

						this.Get<HttpResponseBase>().Redirect(diggUrl);
					}

					break;
				case "reddit":
					{
						var redditUrl =
								"http://www.reddit.com/submit?url={0}&title={1}".FormatWith(
										this.Server.UrlEncode(topicUrl), this.Server.UrlEncode((string)this._topic["Topic"]));

						this.Get<HttpResponseBase>().Redirect(redditUrl);
					}

					break;
				case "googleplus":
					{
						var googlePlusUrl =
								"https://plusone.google.com/_/+1/confirm?hl=en&url={0}".FormatWith(
										this.Server.UrlEncode(topicUrl));

						this.Get<HttpResponseBase>().Redirect(googlePlusUrl);
					}

					break;
				default:
					throw new ApplicationException(e.Item);
			}
		}