Пример #1
0
        ///////////////////////////////////////////////////////////////////////

        public static void add_attachment(string filename, SharpMimeMessage part, int bugid, int parent_postid, Security security)
        {
            Util.write_to_log("attachment:" + filename);

            string missing_attachment_msg = "";

            int max_upload_size = Convert.ToInt32(Util.get_setting("MaxUploadSize", "100000"));

            if (part.Size > max_upload_size)
            {
                missing_attachment_msg = "ERROR: email attachment exceeds size limit.";
            }

            string       content_type = part.Header.TopLevelMediaType + "/" + part.Header.SubType;
            string       desc;
            MemoryStream attachmentStream = new MemoryStream();

            if (missing_attachment_msg == "")
            {
                desc = "email attachment";
            }
            else
            {
                desc = missing_attachment_msg;
            }

            part.DumpBody(attachmentStream);
            attachmentStream.Position = 0;
            Bug.insert_post_attachment(
                security,
                bugid,
                attachmentStream,
                (int)attachmentStream.Length,
                filename,
                desc,
                content_type,
                parent_postid,
                false,  // not hidden
                false); // don't send notifications
        }
        ///////////////////////////////////////////////////////////////////////
        protected void Page_Load(Object sender, EventArgs e)
        {
            Util.do_not_cache(Response);

            Page.Header.Title = Util.get_setting("AppTitle", "BugTracker.NET") + " - "
                                + "add attachment";

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

            if (string_id == null || string_id == "0")
            {
                write_msg("Invalid id.", false);
                Response.End();
                return;
            }
            else
            {
                bugid = Convert.ToInt32(string_id);
                int permission_level = Bug.get_bug_permission_level(bugid, User.Identity);
                if (permission_level == PermissionLevel.None ||
                    permission_level == PermissionLevel.ReadOnly)
                {
                    write_msg("You are not allowed to edit this item", false);
                    Response.End();
                    return;
                }
            }


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

            if (IsPostBack)
            {
                on_update();
            }
        }
