Esempio n. 1
0
        // update an existing index
        static void threadproc_update(object obj)
        {
            // just to be safe, make the worker threads wait for each other
            //System.Console.Beep(540, 20);
            lock (my_lock) // prevent contention between searching and writing?
            {
                //System.Console.Beep(840, 20);
                try
                {
                    if (searcher != null)
                    {
                        try
                        {
                            searcher.Close();
                        }
                        catch (Exception e)
                        {
                            Util.write_to_log("Exception closing lucene searcher:" + e.Message);
                            Util.write_to_log(e.StackTrace);
                        }
                        searcher = null;
                    }

                    Lucene.Net.Index.IndexModifier modifier = new Lucene.Net.Index.IndexModifier(index_path, anal, false);

                    // same as buid, but uses "modifier" instead of write.
                    // uses additional "where" clause for bugid

                    int bug_id = (int)obj;

                    Util.write_to_log("started updating Lucene index using folder " + MyLucene.index_path);

                    modifier.DeleteDocuments(new Lucene.Net.Index.Term("bg_id", Convert.ToString(bug_id)));

                    string sql = @"
select bg_id, 
$custom_cols
isnull(bg_tags,'') bg_tags,
bg_short_desc    
from bugs where bg_id = $bugid";

                    sql = sql.Replace("$bugid", Convert.ToString(bug_id));

                    DataSet ds_text_custom_cols = get_text_custom_cols();

                    sql = sql.Replace("$custom_cols", get_text_custom_cols_names(ds_text_custom_cols));

                    // index the bugs
                    DataRow dr = DbUtil.get_datarow(sql);

                    modifier.AddDocument(MyLucene.create_doc(
                                             (int)dr["bg_id"],
                                             0,
                                             "desc",
                                             (string)dr["bg_short_desc"]));

                    // tags
                    string tags = (string)dr["bg_tags"];
                    if (tags != "")
                    {
                        modifier.AddDocument(MyLucene.create_doc(
                                                 (int)dr["bg_id"],
                                                 0,
                                                 "tags",
                                                 tags));
                    }

                    // custom text fields
                    foreach (DataRow dr_custom_col in ds_text_custom_cols.Tables[0].Rows)
                    {
                        string name = (string)dr_custom_col["name"];
                        string val  = Convert.ToString(dr[name]);
                        if (val != "")
                        {
                            modifier.AddDocument(MyLucene.create_doc(
                                                     (int)dr["bg_id"],
                                                     0,
                                                     name.Replace("'", "''"),
                                                     val));
                        }
                    }


                    // index the bug posts
                    DataSet ds = DbUtil.get_dataset(@"
select bp_bug, bp_id, 
isnull(bp_comment_search,bp_comment) [text] 
from bug_posts 
where bp_type <> 'update'
and bp_hidden_from_external_users = 0
and bp_bug = " + Convert.ToString(bug_id));

                    foreach (DataRow dr2 in ds.Tables[0].Rows)
                    {
                        modifier.AddDocument(MyLucene.create_doc(
                                                 (int)dr2["bp_bug"],
                                                 (int)dr2["bp_id"],
                                                 "post",
                                                 (string)dr2["text"]));
                    }

                    modifier.Flush();
                    modifier.Close();
                    Util.write_to_log("done updating Lucene index");
                }
                catch (Exception e)
                {
                    Util.write_to_log("exception updating Lucene index: " + e.Message);
                    Util.write_to_log(e.StackTrace);
                }
            }
        }
Esempio n. 2
0
        //*************************************************************

        public static bool fetch_messages(string project_user, string project_password, int projectid)
        {
            // experimental, under construction

            POP3Client.POP3client client = new POP3Client.POP3client(Pop3ReadInputStreamCharByChar);

            string[] SubjectCannotContainStrings = Util.rePipes.Split(Pop3SubjectCannotContain);
            string[] FromCannotContainStrings    = Util.rePipes.Split(Pop3FromCannotContain);

            //try
            {
                System.Data.DataRow defaults = Bug.get_bug_defaults();

                //int projectid = (int)defaults["pj"];
                int categoryid = (int)defaults["ct"];
                int priorityid = (int)defaults["pr"];
                int statusid   = (int)defaults["st"];
                int udfid      = (int)defaults["udf"];

                Util.write_to_log("pop3:" + client.connect(Pop3Server, Pop3Port, Pop3UseSSL));

                Util.write_to_log("pop3:sending POP3 command USER");
                Util.write_to_log("pop3:" + client.USER(project_user));

                Util.write_to_log("pop3:sending POP3 command PASS");
                Util.write_to_log("pop3:" + client.PASS(project_password));

                Util.write_to_log("pop3:sending POP3 command STAT");
                Util.write_to_log("pop3:" + client.STAT());

                Util.write_to_log("pop3:sending POP3 command LIST");
                string list;
                list = client.LIST();
                Util.write_to_log("pop3:list follows:");
                Util.write_to_log(list);

                string[] messages = null;
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\r\n");
                messages = regex.Split(list);

                int end = messages.Length - 1;

                // loop through the messages
                for (int i = 1; i < end; i++)
                {
                    int    space_pos          = messages[i].IndexOf(" ");
                    int    message_number     = Convert.ToInt32(messages[i].Substring(0, space_pos));
                    string message_raw_string = client.RETR(message_number);

                    if (Pop3WriteRawMessagesToLog)
                    {
                        Util.write_to_log("raw email message:");
                        Util.write_to_log(message_raw_string);
                    }

                    SharpMimeMessage mime_message = MyMime.get_sharp_mime_message(message_raw_string);

                    string from_addr = MyMime.get_from_addr(mime_message);
                    string subject   = MyMime.get_subject(mime_message);


                    if (Pop3SubjectMustContain != "" && subject.IndexOf(Pop3SubjectMustContain) < 0)
                    {
                        Util.write_to_log("skipping because subject does not contain: " + Pop3SubjectMustContain);
                        continue;
                    }

                    bool bSkip = false;

                    for (int k = 0; k < SubjectCannotContainStrings.Length; k++)
                    {
                        if (SubjectCannotContainStrings[k] != "")
                        {
                            if (subject.IndexOf(SubjectCannotContainStrings[k]) >= 0)
                            {
                                Util.write_to_log("skipping because subject cannot contain: " + SubjectCannotContainStrings[k]);
                                bSkip = true;
                                break;  // done checking, skip this message
                            }
                        }
                    }

                    if (bSkip)
                    {
                        continue;
                    }

                    if (Pop3FromMustContain != "" && from_addr.IndexOf(Pop3FromMustContain) < 0)
                    {
                        Util.write_to_log("skipping because from does not contain: " + Pop3FromMustContain);
                        continue; // that is, skip to next message
                    }

                    for (int k = 0; k < FromCannotContainStrings.Length; k++)
                    {
                        if (FromCannotContainStrings[k] != "")
                        {
                            if (from_addr.IndexOf(FromCannotContainStrings[k]) >= 0)
                            {
                                Util.write_to_log("skipping because from cannot contain: " + FromCannotContainStrings[k]);
                                bSkip = true;
                                break; // done checking, skip this message
                            }
                        }
                    }

                    if (bSkip)
                    {
                        continue;
                    }


                    int    bugid   = MyMime.get_bugid_from_subject(ref subject);
                    string cc      = MyMime.get_cc(mime_message);
                    string comment = MyMime.get_comment(mime_message);
                    string headers = MyMime.get_headers_for_comment(mime_message);
                    if (headers != "")
                    {
                        comment = headers + "\n" + comment;
                    }

                    Security security = MyMime.get_synthesized_security(mime_message, from_addr, Pop3ServiceUsername);
                    int      orgid    = security.user.org;

                    if (bugid == 0)
                    {
                        if (security.user.forced_project != 0)
                        {
                            projectid = security.user.forced_project;
                        }

                        if (subject.Length > 200)
                        {
                            subject = subject.Substring(0, 200);
                        }

                        Bug.NewIds new_ids = Bug.insert_bug(
                            subject,
                            security,
                            "", // tags
                            projectid,
                            orgid,
                            categoryid,
                            priorityid,
                            statusid,
                            0,          // assignedid,
                            udfid,
                            "", "", "", // project specific dropdown values
                            comment,
                            comment,
                            from_addr,
                            cc,
                            "text/plain",
                            false, // internal only
                            null,  // custom columns
                            false);

                        MyMime.add_attachments(mime_message, new_ids.bugid, new_ids.postid, security);

                        // your customizations
                        Bug.apply_post_insert_rules(new_ids.bugid);

                        Bug.send_notifications(Bug.INSERT, new_ids.bugid, security);
                        WhatsNew.add_news(new_ids.bugid, subject, "added", security);

                        MyPop3.auto_reply(new_ids.bugid, from_addr, subject, projectid);
                    }
                    else // update existing
                    {
                        string StatusResultingFromIncomingEmail = Util.get_setting("StatusResultingFromIncomingEmail", "0");

                        string sql = "";

                        if (StatusResultingFromIncomingEmail != "0")
                        {
                            sql = @"update bugs
				                set bg_status = $st
				                where bg_id = $bg
				                "                ;

                            sql = sql.Replace("$st", StatusResultingFromIncomingEmail);
                        }

                        sql += "select bg_short_desc from bugs where bg_id = $bg";
                        sql  = sql.Replace("$bg", Convert.ToString(bugid));
                        DataRow dr2 = DbUtil.get_datarow(sql);

                        // Add a comment to existing bug.
                        int postid = Bug.insert_comment(
                            bugid,
                            security.user.usid, // (int) dr["us_id"],
                            comment,
                            comment,
                            from_addr,
                            cc,
                            "text/plain",
                            false); // internal only

                        MyMime.add_attachments(mime_message, bugid, postid, security);
                        Bug.send_notifications(Bug.UPDATE, bugid, security);
                        WhatsNew.add_news(bugid, (string)dr2["bg_short_desc"], "updated", security);
                    }

                    if (Pop3DeleteMessagesOnServer)
                    {
                        Util.write_to_log("sending POP3 command DELE");
                        Util.write_to_log(client.DELE(message_number));
                    }
                }
            }
            //catch (Exception ex)
            //{
            //    Util.write_to_log("pop3:exception in fetch_messages: " + ex.Message);
            //    error_count++;
            //    if (error_count > Pop3TotalErrorsAllowed)
            //    {
            //        return false;
            //    }
            //}


            Util.write_to_log("pop3:quit");
            Util.write_to_log("pop3:" + client.QUIT());
            return(true);
        }
Esempio n. 3
0
        ///////////////////////////////////////////////////////////////////////
        protected void Page_Load(Object sender, EventArgs e)
        {
            Master.Menu.SelectedItem = Util.get_setting("PluralBugLabel", "bugs");
            Util.do_not_cache(Response);


            if (User.IsInRole(BtnetRoles.Admin) || User.Identity.GetCanEditAndDeletePosts())
            {
                //
            }
            else
            {
                Response.Write("You are not allowed to use this page.");
                Response.End();
            }

            Page.Title = Util.get_setting("AppTitle", "BugTracker.NET") + " - "
                         + "edit comment";

            msg.InnerText = "";

            id = Convert.ToInt32(Request["id"]);

            if (!IsPostBack)
            {
                sql = new SQLString(@"select bp_comment, bp_type,
        isnull(bp_comment_search,bp_comment) bp_comment_search,
        isnull(bp_content_type,'') bp_content_type,
        bp_bug, bp_hidden_from_external_users
        from bug_posts where bp_id = @id");
            }
            else
            {
                sql = new SQLString(@"select bp_bug, bp_type,
        isnull(bp_content_type,'') bp_content_type,
        bp_hidden_from_external_users
        from bug_posts where bp_id = @id");
            }

            sql = sql.AddParameterWithValue("id", Convert.ToString(id));
            DataRow dr = DbUtil.get_datarow(sql);

            bugid = (int)dr["bp_bug"];

            int permission_level = Bug.get_bug_permission_level(bugid, User.Identity);

            if (permission_level == PermissionLevel.None ||
                permission_level == PermissionLevel.ReadOnly ||
                (string)dr["bp_type"] != "comment")
            {
                Response.Write("You are not allowed to edit this item");
                Response.End();
            }

            string content_type = (string)dr["bp_content_type"];

            if (User.Identity.GetUseFCKEditor() && content_type == "text/html" && Util.get_setting("DisableFCKEditor", "0") == "0")
            {
                use_fckeditor = true;
            }
            else
            {
                use_fckeditor = false;
            }

            if (User.Identity.GetIsExternalUser() || Util.get_setting("EnableInternalOnlyPosts", "0") == "0")
            {
                internal_only.Visible       = false;
                internal_only_label.Visible = false;
            }

            if (!IsPostBack)
            {
                internal_only.Checked = Convert.ToBoolean((int)dr["bp_hidden_from_external_users"]);

                if (use_fckeditor)
                {
                    comment.Value = (string)dr["bp_comment"];
                }
                else
                {
                    comment.Value = (string)dr["bp_comment_search"];
                }
            }
            else
            {
                on_update();
            }
        }
Esempio n. 4
0
        ///////////////////////////////////////////////////////////////////////
        // create a new index
        static void threadproc_build(object obj)
        {
            lock (my_lock)
            {
                try
                {
                    System.Web.HttpApplicationState app = (System.Web.HttpApplicationState)obj;

                    Util.write_to_log("started creating Lucene index using folder " + MyLucene.index_path);
                    Lucene.Net.Index.IndexWriter writer = new Lucene.Net.Index.IndexWriter(index_path, anal, true);



                    string  sql = @"
select bg_id,   
$custom_cols
isnull(bg_tags,'') bg_tags,
bg_short_desc
from bugs";
                    DataSet ds_text_custom_cols = get_text_custom_cols();

                    sql = sql.Replace("$custom_cols", get_text_custom_cols_names(ds_text_custom_cols));

                    // index the bugs
                    DataSet ds = DbUtil.get_dataset(sql);

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        // desc
                        writer.AddDocument(MyLucene.create_doc(
                                               (int)dr["bg_id"],
                                               0,
                                               "desc",
                                               (string)dr["bg_short_desc"]));

                        // tags
                        string tags = (string)dr["bg_tags"];
                        if (tags != "")
                        {
                            writer.AddDocument(MyLucene.create_doc(
                                                   (int)dr["bg_id"],
                                                   0,
                                                   "tags",
                                                   tags));
                        }

                        // custom text fields
                        foreach (DataRow dr_custom_col in ds_text_custom_cols.Tables[0].Rows)
                        {
                            string name = (string)dr_custom_col["name"];
                            string val  = Convert.ToString(dr[name]);
                            if (val != "")
                            {
                                writer.AddDocument(MyLucene.create_doc(
                                                       (int)dr["bg_id"],
                                                       0,
                                                       name.Replace("'", "''"),
                                                       val));
                            }
                        }
                    }

                    // index the bug posts
                    ds = DbUtil.get_dataset(@"
select bp_bug, bp_id, 
isnull(bp_comment_search,bp_comment) [text] 
from bug_posts 
where bp_type <> 'update'
and bp_hidden_from_external_users = 0");

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        writer.AddDocument(MyLucene.create_doc(
                                               (int)dr["bp_bug"],
                                               (int)dr["bp_id"],
                                               "post",
                                               (string)dr["text"]));
                    }

                    writer.Optimize();
                    writer.Close();
                    Util.write_to_log("done creating Lucene index");
                }
                catch (Exception e)
                {
                    Util.write_to_log("exception building Lucene index: " + e.Message);
                    Util.write_to_log(e.StackTrace);
                }
            }
        }
Esempio n. 5
0
        ///////////////////////////////////////////////////////////////////////
        public void Page_Load(Object sender, EventArgs e)
        {
            Util.set_context(HttpContext.Current);
            Util.do_not_cache(Response);

            if (Util.get_setting("ShowForgotPasswordLink", "0") == "0")
            {
                Response.Write("Sorry, Web.config ShowForgotPasswordLink is set to 0");
                Response.End();
            }

            if (!IsPostBack)
            {
                Page.Header.Title = Util.get_setting("AppTitle", "BugTracker.NET") + " - "
                                    + "forgot password";
            }
            else
            {
                msg.InnerHtml = "";

                if (email.Value == "" && username.Value == "")
                {
                    msg.InnerHtml = "Enter either your Username or your Email address.";
                }
                else if (email.Value != "" && !Util.validate_email(email.Value))
                {
                    msg.InnerHtml = "Format of email address is invalid.";
                }
                else
                {
                    int user_count = 0;
                    int user_id    = 0;

                    if (email.Value != "" && username.Value == "")
                    {
                        // check if email exists
                        SQLString sql = new SQLString("select count(1) from users where us_email = @email");
                        sql.AddParameterWithValue("email", email.Value);
                        user_count = (int)DbUtil.execute_scalar(sql);

                        if (user_count == 1)
                        {
                            sql = new SQLString("select us_id from users where us_email = @email");
                            sql.AddParameterWithValue("email", email.Value);
                            user_id = (int)DbUtil.execute_scalar(sql);
                        }
                    }
                    else if (email.Value == "" && username.Value != "")
                    {
                        // check if email exists
                        SQLString sql = new SQLString(
                            "select count(1) from users where isnull(us_email,'') != '' and  us_username = @username");
                        sql.AddParameterWithValue("username", username.Value);
                        user_count = (int)DbUtil.execute_scalar(sql);

                        if (user_count == 1)
                        {
                            sql = new SQLString("select us_id from users where us_username = @username");
                            sql.AddParameterWithValue("username", username.Value);
                            user_id = (int)DbUtil.execute_scalar(sql);
                        }
                    }
                    else if (email.Value != "" && username.Value != "")
                    {
                        // check if email exists
                        SQLString sql = new SQLString(
                            "select count(1) from users where us_username = @username and us_email = @email");
                        sql.AddParameterWithValue("username", username.Value);
                        sql.AddParameterWithValue("email", email.Value);
                        user_count = (int)DbUtil.execute_scalar(sql);

                        if (user_count == 1)
                        {
                            sql = new SQLString(
                                "select us_id from users where us_username = @username and us_email = @email");
                            sql.AddParameterWithValue("username", username.Value);
                            sql.AddParameterWithValue("email", email.Value);
                            user_id = (int)DbUtil.execute_scalar(sql);
                        }
                    }


                    if (user_count == 1)
                    {
                        string guid = Guid.NewGuid().ToString();
                        var    sql  = new SQLString(@"
declare @username nvarchar(255)
declare @email nvarchar(255)

select @username = us_username, @email = us_email
	from users where us_id = @user_id

insert into emailed_links
	(el_id, el_date, el_email, el_action, el_user_id)
	values (@guid, getdate(), @email, N'forgot', @user_id)

select @username us_username, @email us_email");

                        sql = sql.AddParameterWithValue("guid", guid);
                        sql = sql.AddParameterWithValue("user_id", Convert.ToString(user_id));

                        DataRow dr = DbUtil.get_datarow(sql);

                        string result = Email.send_email(
                            (string)dr["us_email"],
                            Util.get_setting("NotificationEmailFrom", ""),
                            "", // cc
                            "reset password",

                            "Click to <a href='"
                            + Util.get_setting("AbsoluteUrlPrefix", "")
                            + "change_password.aspx?id="
                            + guid
                            + "'>reset password</a> for user \""
                            + (string)dr["us_username"]
                            + "\".",

                            MailFormat.Html);

                        if (result == "")
                        {
                            msg.InnerHtml = "An email with password info has been sent to you.";
                        }
                        else
                        {
                            msg.InnerHtml  = "There was a problem sending the email.";
                            msg.InnerHtml += "<br>" + result;
                        }
                    }
                    else
                    {
                        msg.InnerHtml = "Unknown username or email address.<br>Are you sure you spelled everything correctly?<br>Try just username, just email, or both.";
                    }
                }
            }
        }
        public BugQueryResult ExecuteQuery(IIdentity identity, int start, int length, string orderBy, string sortDirection, bool idOnly, BugQueryFilter[] filters = null)
        {
            if (!string.IsNullOrEmpty(orderBy) && !_columnNames.Contains(orderBy))
            {
                throw new ArgumentException("Invalid order by column specified: {0}", orderBy);
            }

            bool   hasFilters      = filters != null && filters.Any();
            string columnsToSelect = idOnly ? "id" : "*";
            var    innerSql        = GetInnerSql(identity);
            var    countSql        = string.Format("SELECT COUNT(1) FROM ({0}) t", GetInnerSql(identity));

            SQLString sqlString = new SQLString(countSql);

            sqlString.Append(";");
            if (hasFilters)
            {
                sqlString.Append(countSql);
                ApplyWhereClause(sqlString, filters);
                sqlString.Append(";");
            }

            var bugsSql = string.Format("SELECT t.{0} FROM ({1}) t", columnsToSelect, innerSql);

            sqlString.Append(bugsSql);


            sqlString.Append(" WHERE id IN (");
            var innerBugsSql = string.Format("SELECT t.id FROM ({0}) t", innerSql);

            sqlString.Append(innerBugsSql);

            ApplyWhereClause(sqlString, filters);


            if (hasFilters)
            {
                foreach (var filter in filters)
                {
                    sqlString.AddParameterWithValue(GetCleanParameterName(filter.Column), filter.Value);
                }
            }

            sqlString.Append(" ORDER BY ");

            sqlString.Append(BuildDynamicOrderByClause(orderBy, sortDirection));

            sqlString.Append(" OFFSET @offset ROWS FETCH NEXT @page_size ROWS ONLY)");


            int userId = identity.GetUserId();

            sqlString.AddParameterWithValue("@ME", userId);
            sqlString.AddParameterWithValue("page_size", length > 0 ? length : MaxLength);
            sqlString.AddParameterWithValue("offset", start);
            DataSet dataSet = DbUtil.get_dataset(sqlString);

            var countUnfiltered   = Convert.ToInt32(dataSet.Tables[0].Rows[0][0]);
            var countFiltered     = hasFilters ? Convert.ToInt32(dataSet.Tables[1].Rows[0][0]) : countUnfiltered;
            var bugDataTableIndex = hasFilters ? 2 : 1;

            return(new BugQueryResult
            {
                CountUnfiltered = countUnfiltered,
                CountFiltered = countFiltered,
                Data = dataSet.Tables[bugDataTableIndex]
            });
        }
        ///////////////////////////////////////////////////////////////////////
        protected void Page_Load(Object sender, EventArgs e)
        {
            Util.do_not_cache(Response);

            string id = Util.sanitize_integer(Request["id"]);

            if (!User.IsInRole(BtnetRoles.Admin))
            {
                sql = new SQLString(@"select us_created_user, us_admin from users where us_id = @us");
                sql = sql.AddParameterWithValue("us", id);
                DataRow dr = DbUtil.get_datarow(sql);

                if (User.Identity.GetUserId() != (int)dr["us_created_user"])
                {
                    Response.Write("You not allowed to delete this user, because you didn't create it.");
                    Response.End();
                }
                else if ((int)dr["us_admin"] == 1)
                {
                    Response.Write("You not allowed to delete this user, because it is an admin.");
                    Response.End();
                }
            }

            if (IsPostBack)
            {
                // do delete here
                sql = new SQLString(@"
delete from emailed_links where el_username in (select us_username from users where us_id = @us)
delete users where us_id = @us
delete project_user_xref where pu_user = @us
delete bug_subscriptions where bs_user = @us
delete bug_user where bu_user = @us
delete queries where qu_user = @us
delete queued_notifications where qn_user = @us
delete dashboard_items where ds_user = @us");

                sql = sql.AddParameterWithValue("us", Util.sanitize_integer(row_id.Value));
                DbUtil.execute_nonquery(sql);
                Server.Transfer("users.aspx");
            }
            else
            {
                Page.Header.Title = Util.get_setting("AppTitle", "BugTracker.NET") + " - "
                                    + "delete user";

                sql = new SQLString(@"declare @cnt int
select @cnt = count(1) from bugs where bg_reported_user = @us or bg_assigned_to_user = @us
if @cnt = 0
begin
	select @cnt = count(1) from bug_posts where bp_user = @us
end
select us_username, @cnt [cnt] from users where us_id = @us");


                sql = sql.AddParameterWithValue("us", id);

                DataRow dr = DbUtil.get_datarow(sql);

                if ((int)dr["cnt"] > 0)
                {
                    Response.Write("You can't delete user \""
                                   + Convert.ToString(dr["us_username"])
                                   + "\" because some bugs or bug posts still reference it.");
                    Response.End();
                }
                else
                {
                    confirm_href.InnerText = "confirm delete of \""
                                             + Convert.ToString(dr["us_username"])
                                             + "\"";

                    row_id.Value = id;
                }
            }
        }
Esempio n. 8
0
		///////////////////////////////////////////////////////////////////////
		public static void print_bug (HttpResponse Response, DataRow dr, Security security, 
            bool include_style, 
            bool images_inline, 
            bool history_inline,
            bool internal_posts)
		{

			int bugid = Convert.ToInt32(dr["id"]);
			string string_bugid = Convert.ToString(bugid);

            if (include_style) // when sending emails
            {
                Response.Write("\n<style>\n");

                // If this file exists, use it.

                string map_path = (string) HttpRuntime.Cache["MapPath"];

                string css_for_email_file = map_path + "\\custom\\btnet_css_for_email.css";

                try
                {
                    if (System.IO.File.Exists(css_for_email_file))
                    {
                        Response.WriteFile(css_for_email_file);
					    Response.Write("\n");
                    }
                    else
                    {
                        css_for_email_file = map_path + "\\Content\\bootstrap.min.css";
                        Response.WriteFile(css_for_email_file);
					    Response.Write("\n");
                        //css_for_email_file = map_path + "\\custom\\" + "btnet_custom.css";
                        //if (System.IO.File.Exists(css_for_email_file))
                        //{
                        //    Response.WriteFile(css_for_email_file);
                        //    Response.Write("\n");
                        //}
                    }
                }
                catch (Exception e)
                {
                    Util.write_to_log("Exception trying to read css file for email \"" 
                        + css_for_email_file
                        + "\":" 
                        + e.Message);
                }

                // underline links in the emails to make them more obvious
                Response.Write("\na {text-decoration: underline; }");
                Response.Write("\na:visited {text-decoration: underline; }");
                Response.Write("\na:hover {text-decoration: underline; }");
                Response.Write("\n</style>\n");
            }

			Response.Write ("<body style='background:white'>");
			Response.Write ("<b>"
				+ Util.capitalize_first_letter(Util.get_setting("SingularBugLabel","bug"))
				+ " ID:&nbsp;<a href="
				+ Util.get_setting("AbsoluteUrlPrefix","http://127.0.0.1/")
				+ "edit_bug.aspx?id="
				+ string_bugid
				+ ">"
				+ string_bugid
				+ "</a>");

            if (Util.get_setting("EnableMobile", "0") == "1")
            {
                Response.Write(
                    "&nbsp;&nbsp;&nbsp;&nbsp;Mobile link:&nbsp;<a href="
                    + Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/")
                    + "mbug.aspx?id="
                    + string_bugid
                    + ">"
                    + Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/")
                    + "mbug.aspx?id="
                    + string_bugid
                    + "</a>");

            }

            Response.Write("<br>");

			Response.Write ("Short desc:&nbsp;<a href="
				+ Util.get_setting("AbsoluteUrlPrefix","http://127.0.0.1/")
				+ "edit_bug.aspx?id="
				+ string_bugid
				+ ">"
				+ HttpUtility.HtmlEncode((string)dr["short_desc"])
				+ "</a></b><p>");

			// start of the table with the bug fields
			Response.Write ("\n<table class='table'>");
            Response.Write("\n<tr><td>Last changed by<td>"
				+ format_username((string)dr["last_updated_user"],(string)dr["last_updated_fullname"])
				+ "&nbsp;");
            Response.Write("\n<tr><td>Reported By<td>"
				+ format_username((string)dr["reporter"],(string)dr["reporter_fullname"])
				+ "&nbsp;");
            Response.Write("\n<tr><td>Reported On<td>" + Util.format_db_date_and_time(dr["reported_date"]) + "&nbsp;");

            if (security.user.tags_field_permission_level > 0)
	            Response.Write("\n<tr><td>Tags<td>" + dr["bg_tags"] + "&nbsp;");

            if (security.user.project_field_permission_level > 0)
	            Response.Write("\n<tr><td>Project<td>" + dr["current_project"] + "&nbsp;");

            if (security.user.org_field_permission_level > 0)
	            Response.Write("\n<tr><td>Organization<td>" + dr["og_name"] + "&nbsp;");

            if (security.user.category_field_permission_level > 0)
	            Response.Write("\n<tr><td>Category<td>" + dr["category_name"] + "&nbsp;");

            if (security.user.priority_field_permission_level > 0)
	            Response.Write("\n<tr><td>Priority<td>" + dr["priority_name"] + "&nbsp;");

            if (security.user.assigned_to_field_permission_level > 0)
	            Response.Write("\n<tr><td>Assigned<td>"
					+ format_username((string)dr["assigned_to_username"],(string)dr["assigned_to_fullname"])
					+ "&nbsp;");

            if (security.user.status_field_permission_level > 0)
            	Response.Write("\n<tr><td>Status<td>" + dr["status_name"] + "&nbsp;");

			if (security.user.udf_field_permission_level > 0)
				if (Util.get_setting("ShowUserDefinedBugAttribute","1") == "1")
				{
					Response.Write("\n<tr><td>"
						+ Util.get_setting("UserDefinedBugAttributeName","YOUR ATTRIBUTE")
						+ "<td>"
						+ dr["udf_name"] + "&nbsp;");
				}

			// Get custom column info  (There's an inefficiency here - we just did this
			// same call in get_bug_datarow...)

			
			DataSet ds_custom_cols = Util.get_custom_columns();


			// Show custom columns

			foreach (DataRow drcc in ds_custom_cols.Tables[0].Rows)
			{
                string column_name = (string) drcc["name"];

                if (security.user.dict_custom_field_permission_level[column_name] == Security.PERMISSION_NONE)
                {
                    continue;
                }

                Response.Write("\n<tr><td>");
				Response.Write (column_name);
				Response.Write ("<td>");

				if ((string)drcc["datatype"] == "datetime")
				{
					object dt = dr[(string)drcc["name"]];

					Response.Write (Util.format_db_date_and_time(dt));
				}
				else
				{
					string s = "";

					if ((string)drcc["dropdown type"] == "users")
					{
						object obj = dr[(string)drcc["name"]];
						if (obj.GetType() != typeof(System.DBNull))
						{
							int userid = Convert.ToInt32(obj);
							if (userid != 0)
							{
								string sql_get_username = "******";
								s = (string) DbUtil.execute_scalar(sql_get_username.Replace("$1", Convert.ToString(userid)));
							}
						}
					}
					else
					{
						s = Convert.ToString(dr[(string)drcc["name"]]);
					}

					s = HttpUtility.HtmlEncode(s);
					s = s.Replace("\n","<br>");
					s = s.Replace("  ","&nbsp; ");
					s = s.Replace("\t","&nbsp;&nbsp;&nbsp;&nbsp;");
					Response.Write (s);
				}
				Response.Write ("&nbsp;");
			}


			// create project custom dropdowns
			if ((int)dr["project"] != 0)
			{

				string sql = @"select
					isnull(pj_enable_custom_dropdown1,0) [pj_enable_custom_dropdown1],
					isnull(pj_enable_custom_dropdown2,0) [pj_enable_custom_dropdown2],
					isnull(pj_enable_custom_dropdown3,0) [pj_enable_custom_dropdown3],
					isnull(pj_custom_dropdown_label1,'') [pj_custom_dropdown_label1],
					isnull(pj_custom_dropdown_label2,'') [pj_custom_dropdown_label2],
					isnull(pj_custom_dropdown_label3,'') [pj_custom_dropdown_label3]
					from projects where pj_id = $pj";

				sql = sql.Replace("$pj", Convert.ToString((int)dr["project"]));

				DataRow project_dr = DbUtil.get_datarow(sql);


				if (project_dr != null)
				{
					for (int i = 1; i < 4; i++)
					{
						if ((int)project_dr["pj_enable_custom_dropdown" + Convert.ToString(i)] == 1)
						{
                            Response.Write("\n<tr><td>");
							Response.Write (project_dr["pj_custom_dropdown_label" + Convert.ToString(i)]);
							Response.Write ("<td>");
							Response.Write (dr["bg_project_custom_dropdown_value"  + Convert.ToString(i)]);
							Response.Write ("&nbsp;");
						}
					}
				}
			}



			Response.Write("\n</table><p>"); // end of the table with the bug fields

			// Relationships
			if (Util.get_setting("EnableRelationships", "0") == "1")
			{
				write_relationships(Response, bugid);
			}

			// Tasks
			if (Util.get_setting("EnableTasks", "0") == "1")
			{
				write_tasks(Response, bugid);
			}


            DataSet ds_posts = get_bug_posts(bugid, security.user.external_user, history_inline);
			write_posts (
                ds_posts,
                Response, 
                bugid, 
                0, 
                false, /* don't write links */
                images_inline, 
                history_inline, 
                internal_posts,
                security.user);

			Response.Write ("</body>");

		}
Esempio n. 9
0
        ///////////////////////////////////////////////////////////////////////
        public static DataRow get_user_datarow_maybe_using_from_addr(SharpMimeMessage mime_message, string from_addr, string username)
        {
            DataRow dr = null;

            string sql = @"
select us_id, us_admin, us_username, us_org, og_other_orgs_permission_level, isnull(us_forced_project,0) us_forced_project
from users
inner join orgs on us_org = og_id
where us_username = N'$us'";

            // Create a new user from the "from" email address
            string btnet_service_username = Util.get_setting("CreateUserFromEmailAddressIfThisUsername", "");

            if (!string.IsNullOrEmpty(from_addr) && username == btnet_service_username)
            {
                // We can do a better job of parsing the from_addr here than we did in btnet_service.exe
                if (mime_message != null)
                {
                    if (mime_message.Header.From != null && mime_message.Header.From != "")
                    {
                        from_addr = SharpMimeTools.parserfc2047Header(mime_message.Header.From);

                        // handle multiline from
                        from_addr = from_addr.Replace("\t", " ");
                    }
                }

                // See if there's already a username that matches this email address
                username = Email.simplify_email_address(from_addr);

                // Does a user with this email already exist?
                sql = sql.Replace("$us", username.Replace("'", "''"));

                // We maybe found [email protected], so let's use him as the user instead of the btnet_service.exe user
                dr = DbUtil.get_datarow(sql);

                // We didn't find the user, so let's create him, using the email address as the username.
                if (dr == null)
                {
                    bool use_domain_as_org_name = Util.get_setting("UseEmailDomainAsNewOrgNameWhenCreatingNewUser", "0") == "1";

                    User.copy_user(
                        username,
                        username,
                        "", "", "",                // first, last, signature
                        0,                         // salt
                        Guid.NewGuid().ToString(), // random value for password,
                        Util.get_setting("CreateUsersFromEmailTemplate", "[error - missing user template]"),
                        use_domain_as_org_name);

                    // now that we have created a user, try again
                    dr = DbUtil.get_datarow(sql);
                }
            }
            else
            {
                // Use the btnet_service.exe user as the username
                sql = sql.Replace("$us", username.Replace("'", "''"));
                dr  = DbUtil.get_datarow(sql);
            }

            return(dr);
        }