Пример #3
0
        ///////////////////////////////////////////////////////////////////////
        void on_update()
        {
            // does it say "Merge" or "Confirm Merge"?

            if (submit.Value == "Merge")
            {
                if (!validate())
                {
                    prev_from_bug.Value = "";
                    prev_into_bug.Value = "";
                    return;
                }
            }


            if (prev_from_bug.Value == from_bug.Value &&
                prev_into_bug.Value == into_bug.Value)
            {
                prev_from_bug.Value = btnet.Util.sanitize_integer(prev_from_bug.Value);
                prev_into_bug.Value = btnet.Util.sanitize_integer(prev_into_bug.Value);

                // rename the attachments

                string upload_folder = Util.get_upload_folder();
                if (upload_folder != null)
                {
                    sql = new SQLString(@"select bp_id, bp_file from bug_posts
			where bp_type = 'file' and bp_bug = @from"            );

                    sql = sql.AddParameterWithValue("from", prev_from_bug.Value);
                    DataSet ds = btnet.DbUtil.get_dataset(sql);

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        // create path
                        StringBuilder path = new StringBuilder(upload_folder);
                        path.Append("\\");
                        path.Append(prev_from_bug.Value);
                        path.Append("_");
                        path.Append(Convert.ToString(dr["bp_id"]));
                        path.Append("_");
                        path.Append(Convert.ToString(dr["bp_file"]));
                        if (System.IO.File.Exists(path.ToString()))
                        {
                            StringBuilder path2 = new StringBuilder(upload_folder);
                            path2.Append("\\");
                            path2.Append(prev_into_bug.Value);
                            path2.Append("_");
                            path2.Append(Convert.ToString(dr["bp_id"]));
                            path2.Append("_");
                            path2.Append(Convert.ToString(dr["bp_file"]));

                            System.IO.File.Move(path.ToString(), path2.ToString());
                        }
                    }
                }


                // copy the from db entries to the to
                sql = new SQLString(@"
insert into bug_subscriptions
(bs_bug, bs_user)
select @into, bs_user
from bug_subscriptions
where bs_bug = @from
and bs_user not in (select bs_user from bug_subscriptions where bs_bug = @into)

insert into bug_user
(bu_bug, bu_user, bu_flag, bu_flag_datetime, bu_seen, bu_seen_datetime, bu_vote, bu_vote_datetime)
select @into, bu_user, bu_flag, bu_flag_datetime, bu_seen, bu_seen_datetime, bu_vote, bu_vote_datetime
from bug_user
where bu_bug = @from
and bu_user not in (select bu_user from bug_user where bu_bug = @into)

update bug_posts     set bp_bug     = @into	where bp_bug = @from
update bug_tasks     set tsk_bug    = @into where tsk_bug = @from
update svn_revisions set svnrev_bug = @into where svnrev_bug = @from
update hg_revisions  set hgrev_bug  = @into where hgrev_bug = @from
update git_commits   set gitcom_bug = @into where gitcom_bug = @from
");

                sql = sql.AddParameterWithValue("from", prev_from_bug.Value);
                sql = sql.AddParameterWithValue("into", prev_into_bug.Value);

                btnet.DbUtil.execute_nonquery(sql);

                // record the merge itself

                sql = new SQLString(@"insert into bug_posts
			(bp_bug, bp_user, bp_date, bp_type, bp_comment, bp_comment_search)
			values(@into, @us,getdate(), 'comment', 'merged bug @from into this bug:', 'merged bug @from into this bug:')
			select scope_identity()"            );

                sql = sql.AddParameterWithValue("@from", prev_from_bug.Value);
                sql = sql.AddParameterWithValue("@into", prev_into_bug.Value);
                sql = sql.AddParameterWithValue("@us", Convert.ToString(User.Identity.GetUserId()));

                int comment_id = Convert.ToInt32(btnet.DbUtil.execute_scalar(sql));

                // update bug comments with info from old bug
                sql = new SQLString(@"update bug_posts
			set bp_comment = convert(nvarchar,bp_comment) + char(10) + bg_short_desc
			from bugs where bg_id = @from
			and bp_id = @bc"            );

                sql = sql.AddParameterWithValue("from", prev_from_bug.Value);
                sql = sql.AddParameterWithValue("bc", Convert.ToString(comment_id));
                btnet.DbUtil.execute_nonquery(sql);


                // delete the from bug
                int from_bugid = Convert.ToInt32(prev_from_bug.Value);
                Bug.delete_bug(from_bugid);

                btnet.Bug.send_notifications(btnet.Bug.UPDATE, Convert.ToInt32(prev_into_bug.Value), User.Identity);

                Response.Redirect("edit_bug.aspx?id=" + prev_into_bug.Value);
            }
            else
            {
                prev_from_bug.Value               = from_bug.Value;
                prev_into_bug.Value               = into_bug.Value;
                static_from_bug.InnerText         = from_bug.Value;
                static_into_bug.InnerText         = into_bug.Value;
                static_from_desc.InnerText        = (string)dr[0];
                static_into_desc.InnerText        = (string)dr[1];
                from_bug.Style["display"]         = "none";
                into_bug.Style["display"]         = "none";
                static_from_bug.Style["display"]  = "";
                static_into_bug.Style["display"]  = "";
                static_from_desc.Style["display"] = "";
                static_into_desc.Style["display"] = "";
                submit.Value = "Confirm Merge";
            }
        }
Пример #4
0
        ///////////////////////////////////////////////////////////////////////
        public static NewIds insert_bug(
            string short_desc,
            Security security,
            string tags,
            int projectid,
            int orgid,
            int categoryid,
            int priorityid,
            int statusid,
            int assigned_to_userid,
            int udfid,
            string project_custom_dropdown_value1,
            string project_custom_dropdown_value2,
            string project_custom_dropdown_value3,
            string comment_formated,
            string comment_search,
            string from,
            string cc,
            string content_type,
            bool internal_only,
            SortedDictionary <string, string> hash_custom_cols,
            bool send_notifications)
        {
            if (short_desc.Trim() == "")
            {
                short_desc = "[No Description]";
            }

            if (assigned_to_userid == 0)
            {
                assigned_to_userid = Util.get_default_user(projectid);
            }

            string sql = @"insert into bugs
					(bg_short_desc,
					bg_tags,
					bg_reported_user,
					bg_last_updated_user,
					bg_reported_date,
					bg_last_updated_date,
					bg_project,
					bg_org,
					bg_category,
					bg_priority,
					bg_status,
					bg_assigned_to_user,
					bg_user_defined_attribute,
					bg_project_custom_dropdown_value1,
					bg_project_custom_dropdown_value2,
					bg_project_custom_dropdown_value3
					$custom_cols_placeholder1)
					values (N'$short_desc', N'$tags', $reported_user,  $reported_user, getdate(), getdate(),
					$project, $org,
					$category, $priority, $status, $assigned_user, $udf,
					N'$pcd1',N'$pcd2',N'$pcd3' $custom_cols_placeholder2)"                    ;

            sql = sql.Replace("$short_desc", short_desc.Replace("'", "''"));
            sql = sql.Replace("$tags", tags.Replace("'", "''"));
            sql = sql.Replace("$reported_user", Convert.ToString(security.user.usid));
            sql = sql.Replace("$project", Convert.ToString(projectid));
            sql = sql.Replace("$org", Convert.ToString(orgid));
            sql = sql.Replace("$category", Convert.ToString(categoryid));
            sql = sql.Replace("$priority", Convert.ToString(priorityid));
            sql = sql.Replace("$status", Convert.ToString(statusid));
            sql = sql.Replace("$assigned_user", Convert.ToString(assigned_to_userid));
            sql = sql.Replace("$udf", Convert.ToString(udfid));
            sql = sql.Replace("$pcd1", project_custom_dropdown_value1);
            sql = sql.Replace("$pcd2", project_custom_dropdown_value2);
            sql = sql.Replace("$pcd3", project_custom_dropdown_value3);

            if (hash_custom_cols == null)
            {
                sql = sql.Replace("$custom_cols_placeholder1", "");
                sql = sql.Replace("$custom_cols_placeholder2", "");
            }
            else
            {
                string custom_cols_sql1 = "";
                string custom_cols_sql2 = "";

                DataSet ds_custom_cols = Util.get_custom_columns();

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

                    // skip if no permission to update
                    if (security.user.dict_custom_field_permission_level[column_name] != Security.PERMISSION_ALL)
                    {
                        continue;
                    }

                    custom_cols_sql1 += ",[" + column_name + "]";

                    string datatype = (string)drcc["datatype"];

                    string custom_col_val = Util.request_to_string_for_sql(
                        hash_custom_cols[column_name],
                        datatype);

                    custom_cols_sql2 += "," + custom_col_val;
                }
                sql = sql.Replace("$custom_cols_placeholder1", custom_cols_sql1);
                sql = sql.Replace("$custom_cols_placeholder2", custom_cols_sql2);
            }



            sql += "\nselect scope_identity()";


            int bugid  = Convert.ToInt32(DbUtil.execute_scalar(sql));
            int postid = Bug.insert_comment(
                bugid,
                security.user.usid,
                comment_formated,
                comment_search,
                from,
                cc,
                content_type,
                internal_only);

            Bug.auto_subscribe(bugid);

            if (send_notifications)
            {
                Bug.send_notifications(Bug.INSERT, bugid, security);
            }

            return(new NewIds(bugid, postid));
        }
Пример #5
0
        ///////////////////////////////////////////////////////////////////////
        private static int insert_post_attachment_impl(
            Security security,
            int bugid,
            Stream content,
            int content_length,
            int copy_bpid,
            string file,
            string comment,
            string content_type,
            int parent,
            bool hidden_from_external_users,
            bool send_notifications)
        {
            // Note that this method does not perform any security check nor does
            // it check that content_length is less than MaxUploadSize.
            // These are left up to the caller.


            string upload_folder = Util.get_upload_folder();
            string sql;
            bool   store_attachments_in_database = (Util.get_setting("StoreAttachmentsInDatabase", "0") == "1");
            string effective_file           = file;
            int    effective_content_length = content_length;
            string effective_content_type   = content_type;
            Stream effective_content        = null;

            try
            {
                // Determine the content. We may be instructed to copy an existing
                // attachment via copy_bpid, or a Stream may be provided as the content parameter.

                if (copy_bpid != -1)
                {
                    BugPostAttachment bpa = get_bug_post_attachment(copy_bpid);

                    effective_content        = bpa.content;
                    effective_file           = bpa.file;
                    effective_content_length = bpa.content_length;
                    effective_content_type   = bpa.content_type;
                }
                else
                {
                    effective_content        = content;
                    effective_file           = file;
                    effective_content_length = content_length;
                    effective_content_type   = content_type;
                }

                // Insert a new post into bug_posts.

                sql = @"
declare @now datetime

set @now = getdate()

update bugs
	set bg_last_updated_date = @now,
	bg_last_updated_user = $us
	where bg_id = $bg

insert into bug_posts
	(bp_type, bp_bug, bp_file, bp_comment, bp_size, bp_date, bp_user, bp_content_type, bp_parent, bp_hidden_from_external_users)
	values ('file', $bg, N'$fi', N'$de', $si, @now, $us, N'$ct', $pa, $internal)
	select scope_identity()"    ;

                sql = sql.Replace("$bg", Convert.ToString(bugid));
                sql = sql.Replace("$fi", effective_file.Replace("'", "''"));
                sql = sql.Replace("$de", comment.Replace("'", "''"));
                sql = sql.Replace("$si", Convert.ToString(effective_content_length));
                sql = sql.Replace("$us", Convert.ToString(security.user.usid));

                // Sometimes, somehow, content type is null.  Not sure how.
                sql = sql.Replace("$ct",
                                  effective_content_type != null
                                                ? effective_content_type.Replace("'", "''")
                                                : string.Empty);

                if (parent == -1)
                {
                    sql = sql.Replace("$pa", "null");
                }
                else
                {
                    sql = sql.Replace("$pa", Convert.ToString(parent));
                }
                sql = sql.Replace("$internal", Util.bool_to_string(hidden_from_external_users));

                int bp_id = Convert.ToInt32(DbUtil.execute_scalar(sql));

                try
                {
                    // Store attachment in bug_post_attachments table.

                    if (store_attachments_in_database)
                    {
                        byte[] data       = new byte[effective_content_length];
                        int    bytes_read = 0;

                        while (bytes_read < effective_content_length)
                        {
                            int bytes_read_this_iteration = effective_content.Read(data, bytes_read, effective_content_length - bytes_read);
                            if (bytes_read_this_iteration == 0)
                            {
                                throw new Exception("Unexpectedly reached the end of the stream before all data was read.");
                            }
                            bytes_read += bytes_read_this_iteration;
                        }

                        sql = @"insert into bug_post_attachments
								(bpa_post, bpa_content)
								values (@bp, @bc)"                                ;
                        using (SqlCommand cmd = new SqlCommand(sql))
                        {
                            cmd.Parameters.AddWithValue("@bp", bp_id);
                            cmd.Parameters.Add("@bc", SqlDbType.Image).Value = data;
                            cmd.CommandTimeout = Convert.ToInt32(Util.get_setting("SqlCommand.CommandTimeout", "30"));
                            DbUtil.execute_nonquery(cmd);
                        }
                    }
                    else
                    {
                        // Store attachment in UploadFolder.

                        if (upload_folder == null)
                        {
                            throw new Exception("StoreAttachmentsInDatabase is false and UploadFolder is not set in web.config.");
                        }

                        // Copy the content Stream to a file in the upload_folder.
                        byte[] buffer     = new byte[16384];
                        int    bytes_read = 0;
                        using (FileStream fs = new FileStream(upload_folder + "\\" + bugid + "_" + bp_id + "_" + effective_file, FileMode.CreateNew, FileAccess.Write))
                        {
                            while (bytes_read < effective_content_length)
                            {
                                int bytes_read_this_iteration = effective_content.Read(buffer, 0, buffer.Length);
                                if (bytes_read_this_iteration == 0)
                                {
                                    throw new Exception("Unexpectedly reached the end of the stream before all data was read.");
                                }
                                fs.Write(buffer, 0, bytes_read_this_iteration);
                                bytes_read += bytes_read_this_iteration;
                            }
                        }
                    }
                }
                catch
                {
                    // clean up
                    sql = @"delete from bug_posts where bp_id = $bp";

                    sql = sql.Replace("$bp", Convert.ToString(bp_id));

                    DbUtil.execute_nonquery(sql);

                    throw;
                }

                if (send_notifications)
                {
                    Bug.send_notifications(Bug.UPDATE, bugid, security);
                }
                return(bp_id);
            }
            finally
            {
                // If this procedure "owns" the content (instead of our caller owning it), dispose it.
                if (effective_content != null && effective_content != content)
                {
                    effective_content.Dispose();
                }
            }
        }
Пример #6
0
        ///////////////////////////////////////////////////////////////////////
        // This used to send the emails, but not now.  Now it just queues
        // the emails to be sent, then spawns a thread to send them.
        public static void send_notifications(int insert_or_update,          // The implementation
                                              int bugid,
                                              Security security,
                                              int just_to_this_userid,
                                              bool status_changed,
                                              bool assigned_to_changed,
                                              int prev_assigned_to_user)
        {
            // If there's something worth emailing about, then there's
            // probably something worth updating the index about.
            // Really, though, we wouldn't want to update the index if it were
            // just the status that were changing...
            if (Util.get_setting("EnableLucene", "1") == "1")
            {
                MyLucene.update_lucene_index(bugid);
            }

            bool notification_email_enabled = (Util.get_setting("NotificationEmailEnabled", "1") == "1");

            if (!notification_email_enabled)
            {
                return;
            }
            // MAW -- 2006/01/27 -- Determine level of change detected
            int changeLevel = 0;

            if (insert_or_update == INSERT)
            {
                changeLevel = 1;
            }
            else if (status_changed)
            {
                changeLevel = 2;
            }
            else if (assigned_to_changed)
            {
                changeLevel = 3;
            }
            else
            {
                changeLevel = 4;
            }

            string sql;

            if (just_to_this_userid > 0)
            {
                sql = @"
/* get notification email for just one user  */
select us_email, us_id, us_admin, og.*
from bug_subscriptions
inner join users on bs_user = us_id
inner join orgs og on us_org = og_id
inner join bugs on bg_id = bs_bug
left outer join project_user_xref on pu_user = us_id and pu_project = bg_project
where us_email is not null
and us_enable_notifications = 1
-- $status_change
and us_active = 1
and us_email <> ''
and
case
when
	us_org <> bg_org
	and og_other_orgs_permission_level < 2
	and og_other_orgs_permission_level < isnull(pu_permission_level,$dpl)
		then og_other_orgs_permission_level
else
	isnull(pu_permission_level,$dpl)
end <> 0
and bs_bug = $id
and us_id = $just_this_usid";

                sql = sql.Replace("$just_this_usid", Convert.ToString(just_to_this_userid));
            }
            else
            {
                // MAW -- 2006/01/27 -- Added different notifications if reported or assigned-to
                sql = @"
/* get notification emails for all subscribers */
select us_email, us_id, us_admin, og.*
from bug_subscriptions
inner join users on bs_user = us_id
inner join orgs og on us_org = og_id
inner join bugs on bg_id = bs_bug
left outer join project_user_xref on pu_user = us_id and pu_project = bg_project
where us_email is not null
and us_enable_notifications = 1
-- $status_change
and us_active = 1
and us_email <> ''
and (   ($cl <= us_reported_notifications and bg_reported_user = bs_user)
or ($cl <= us_assigned_notifications and bg_assigned_to_user = bs_user)
or ($cl <= us_assigned_notifications and $pau = bs_user)
or ($cl <= us_subscribed_notifications))
and
case
when
us_org <> bg_org
and og_other_orgs_permission_level < 2
and og_other_orgs_permission_level < isnull(pu_permission_level,$dpl)
	then og_other_orgs_permission_level
else
isnull(pu_permission_level,$dpl)
end <> 0
and bs_bug = $id
and (us_id <> $us or isnull(us_send_notifications_to_self,0) = 1)";
            }

            sql = sql.Replace("$cl", changeLevel.ToString());
            sql = sql.Replace("$pau", prev_assigned_to_user.ToString());
            sql = sql.Replace("$id", Convert.ToString(bugid));
            sql = sql.Replace("$dpl", Util.get_setting("DefaultPermissionLevel", "2"));
            sql = sql.Replace("$us", Convert.ToString(security.user.usid));


            DataSet ds_subscribers = DbUtil.get_dataset(sql);

            if (ds_subscribers.Tables[0].Rows.Count > 0)
            {
                bool added_to_queue = false;


                // Get bug html
                DataRow bug_dr = Bug.get_bug_datarow(bugid, security);

                string from = Util.get_setting("NotificationEmailFrom", "");

                // Format the subject line
                string subject = Util.get_setting("NotificationSubjectFormat", "$THING$:$BUGID$ was $ACTION$ - $SHORTDESC$ $TRACKINGID$");

                subject = subject.Replace("$THING$", Util.capitalize_first_letter(Util.get_setting("SingularBugLabel", "bug")));

                string action = "";
                if (insert_or_update == INSERT)
                {
                    action = "added";
                }
                else
                {
                    action = "updated";
                }

                subject = subject.Replace("$ACTION$", action);
                subject = subject.Replace("$BUGID$", Convert.ToString(bugid));
                subject = subject.Replace("$SHORTDESC$", (string)bug_dr["short_desc"]);

                string tracking_id = " (";
                tracking_id += Util.get_setting("TrackingIdString", "DO NOT EDIT THIS:");
                tracking_id += Convert.ToString(bugid);
                tracking_id += ")";
                subject      = subject.Replace("$TRACKINGID$", tracking_id);

                subject = subject.Replace("$PROJECT$", (string)bug_dr["current_project"]);
                subject = subject.Replace("$ORGANIZATION$", (string)bug_dr["og_name"]);
                subject = subject.Replace("$CATEGORY$", (string)bug_dr["category_name"]);
                subject = subject.Replace("$PRIORITY$", (string)bug_dr["priority_name"]);
                subject = subject.Replace("$STATUS$", (string)bug_dr["status_name"]);
                subject = subject.Replace("$ASSIGNED_TO$", (string)bug_dr["assigned_to_username"]);


                // send a separate email to each subscriber
                foreach (DataRow dr in ds_subscribers.Tables[0].Rows)
                {
                    string to = (string)dr["us_email"];

                    // Create a fake response and let the code
                    // write the html to that response
                    System.IO.StringWriter writer      = new System.IO.StringWriter();
                    HttpResponse           my_response = new HttpResponse(writer);
                    my_response.Write("<html>");
                    my_response.Write("<base href=\"" +
                                      Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/") + "\"/>");

                    // create a security rec for the user receiving the email
                    Security sec2 = new Security();

                    // fill in what we know is needed downstream
                    sec2.user.is_admin      = Convert.ToBoolean(dr["us_admin"]);
                    sec2.user.external_user = Convert.ToBoolean(dr["og_external_user"]);
                    sec2.user.tags_field_permission_level        = (int)dr["og_tags_field_permission_level"];
                    sec2.user.category_field_permission_level    = (int)dr["og_category_field_permission_level"];
                    sec2.user.priority_field_permission_level    = (int)dr["og_priority_field_permission_level"];
                    sec2.user.assigned_to_field_permission_level = (int)dr["og_assigned_to_field_permission_level"];
                    sec2.user.status_field_permission_level      = (int)dr["og_status_field_permission_level"];
                    sec2.user.project_field_permission_level     = (int)dr["og_project_field_permission_level"];
                    sec2.user.org_field_permission_level         = (int)dr["og_org_field_permission_level"];
                    sec2.user.udf_field_permission_level         = (int)dr["og_udf_field_permission_level"];

                    DataSet ds_custom = Util.get_custom_columns();
                    foreach (DataRow dr_custom in ds_custom.Tables[0].Rows)
                    {
                        string bg_name = (string)dr_custom["name"];
                        string og_name = "og_"
                                         + (string)dr_custom["name"]
                                         + "_field_permission_level";

                        object obj = dr[og_name];
                        if (Convert.IsDBNull(obj))
                        {
                            sec2.user.dict_custom_field_permission_level[bg_name] = Security.PERMISSION_ALL;
                        }
                        else
                        {
                            sec2.user.dict_custom_field_permission_level[bg_name] = (int)dr[og_name];
                        }
                    }

                    PrintBug.print_bug(
                        my_response,
                        bug_dr,
                        sec2,
                        true,  // include style
                        false, // images_inline
                        true,  // history_inline
                        true); // internal_posts

                    // at this point "writer" has the bug html

                    sql = @"
delete from queued_notifications where qn_bug = $bug and qn_to = N'$to'

insert into queued_notifications
(qn_date_created, qn_bug, qn_user, qn_status, qn_retries, qn_to, qn_from, qn_subject, qn_body, qn_last_exception)
values (getdate(), $bug, $user, N'not sent', 0, N'$to', N'$from', N'$subject', N'$body', N'')";

                    sql = sql.Replace("$bug", Convert.ToString(bugid));
                    sql = sql.Replace("$user", Convert.ToString(dr["us_id"]));
                    sql = sql.Replace("$to", to.Replace("'", "''"));
                    sql = sql.Replace("$from", from.Replace("'", "''"));
                    sql = sql.Replace("$subject", subject.Replace("'", "''"));
                    sql = sql.Replace("$body", writer.ToString().Replace("'", "''"));

                    DbUtil.execute_nonquery_without_logging(sql);

                    added_to_queue = true;
                }                 // end loop through ds_subscribers

                if (added_to_queue)
                {
                    // spawn a worker thread to send the emails
                    System.Threading.Thread thread = new System.Threading.Thread(threadproc_notifications);
                    thread.Start();
                }
            }              // if there are any subscribers
        }
Пример #7
0
        ///////////////////////////////////////////////////////////////////////
        void on_update()
        {
            Boolean good = validate();

            if (good)
            {
                if (tsk_id == 0)  // insert new
                {
                    sql = new SQLString(@"
insert into bug_tasks (
tsk_bug,
tsk_created_user,
tsk_created_date,
tsk_last_updated_user,
tsk_last_updated_date,
tsk_assigned_to_user,
tsk_planned_start_date,
tsk_actual_start_date,
tsk_planned_end_date,
tsk_actual_end_date,
tsk_planned_duration,
tsk_actual_duration,
tsk_duration_units,
tsk_percent_complete,
tsk_status,
tsk_sort_sequence,
tsk_description
)
values (
@tsk_bug,
@tsk_created_user,
getdate(),
@tsk_last_updated_user,
getdate(),
@tsk_assigned_to_user,
@tsk_planned_start_date,
@tsk_actual_start_date,
@tsk_planned_end_date,
@tsk_actual_end_date,
@tsk_planned_duration,
@tsk_actual_duration,
@tsk_duration_units,
@tsk_percent_complete,
@tsk_status,
@tsk_sort_sequence,
@tsk_description
);

declare @tsk_id int
select @tsk_id = scope_identity()

insert into bug_posts
(bp_bug, bp_user, bp_date, bp_comment, bp_type)
values(@tsk_bug, @tsk_last_updated_user, getdate(), N'added task ' + convert(varchar, @tsk_id), 'update')");


                    sql = sql.AddParameterWithValue("tsk_created_user", Convert.ToString(User.Identity.GetUserId()));
                }
                else // edit existing
                {
                    sql = new SQLString(@"
update bug_tasks set
tsk_last_updated_user = @tsk_last_updated_user,
tsk_last_updated_date = getdate(),
tsk_assigned_to_user = @tsk_assigned_to_user,
tsk_planned_start_date = '@tsk_planned_start_date',
tsk_actual_start_date = '@tsk_actual_start_date',
tsk_planned_end_date = '@tsk_planned_end_date',
tsk_actual_end_date = '@tsk_actual_end_date',
tsk_planned_duration = @tsk_planned_duration,
tsk_actual_duration = @tsk_actual_duration,
tsk_duration_units = @tsk_duration_units,
tsk_percent_complete = @tsk_percent_complete,
tsk_status = @tsk_status,
tsk_sort_sequence = @tsk_sort_sequence,
tsk_description = @tsk_description
where tsk_id = @tsk_id;
                
insert into bug_posts
(bp_bug, bp_user, bp_date, bp_comment, bp_type)
values(@tsk_bug, @tsk_last_updated_user, getdate(), N'updated task ' + @tsk_id, 'update')");

                    sql = sql.AddParameterWithValue("tsk_id", Convert.ToString(tsk_id));
                }

                sql = sql.AddParameterWithValue("tsk_bug", Convert.ToString(bugid));
                sql = sql.AddParameterWithValue("tsk_last_updated_user", Convert.ToString(User.Identity.GetUserId()));

                sql = sql.AddParameterWithValue("tsk_planned_start_date", format_date_hour_min(
                                                    planned_start_date.Value,
                                                    planned_start_hour.SelectedItem.Value,
                                                    planned_start_min.SelectedItem.Value));

                sql = sql.AddParameterWithValue("tsk_actual_start_date", format_date_hour_min(
                                                    actual_start_date.Value,
                                                    actual_start_hour.SelectedItem.Value,
                                                    actual_start_min.SelectedItem.Value));

                sql = sql.AddParameterWithValue("tsk_planned_end_date", format_date_hour_min(
                                                    planned_end_date.Value,
                                                    planned_end_hour.SelectedItem.Value,
                                                    planned_end_min.SelectedItem.Value));

                sql = sql.AddParameterWithValue("tsk_actual_end_date", format_date_hour_min(
                                                    actual_end_date.Value,
                                                    actual_end_hour.SelectedItem.Value,
                                                    actual_end_min.SelectedItem.Value));

                sql = sql.AddParameterWithValue("tsk_planned_duration", format_decimal_for_db(planned_duration.Value));
                sql = sql.AddParameterWithValue("tsk_actual_duration", format_decimal_for_db(actual_duration.Value));
                sql = sql.AddParameterWithValue("tsk_percent_complete", format_number_for_db(percent_complete.Value));
                sql = sql.AddParameterWithValue("tsk_status", status.SelectedItem.Value);
                sql = sql.AddParameterWithValue("tsk_sort_sequence", format_number_for_db(sort_sequence.Value));
                sql = sql.AddParameterWithValue("tsk_assigned_to_user", assigned_to.SelectedItem.Value);
                sql = sql.AddParameterWithValue("tsk_description", desc.Value);
                sql = sql.AddParameterWithValue("tsk_duration_units", duration_units.SelectedItem.Value);

                DbUtil.execute_nonquery(sql);

                Bug.send_notifications(Bug.UPDATE, bugid, User.Identity);


                Response.Redirect("tasks.aspx?bugid=" + Convert.ToString(bugid));
            }
            else
            {
                if (tsk_id == 0)  // insert new
                {
                    msg.InnerText = "Task was not created.";
                }
                else // edit existing
                {
                    msg.InnerText = "Task was not updated.";
                }
            }
        }
Пример #8
0
        ///////////////////////////////////////////////////////////////////////
        protected void Page_Load(Object sender, EventArgs e)
        {
            Util.do_not_cache(Response);

            msg.InnerText = "";

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

            bugid = Convert.ToInt32(string_bugid);

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

            if (permission_level != PermissionLevel.All)
            {
                Response.Write("You are not allowed to edit tasks for this item");
                Response.End();
            }

            if (User.IsInRole(BtnetRoles.Admin) || User.Identity.GetCanEditTasks())
            {
                // allowed
            }
            else
            {
                Response.Write("You are not allowed to edit tasks");
                Response.End();
            }


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

            tsk_id_static.InnerHtml = string_tsk_id;
            tsk_id = Convert.ToInt32(string_tsk_id);

            if (!IsPostBack)
            {
                Master.Menu.SelectedItem = "admin";
                Page.Title = Util.get_setting("AppTitle", "BugTracker.NET") + " - "
                             + "edit task";

                bugid_label.InnerHtml  = Util.capitalize_first_letter(Util.get_setting("SingularBugLabel", "bug")) + " ID:";
                bugid_static.InnerHtml = Convert.ToString(bugid);

                load_users_dropdowns(bugid);

                if (Util.get_setting("ShowTaskAssignedTo", "1") == "0")
                {
                    assigned_to_tr.Visible = false;
                }

                if (Util.get_setting("ShowTaskPlannedStartDate", "1") == "0")
                {
                    planned_start_date_tr.Visible = false;
                }
                if (Util.get_setting("ShowTaskActualStartDate", "1") == "0")
                {
                    actual_start_date_tr.Visible = false;
                }

                if (Util.get_setting("ShowTaskPlannedEndDate", "1") == "0")
                {
                    planned_end_date_tr.Visible = false;
                }
                if (Util.get_setting("ShowTaskActualEndDate", "1") == "0")
                {
                    actual_end_date_tr.Visible = false;
                }

                if (Util.get_setting("ShowTaskPlannedDuration", "1") == "0")
                {
                    planned_duration_tr.Visible = false;
                }
                if (Util.get_setting("ShowTaskActualDuration", "1") == "0")
                {
                    actual_duration_tr.Visible = false;
                }


                if (Util.get_setting("ShowTaskDurationUnits", "1") == "0")
                {
                    duration_units_tr.Visible = false;
                }

                if (Util.get_setting("ShowTaskPercentComplete", "1") == "0")
                {
                    percent_complete_tr.Visible = false;
                }

                if (Util.get_setting("ShowTaskStatus", "1") == "0")
                {
                    status_tr.Visible = false;
                }

                if (Util.get_setting("ShowTaskSortSequence", "1") == "0")
                {
                    sort_sequence_tr.Visible = false;
                }


                // add or edit?
                if (tsk_id == 0)
                {
                    tsk_id_tr.Visible = false;
                    sub.Value         = "Create";

                    string default_duration_units = Util.get_setting("TaskDefaultDurationUnits", "hours");
                    duration_units.Items.FindByText(default_duration_units).Selected = true;

                    string default_hour = Util.get_setting("TaskDefaultHour", "09");
                    planned_start_hour.Items.FindByText(default_hour).Selected = true;
                    actual_start_hour.Items.FindByText(default_hour).Selected  = true;
                    planned_end_hour.Items.FindByText(default_hour).Selected   = true;
                    actual_end_hour.Items.FindByText(default_hour).Selected    = true;

                    string default_status = Util.get_setting("TaskDefaultStatus", "[no status]");
                    status.Items.FindByText(default_status).Selected = true;
                }
                else
                {
                    // Get this entry's data from the db and fill in the form

                    sql = new SQLString(@"select * from bug_tasks where tsk_id = @tsk_id and tsk_bug = @bugid");
                    sql = sql.AddParameterWithValue("tsk_id", Convert.ToString(tsk_id));
                    sql = sql.AddParameterWithValue("bugid", Convert.ToString(bugid));
                    DataRow dr = DbUtil.get_datarow(sql);

                    assigned_to.Items.FindByValue(Convert.ToString(dr["tsk_assigned_to_user"])).Selected = true;

                    duration_units.Items.FindByText(Convert.ToString(dr["tsk_duration_units"])).Selected = true;

                    status.Items.FindByValue(Convert.ToString(dr["tsk_status"])).Selected = true;

                    planned_duration.Value = Util.format_db_value(dr["tsk_planned_duration"]);
                    actual_duration.Value  = Util.format_db_value(dr["tsk_actual_duration"]);
                    percent_complete.Value = Convert.ToString(dr["tsk_percent_complete"]);
                    sort_sequence.Value    = Convert.ToString(dr["tsk_sort_sequence"]);
                    desc.Value             = Convert.ToString(dr["tsk_description"]);

                    load_date_hour_min(
                        planned_start_date,
                        planned_start_hour,
                        planned_start_min,
                        dr["tsk_planned_start_date"]);

                    load_date_hour_min(
                        actual_start_date,
                        actual_start_hour,
                        actual_start_min,
                        dr["tsk_actual_start_date"]);

                    load_date_hour_min(
                        planned_end_date,
                        planned_end_hour,
                        planned_end_min,
                        dr["tsk_planned_end_date"]);

                    load_date_hour_min(
                        actual_end_date,
                        actual_end_hour,
                        actual_end_min,
                        dr["tsk_actual_end_date"]);

                    sub.Value = "Update";
                }
            }
            else
            {
                on_update();
            }
        }
        ///////////////////////////////////////////////////////////////////////
        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();
            }

            if (IsPostBack)
            {
                // do delete here

                sql = new SQLString(@"delete bug_posts where bp_id = @bpid");
                sql = sql.AddParameterWithValue("bpid", Util.sanitize_integer(row_id.Value));
                DbUtil.execute_nonquery(sql);
                Response.Redirect("edit_bug.aspx?id=" + Util.sanitize_integer(redirect_bugid.Value));
            }
            else
            {
                string bug_id = Util.sanitize_integer(Request["bug_id"]);
                redirect_bugid.Value = bug_id;

                int permission_level = Bug.get_bug_permission_level(Convert.ToInt32(bug_id), User.Identity);
                if (permission_level != PermissionLevel.All)
                {
                    Response.Write("You are not allowed to edit this item");
                    Response.End();
                }

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

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

                back_href.HRef = "edit_bug.aspx?id=" + bug_id;

                sql = new SQLString(@"select bp_comment from bug_posts where bp_id = @bpid");
                sql = sql.AddParameterWithValue("bpid", id);

                DataRow dr = DbUtil.get_datarow(sql);

                // show the first few chars of the comment
                string s   = Convert.ToString(dr["bp_comment"]);
                int    len = 20;
                if (s.Length < len)
                {
                    len = s.Length;
                }

                confirm_href.InnerText = "confirm delete of comment: "
                                         + s.Substring(0, len)
                                         + "...";

                row_id.Value = id;
            }
        }
Пример #10
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);
        }
Пример #11
0
		///////////////////////////////////////////////////////////////////////
		public static string send_email(
			string to,
			string from,
			string cc,
			string subject,
			string body,
			System.Web.Mail.MailFormat body_format,
			System.Web.Mail.MailPriority priority,
			int[] attachment_bpids,
			bool return_receipt)
		{
            Dictionary<string,int> files_to_delete = new Dictionary<string,int>();
			ArrayList directories_to_delete = new ArrayList();
			System.Web.Mail.MailMessage msg = new System.Web.Mail.MailMessage();
			msg.To = to;
			msg.From = from;

            if (!string.IsNullOrEmpty(cc.Trim())) 
            {
                msg.Cc = cc; 
            }
			
            msg.Subject = subject;
			msg.Priority = priority;

			// This fixes a bug for a couple people, but make it configurable, just in case.
			if (Util.get_setting("BodyEncodingUTF8", "1") == "1")
			{
				msg.BodyEncoding = Encoding.UTF8;
			}


			if (return_receipt)
			{
                msg.Headers.Add("Disposition-Notification-To", from);
			}

			// workaround for a bug I don't understand...
			if (Util.get_setting("SmtpForceReplaceOfBareLineFeeds", "0") == "1")
			{
				body = body.Replace("\n", "\r\n");
			}

            msg.Body = body;
			msg.BodyFormat = body_format;


			string smtp_server = Util.get_setting("SmtpServer", "");
			if (smtp_server != "")
			{
				System.Web.Mail.SmtpMail.SmtpServer = smtp_server;
			}

			string smtp_password = Util.get_setting("SmtpServerAuthenticatePassword", "");

			if (smtp_password != "")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = smtp_password;
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] =
					Util.get_setting("SmtpServerAuthenticateUser", "");
			}

			string smtp_pickup = Util.get_setting("SmtpServerPickupDirectory", "");
			if (smtp_pickup != "")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverpickupdirectory"] = smtp_pickup;
			}


			string send_using = Util.get_setting("SmtpSendUsing", "");
			if (send_using != "")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = send_using;
			}


			string smtp_use_ssl = Util.get_setting("SmtpUseSSL", "");
			if (smtp_use_ssl == "1")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";
			}

			string smtp_server_port = Util.get_setting("SmtpServerPort", "");
			if (smtp_server_port != "")
			{
				msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = smtp_server_port;
			}

			if (attachment_bpids != null && attachment_bpids.Length > 0)
			{

				string upload_folder = btnet.Util.get_upload_folder();

				if (string.IsNullOrEmpty(upload_folder))
				{
					upload_folder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
					Directory.CreateDirectory(upload_folder);
					directories_to_delete.Add(upload_folder);
				}


				foreach (int attachment_bpid in attachment_bpids)
				{
					byte[] buffer = new byte[16 * 1024];
					string dest_path_and_filename;
					Bug.BugPostAttachment bpa = Bug.get_bug_post_attachment(attachment_bpid);
					using (bpa.content)
					{
						dest_path_and_filename = Path.Combine(upload_folder, bpa.file);

                        // logic to rename in case of dupes.  MS Outlook embeds images all with the same filename
                        int suffix = 0;
                        string renamed_to_prevent_dupe = dest_path_and_filename;
                        while (files_to_delete.ContainsKey(renamed_to_prevent_dupe))
                        {
                            suffix++;
                            renamed_to_prevent_dupe = dest_path_and_filename + Convert.ToString(suffix);
                        }
                        dest_path_and_filename = renamed_to_prevent_dupe;

                        // Save to disk
						using (FileStream out_stream = new FileStream(
							dest_path_and_filename,
							FileMode.CreateNew,
							FileAccess.Write,
							FileShare.None))
						{
                            int bytes_read = bpa.content.Read(buffer, 0, buffer.Length);
							while (bytes_read != 0)
							{
								out_stream.Write(buffer, 0, bytes_read);

								bytes_read = bpa.content.Read(buffer, 0, buffer.Length);
							}
						}

					}

                    // Add saved file as attachment
					System.Web.Mail.MailAttachment mail_attachment = new System.Web.Mail.MailAttachment(
						dest_path_and_filename,
						System.Web.Mail.MailEncoding.Base64);
					msg.Attachments.Add(mail_attachment);
                    files_to_delete[dest_path_and_filename] = 1;
				}
			}


			try
			{
                // This fixes a bug for some people.  Not sure how it happens....
                msg.Body = msg.Body.Replace(Convert.ToChar(0), ' ').Trim();
                System.Web.Mail.SmtpMail.Send(msg);

				// We delete late here because testing showed that SmtpMail class
				// got confused when we deleted too soon.
				foreach (string file in files_to_delete.Keys)
				{
					File.Delete(file);
				}

				foreach (string directory in directories_to_delete)
				{
					Directory.Delete(directory);
				}

				return "";
			}
			catch (Exception e)
			{
				Util.write_to_log("There was a problem sending email.   Check settings in Web.config.");
				Util.write_to_log("TO:" + to);
				Util.write_to_log("FROM:" + from);
				Util.write_to_log("SUBJECT:" + subject);
				Util.write_to_log(e.GetBaseException().Message.ToString());
				return (e.GetBaseException().Message);
			}

		}
Пример #12
0
        ///////////////////////////////////////////////////////////////////////
        void on_update()
        {
            var file = Request.Files["attached_file"];

            if (file == null)
            {
                file = Request.Files[0];
            }

            if (file == null)
            {
                write_msg("Please select file", false);
                return;
            }

            string filename = System.IO.Path.GetFileName(file.FileName);

            if (string.IsNullOrEmpty(filename))
            {
                write_msg("Please select file", false);
                return;
            }

            int max_upload_size = Convert.ToInt32(Util.get_setting("MaxUploadSize", "100000"));
            int content_length  = file.ContentLength;

            if (content_length > max_upload_size)
            {
                write_msg("File exceeds maximum allowed length of "
                          + Convert.ToString(max_upload_size)
                          + ".", false);
                return;
            }

            if (content_length == 0)
            {
                write_msg("No data was uploaded.", false);
                return;
            }

            bool good = false;

            try
            {
                Bug.insert_post_attachment(
                    User.Identity,
                    bugid,
                    file.InputStream,
                    content_length,
                    filename,
                    desc.Value,
                    file.ContentType,
                    -1, // parent
                    internal_only.Checked,
                    true);

                good = true;
            }
            catch (Exception ex)
            {
                write_msg("caught exception:" + ex.Message, false);
                return;
            }


            if (good)
            {
                write_msg(
                    filename
                    + " was successfully upload ("
                    + file.ContentType
                    + "), "
                    + Convert.ToString(content_length)
                    + " bytes"
                    , true);
            }
            else
            {
                // This should never happen....
                write_msg("Unexpected error with file upload.", false);
            }
        }
Пример #13
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();
            }
        }
        ///////////////////////////////////////////////////////////////////////
        protected void Page_Load(Object sender, EventArgs e)
        {
            Util.do_not_cache(Response);

            this.Master.Menu.SelectedItem = Util.get_setting("PluralBugLabel", "bugs");

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

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

            int permission_level = Bug.get_bug_permission_level(Convert.ToInt32(bug_id_string), User.Identity);

            if (permission_level != PermissionLevel.All)
            {
                Response.Write("You are not allowed to edit this item");
                Response.End();
            }


            if (IsPostBack)
            {
                // save the filename before deleting the row
                sql = new SQLString(@"select bp_file from bug_posts where bp_id = @ba");
                sql = sql.AddParameterWithValue("ba", attachment_id_string);
                string filename = (string)DbUtil.execute_scalar(sql);

                // delete the row representing the attachment
                sql = new SQLString(@"delete bug_post_attachments where bpa_post = @ba
            delete bug_posts where bp_id = @ba");
                sql = sql.AddParameterWithValue("ba", attachment_id_string);
                DbUtil.execute_nonquery(sql);

                // delete the file too
                string upload_folder = Util.get_upload_folder();
                if (upload_folder != null)
                {
                    StringBuilder path = new StringBuilder(upload_folder);
                    path.Append("\\");
                    path.Append(bug_id_string);
                    path.Append("_");
                    path.Append(attachment_id_string);
                    path.Append("_");
                    path.Append(filename);
                    if (System.IO.File.Exists(path.ToString()))
                    {
                        System.IO.File.Delete(path.ToString());
                    }
                }


                Response.Redirect("edit_bug.aspx?id=" + bug_id_string);
            }
            else
            {
                Page.Header.Title = Util.get_setting("AppTitle", "BugTracker.NET") + " - "
                                    + "delete attachment";

                back_href.HRef = "edit_bug.aspx?id=" + bug_id_string;

                sql = new SQLString(@"select bp_file from bug_posts where bp_id = @id");
                sql = sql.AddParameterWithValue("id", attachment_id_string);

                DataRow dr = DbUtil.get_datarow(sql);

                string s = Convert.ToString(dr["bp_file"]);

                confirm_href.InnerText = "confirm delete of attachment: " + s;

                row_id.Value = attachment_id_string;
            }
        }