/// <summary> [PUBLIC] Get the list of uploaded images for a particular aggregation </summary>
        /// <param name="Response"></param>
        /// <param name="UrlSegments"></param>
        /// <param name="QueryString"></param>
        /// <param name="Protocol"></param>
        /// <param name="IsDebug"></param>
        /// <remarks> This REST API should be publicly available for users that are performing administrative work </remarks>
        public void GetAggregationUploadedImages(HttpResponse Response, List <string> UrlSegments, NameValueCollection QueryString, Microservice_Endpoint_Protocol_Enum Protocol, bool IsDebug)
        {
            if (UrlSegments.Count > 0)
            {
                string aggregation = UrlSegments[0];

                // Ensure a valid aggregation
                Item_Aggregation_Related_Aggregations aggrInfo = Engine_ApplicationCache_Gateway.Codes[aggregation];
                if (aggrInfo != null)
                {
                    List <UploadedFileFolderInfo> serverFiles = new List <UploadedFileFolderInfo>();

                    string design_folder = Engine_ApplicationCache_Gateway.Settings.Servers.Base_Design_Location + "aggregations\\" + aggregation + "\\uploads";
                    if (Directory.Exists(design_folder))
                    {
                        string foldername = aggrInfo.ShortName;
                        if (String.IsNullOrEmpty(foldername))
                        {
                            foldername = aggregation;
                        }

                        string[] files = SobekCM_File_Utilities.GetFiles(design_folder, "*.jpg|*.bmp|*.gif|*.png");
                        foreach (string thisFile in files)
                        {
                            string filename  = Path.GetFileName(thisFile);
                            string extension = Path.GetExtension(thisFile);

                            // Exclude some files
                            if ((!String.IsNullOrEmpty(extension)) && (extension.ToLower().IndexOf(".db") < 0) && (extension.ToLower().IndexOf("bridge") < 0) && (extension.ToLower().IndexOf("cache") < 0))
                            {
                                string url = Engine_ApplicationCache_Gateway.Settings.Servers.System_Base_URL + "design/aggregations/" + aggregation + "/uploads/" + filename;
                                serverFiles.Add(new UploadedFileFolderInfo(url, foldername));
                            }
                        }
                    }

                    JSON.Serialize(serverFiles, Response.Output, Options.ISO8601ExcludeNulls);
                }
            }
        }
        /// <summary> Constructor for a new instance of the Aggregations_Mgmt_AdminViewer class </summary>
        /// <param name="User"> Authenticated user information </param>
        /// <param name="CurrentMode"> Mode / navigation information for the current request</param>
        /// <param name="Code_Manager"> List of valid collection codes, including mapping from the Sobek collections to Greenstone collections</param>
        /// <param name="Thematic_Headings"> Headings under which all the highlighted collections on the home page are organized </param>       
        /// <param name="Tracer">Trace object keeps a list of each method executed and important milestones in rendering</param>
        /// <remarks> Postback from handling an edit or new aggregation is handled here in the constructor </remarks>
        public Aggregations_Mgmt_AdminViewer(User_Object User, SobekCM_Navigation_Object CurrentMode, Aggregation_Code_Manager Code_Manager, List<Thematic_Heading> Thematic_Headings, Custom_Tracer Tracer)
            : base(User)
        {
            Tracer.Add_Trace("Aggregations_Mgmt_AdminViewer.Constructor", String.Empty);

            codeManager = Code_Manager;
            currentMode = CurrentMode;
            thematicHeadings = Thematic_Headings;

            // Set some defaults
            actionMessage = String.Empty;
            enteredCode = String.Empty;
            enteredParent = String.Empty;
            enteredType = String.Empty;
            enteredShortname = String.Empty;
            enteredName = String.Empty;
            enteredDescription = String.Empty;
            enteredIsActive = false;
            enteredIsHidden = false;

            // If the user cannot edit this, go back
            if (( user == null ) || ((!user.Is_System_Admin) && ( !user.Is_Portal_Admin )))
            {
                currentMode.Mode = Display_Mode_Enum.My_Sobek;
                currentMode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                currentMode.Redirect();
                return;
            }

            // If this is a postback, handle any events first
            if (currentMode.isPostBack)
            {
                try
                {
                    // Pull the standard values
                    NameValueCollection form = HttpContext.Current.Request.Form;

                    string save_value = form["admin_aggr_tosave"].ToUpper().Trim();
                    string new_aggregation_code = String.Empty;
                    if ( form["admin_aggr_code"] != null )
                        new_aggregation_code = form["admin_aggr_code"].ToUpper().Trim();

                    // Check for reset request as well
                    string reset_aggregation_code = String.Empty;
                    if (form["admin_aggr_reset"] != null)
                        reset_aggregation_code = form["admin_aggr_reset"].ToLower().Trim();

                    string delete_aggregation_code = String.Empty;
                    if (form["admin_aggr_delete"] != null)
                        delete_aggregation_code = form["admin_aggr_delete"].ToLower().Trim();

                    // Was this to delete the aggregation?
                    if ( delete_aggregation_code.Length > 0)
                    {
                        string delete_error;
                        int errorCode = SobekCM_Database.Delete_Item_Aggregation(delete_aggregation_code, user.Is_System_Admin, user.Full_Name, Tracer, out delete_error);
                        if (errorCode <= 0)
                        {
                            string delete_folder = SobekCM_Library_Settings.Base_Design_Location + "aggregations\\" + delete_aggregation_code;
                            if (SobekCM_File_Utilities.Delete_Folders_Recursively(delete_folder))
                                actionMessage = "Deleted '" + delete_aggregation_code + "' aggregation<br /><br />Unable to remove aggregation directory<br /><br />Some of the files may be in use";
                            else
                                actionMessage = "Deleted '" + delete_aggregation_code + "' aggregation";
                        }
                        else
                        {
                            actionMessage = delete_error;
                        }

                        // Reload the list of all codes, to include this new one and the new hierarchy
                        lock (codeManager)
                        {
                            SobekCM_Database.Populate_Code_Manager(codeManager, Tracer);
                        }
                    }

                    // If there is a reset request here, purge the aggregation from the cache
                    if (reset_aggregation_code.Length > 0)
                    {
                        Cached_Data_Manager.Remove_Item_Aggregation(reset_aggregation_code, Tracer);
                    }

                    // If there was a save value continue to pull the rest of the data
                    if (save_value.Length > 0)
                    {

                        bool is_active = false;
                        bool is_hidden = true;

                        // Was this to save a new aggregation (from the main page) or edit an existing (from the popup form)?
                        if (save_value == new_aggregation_code)
                        {

                            // Pull the values from the submitted form
                            string new_type = form["admin_aggr_type"];
                            string new_parent = form["admin_aggr_parent"].Trim();
                            string new_name = form["admin_aggr_name"].Trim();
                            string new_shortname = form["admin_aggr_shortname"].Trim();
                            string new_description = form["admin_aggr_desc"].Trim();
                            string new_link = form["admin_aggr_link"].Trim();

                            object temp_object = form["admin_aggr_isactive"];
                            if (temp_object != null)
                            {
                                is_active = true;
                            }

                            temp_object = form["admin_aggr_ishidden"];
                            if (temp_object != null)
                            {
                                is_hidden = false;
                            }

                            // Convert to the integer id for the parent and begin to do checking
                            List<string> errors = new List<string>();
                            int parentid = -1;
                            if (new_parent.Length > 0)
                            {
                                try
                                {
                                    parentid = Convert.ToInt32(new_parent);
                                }
                                catch
                                {
                                    errors.Add("Invalid parent id selected!");
                                }
                            }
                            else
                            {
                                errors.Add("You must select a PARENT for this new aggregation");
                            }

                            // Validate the code
                            if (new_aggregation_code.Length > 20)
                            {
                                errors.Add("New aggregation code must be twenty characters long or less");
                            }
                            else if (new_aggregation_code.Length == 0)
                            {
                                errors.Add("You must enter a CODE for this item aggregation");

                            }
                            else if (codeManager[new_aggregation_code.ToUpper()] != null)
                            {
                                errors.Add("New code must be unique... <i>" + new_aggregation_code + "</i> already exists");
                            }
                            else if (SobekCM_Library_Settings.Reserved_Keywords.Contains(new_aggregation_code.ToLower()))
                            {
                                errors.Add("That code is a system-reserved keyword.  Try a different code.");
                            }

                            // Was there a type and name
                            if (new_type.Length == 0)
                            {
                                errors.Add("You must select a TYPE for this new aggregation");
                            }
                            if (new_description.Length == 0)
                            {
                                errors.Add("You must enter a DESCRIPTION for this new aggregation");
                            }
                            if (new_name.Length == 0)
                            {
                                errors.Add("You must enter a NAME for this new aggregation");
                            }
                            else
                            {
                                if (new_shortname.Length == 0)
                                    new_shortname = new_name;
                            }

                            if (errors.Count > 0)
                            {
                                // Create the error message
                                actionMessage = "ERROR: Invalid entry for new item aggregation<br />";
                                foreach (string error in errors)
                                    actionMessage = actionMessage + "<br />" + error;

                                // Save all the values that were entered
                                enteredCode = new_aggregation_code;
                                enteredDescription = new_description;
                                enteredIsActive = is_active;
                                enteredIsHidden = is_hidden;
                                enteredName = new_name;
                                enteredParent = new_parent;
                                enteredShortname = new_shortname;
                                enteredType = new_type;
                                enteredLink = new_link;
                            }
                            else
                            {
                                // Get the correct type
                                string correct_type = "Collection";
                                switch (new_type)
                                {
                                    case "coll":
                                        correct_type = "Collection";
                                        break;

                                    case "group":
                                        correct_type = "Collection Group";
                                        break;

                                    case "subcoll":
                                        correct_type = "SubCollection";
                                        break;

                                    case "inst":
                                        correct_type = "Institution";
                                        break;

                                    case "exhibit":
                                        correct_type = "Exhibit";
                                        break;

                                    case "subinst":
                                        correct_type = "Institutional Division";
                                        break;
                                }
                                // Make sure inst and subinst start with 'i'
                                if (new_type.IndexOf("inst") >= 0)
                                {
                                    if (new_aggregation_code[0] == 'I')
                                        new_aggregation_code = "i" + new_aggregation_code.Substring(1);
                                    if (new_aggregation_code[0] != 'i')
                                        new_aggregation_code = "i" + new_aggregation_code;
                                }

                                // Get the thematic heading id (no checks here)
                                int thematicHeadingId = -1;
                                if (form["admin_aggr_heading"] != null)
                                    thematicHeadingId = Convert.ToInt32(form["admin_aggr_heading"]);

                                // Try to save the new item aggregation
                                if (SobekCM_Database.Save_Item_Aggregation(new_aggregation_code, new_name, new_shortname, new_description, thematicHeadingId, correct_type, is_active, is_hidden, new_link, parentid, user.Full_Name, Tracer))
                                {
                                    // Ensure a folder exists for this, otherwise create one
                                    try
                                    {
                                        string folder = SobekCM_Library_Settings.Base_Design_Location + "aggregations\\" + new_aggregation_code.ToLower();
                                        if (!Directory.Exists(folder))
                                        {
                                            // Create this directory and all the subdirectories
                                            Directory.CreateDirectory(folder);
                                            Directory.CreateDirectory(folder + "/html");
                                            Directory.CreateDirectory(folder + "/images");
                                            Directory.CreateDirectory(folder + "/html/home");
                                            Directory.CreateDirectory(folder + "/images/buttons");
                                            Directory.CreateDirectory(folder + "/images/banners");

                                            // Create a default home text file
                                            StreamWriter writer = new StreamWriter(folder + "/html/home/text.html");
                                            writer.WriteLine("<br />New collection home page text goes here.<br /><br />To edit this, log on as the aggregation admin and hover over this text to edit it.<br /><br />");
                                            writer.Flush();
                                            writer.Close();

                                            // Copy the default banner and buttons from images
                                            if (File.Exists(SobekCM_Library_Settings.Base_Directory + "default/images/default_button.png"))
                                                File.Copy(SobekCM_Library_Settings.Base_Directory + "default/images/default_button.png", folder + "/images/buttons/coll.png");
                                            if (File.Exists(SobekCM_Library_Settings.Base_Directory + "default/images/default_button.gif"))
                                                File.Copy(SobekCM_Library_Settings.Base_Directory + "default/images/default_button.gif", folder + "/images/buttons/coll.gif");

                                            // Try to create a new custom banner
                                            bool custom_banner_created = false;
                                            // Create the banner with the name of the collection
                                            if (Directory.Exists(SobekCM_Library_Settings.Application_Server_Network + "\\default\\banner_images"))
                                            {
                                                try
                                                {
                                                    string[] banners = Directory.GetFiles(SobekCM_Library_Settings.Application_Server_Network + "\\default\\banner_images", "*.jpg");
                                                    if (banners.Length > 0)
                                                    {
                                                        Random randomizer = new Random();
                                                        string banner_to_use = banners[randomizer.Next(0, banners.Length - 1)];
                                                        Bitmap bitmap = (Bitmap)System.Drawing.Bitmap.FromFile(banner_to_use);

                                                        RectangleF rectf = new RectangleF(30, bitmap.Height - 55, bitmap.Width - 40, 40);
                                                        Graphics g = Graphics.FromImage(bitmap);
                                                        g.SmoothingMode = SmoothingMode.AntiAlias;
                                                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                                        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                                                        g.DrawString(new_name, new Font("Tahoma", 25, FontStyle.Bold), Brushes.Black, rectf);
                                                        g.Flush();

                                                        string new_file = folder + "/images/banners/coll.jpg";
                                                        if (!File.Exists(new_file))
                                                        {
                                                            bitmap.Save(new_file, ImageFormat.Jpeg);
                                                            custom_banner_created = true;
                                                        }
                                                    }
                                                }
                                                catch (Exception ee)
                                                {
                                                    string msg = ee.Message;
                                                }
                                            }

                                            if ((!custom_banner_created) && (!File.Exists(folder + "/images/banners/coll.jpg")))
                                            {
                                                if (File.Exists(SobekCM_Library_Settings.Base_Directory + "default/images/default_banner.jpg"))
                                                    File.Copy(SobekCM_Library_Settings.Base_Directory + "default/images/default_banner.jpg", folder + "/images/banners/coll.jpg");
                                            }

                                            // Now, try to create the item aggregation and write the configuration file
                                            Item_Aggregation itemAggregation = Item_Aggregation_Builder.Get_Item_Aggregation(new_aggregation_code, String.Empty, null, false, false, Tracer);
                                            itemAggregation.Write_Configuration_File(SobekCM_Library_Settings.Base_Design_Location + itemAggregation.ObjDirectory);
                                        }
                                    }
                                    catch
                                    {
                                        actionMessage = "ERROR saving the new item aggregation to the database";
                                    }

                                    // Reload the list of all codes, to include this new one and the new hierarchy
                                    lock (codeManager)
                                    {
                                        SobekCM_Database.Populate_Code_Manager(codeManager, Tracer);
                                    }
                                    if ( !String.IsNullOrEmpty(actionMessage))
                                        actionMessage = "New item aggregation <i>" + new_aggregation_code + "</i> saved successfully";
                                }
                                else
                                {
                                    actionMessage = "ERROR saving the new item aggregation to the database";
                                }
                            }
                        }
                    }
                }
                catch
                {
                    actionMessage = "General error while reading postback information";
                }
            }
        }
Пример #3
0
        public Import_Spreadsheet_MySobekViewer(RequestCache RequestSpecificValues) : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Import_Spreadsheet_MySobekViewer.Constructor", String.Empty);

            // If the RequestSpecificValues.Current_User cannot submit items, go back
            //if (!RequestSpecificValues.Current_User.Can_Submit)
            //{
            //    RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
            //    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
            //    return;
            //}

            // Create a new GUID for this task, or get from the session state
            string guid = HttpContext.Current.Session["Import_Data_Current_GUID"] as string;

            if (String.IsNullOrEmpty(guid))
            {
                guid = Guid.NewGuid().ToString();
                HttpContext.Current.Session.Add("Import_Data_Current_GUID", guid);
            }

            // Determine the in process directory for this
            if (RequestSpecificValues.Current_User.ShibbID.Trim().Length > 0)
            {
                taskUrl       = RequestSpecificValues.Current_Mode.Base_URL + "mySobek/InProcess/" + RequestSpecificValues.Current_User.ShibbID + "/task/" + guid;
                taskDirectory = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.In_Process_Submission_Location, RequestSpecificValues.Current_User.ShibbID, "task", guid);
            }
            else
            {
                taskUrl       = RequestSpecificValues.Current_Mode.Base_URL + "mySobek/InProcess/" + RequestSpecificValues.Current_User.UserName.Replace(".", "").Replace("@", "") + "/task/" + guid;
                taskDirectory = Path.Combine(UI_ApplicationCache_Gateway.Settings.Servers.In_Process_Submission_Location, RequestSpecificValues.Current_User.UserName.Replace(".", "").Replace("@", ""), "task", guid);
            }

            // Try to determine the current page
            page = 1;
            int.TryParse(RequestSpecificValues.Current_Mode.My_Sobek_SubMode, out page);
            if (page < 1)
            {
                page = 1;
            }

            // Is there a data file here?
            string extension = null;

            if (Directory.Exists(taskDirectory))
            {
                string[] source_file = SobekCM_File_Utilities.GetFiles(taskDirectory, "*.xls|*.xlsx|*.csv|*.mrc");
                if (source_file.Length > 0)
                {
                    file_name = Path.GetFileName(source_file[0]);
                    extension = Path.GetExtension(source_file[0]);
                }
            }

            // Determine file type
            if ((!String.IsNullOrEmpty(file_name)) && (!String.IsNullOrEmpty(extension)))
            {
                switch (extension.ToUpper())
                {
                case ".XLS":
                case ".XLSX":
                    file_type = Import_File_Type_Enum.Excel;
                    break;

                case ".CSV":
                case ".TXT":
                    file_type = Import_File_Type_Enum.CSV;
                    break;

                case ".MRC":
                    file_type = Import_File_Type_Enum.Marc21;
                    break;

                case ".XML":
                    file_type = Import_File_Type_Enum.MarcXML;
                    break;
                }
            }
            else
            {
                file_type = Import_File_Type_Enum.None;
            }

            // Handle postback for changing the CompleteTemplate or project
            if (RequestSpecificValues.Current_Mode.isPostBack)
            {
                string action1 = HttpContext.Current.Request.Form["action"];
                if (action1 == "cancel")
                {
                    if (Directory.Exists(taskDirectory))
                    {
                        string[] allFiles = Directory.GetFiles(taskDirectory);
                        foreach (string thisFile in allFiles)
                        {
                            File.Delete(thisFile);
                        }
                        Directory.Delete(taskDirectory);
                    }
                    HttpContext.Current.Session["Import_Data_Current_GUID"]      = null;
                    HttpContext.Current.Session["Import_Data_Current_Worksheet"] = null;
                    RequestSpecificValues.Current_Mode.My_Sobek_Type             = My_Sobek_Type_Enum.Home;
                    UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                    return;
                }

                if (action1 == "delete")
                {
                    if (Directory.Exists(taskDirectory))
                    {
                        string file = Path.Combine(taskDirectory, file_name);
                        if (File.Exists(file))
                        {
                            File.Delete(file);
                        }
                    }

                    page      = 1;
                    file_name = String.Empty;
                    file_type = Import_File_Type_Enum.None;
                    HttpContext.Current.Session["Import_Data_Current_Worksheet"] = null;
                }
            }
        }
        /// <summary> Moves all packages from the inbound folder into the processing folder
        /// to queue them for loading into the library  </summary>
        /// <param name="Message"> Message to be passed out if something occurred during this attempted move </param>
        /// <returns> TRUE if successful, or FALSE if an error occurs </returns>
        public bool Move_From_Inbound_To_Processing(InstanceWide_Settings Settings, out string Message)
        {
            Message = String.Empty;

            // Get the directories
            string inboundFolder = Inbound_Folder;

            // Make sure the inbound directory exists
            if (!Directory.Exists(inboundFolder))
            {
                try
                {
                    Directory.CreateDirectory(inboundFolder);
                }
                catch
                {
                    Message = "Unable to create the non-existent inbound folder " + inboundFolder;
                    return(false);
                }
            }

            // Make sure the processing directory exists
            if (!Directory.Exists(Processing_Folder))
            {
                try
                {
                    Directory.CreateDirectory(Processing_Folder);
                }
                catch
                {
                    Message = "Unable to create the non-existent processing folder " + Processing_Folder;
                    return(false);
                }
            }

            // Make sure the failures directory exists
            if (!Directory.Exists(Failures_Folder))
            {
                try
                {
                    Directory.CreateDirectory(Failures_Folder);
                }
                catch
                {
                    Message = "Unable to create the non-existent failures folder " + Failures_Folder;
                    return(false);
                }
            }

            // If there are loose METS here, move them into flat folders of the same name
            try
            {
                string[] looseMets = SobekCM_File_Utilities.GetFiles(inboundFolder, "*.mets*|*.xml");
                foreach (string thisLooseMetsXml in looseMets)
                {
                    string filename         = Path.GetFileName(thisLooseMetsXml);
                    string filenameSplitter = Path.GetFileNameWithoutExtension(thisLooseMetsXml);
                    if (!Directory.Exists(inboundFolder + "\\" + filenameSplitter))
                    {
                        Directory.CreateDirectory(inboundFolder + "\\" + filenameSplitter);
                    }
                    if (File.Exists(inboundFolder + "\\" + filenameSplitter + "\\" + filename))
                    {
                        File.Delete(thisLooseMetsXml);
                    }
                    else
                    {
                        File.Move(thisLooseMetsXml, inboundFolder + "\\" + filenameSplitter + "\\" + filename);
                    }
                }
            }
            catch (Exception ee)
            {
                Message = "Error moving the package from " + inboundFolder + " to " + Processing_Folder + ":" + ee.Message;
                return(false);
            }


            // Get the list of all terminal directories
            IEnumerable <string> terminalDirectories = Get_Terminal_SubDirectories(inboundFolder);

            // Create a digital resource object for each directory
            List <Incoming_Digital_Resource> inboundResources = terminalDirectories.Select(ThisDirectory => new Incoming_Digital_Resource(ThisDirectory, this)).ToList();

            // Step through each resource which came in
            bool returnVal = true;

            foreach (Incoming_Digital_Resource resource in inboundResources)
            {
                // Is this resource a candidate to move for continued processing?
                long resource_age = resource.AgeInTicks;
                if ((resource_age > Settings.Builder.Complete_Package_Required_Aging) || ((resource_age > Settings.Builder.METS_Only_Package_Required_Aging) && (resource.METS_Only_Package)))
                {
                    if (!resource.Move(Processing_Folder))
                    {
                        returnVal = false;
                    }
                }
                else
                {
                    Message = "Resource ( " + resource.Resource_Folder + " ) needs to age more before it will be processed";
                }
            }

            return(returnVal);
        }
        /// <summary> Adds ALL the image files to the digital resource, regardless if they were just uploaded or not </summary>
        /// <param name="Resource"> Incoming digital resource object </param>
        /// <returns> TRUE if processing can continue, FALSE if a critical error occurred which should stop all processing </returns>
        public override bool DoWork(Incoming_Digital_Resource Resource)
        {
            bool jpeg_added     = false;
            bool jpeg2000_added = false;
            int  jpeg_files     = 0;

            // Ensure all non-image files are linked to the METS file
            string[] all_files = SobekCM_File_Utilities.GetFiles(Resource.Resource_Folder, "*.jp2|*.jpg");
            foreach (string thisFile in all_files)
            {
                string filename  = Path.GetFileName(thisFile);
                string extension = Path.GetExtension(thisFile);

                if ((filename == null) || (extension == null))
                {
                    continue;
                }

                extension = extension.ToLower().Replace(".", "");

                // Also, check to see if this is a jpeg or jpeg2000
                if (extension == "jp2")
                {
                    // Try to just always add JPEG2000s
                    Resource.Metadata.Divisions.Physical_Tree.Add_File(filename);
                    jpeg2000_added = true;
                }
                if (extension == "jpg")
                {
                    // If this is a thumbnail jpeg, only add if a regular JPEG or JP2000 exists
                    // Otherwise, it is likely just a thumbnail for a PDF or PPT file or something
                    if (filename.IndexOf("thm.jpg", StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        string possible_jpeg     = thisFile.ToLower().Replace("thm.jpg", ".jpg");
                        string possible_jpeg2000 = thisFile.ToLower().Replace("thm.jpg", "jp2");

                        if ((File.Exists(possible_jpeg)) || (File.Exists(possible_jpeg2000)))
                        {
                            Resource.Metadata.Divisions.Physical_Tree.Add_File(filename);
                        }
                    }
                    else
                    {
                        // Non thumbnail, so go ahead and add it
                        Resource.Metadata.Divisions.Physical_Tree.Add_File(filename);
                        jpeg_added = true;
                        jpeg_files++;
                    }
                }
            }

            //// Ensure proper views are attached to this item
            //if ((jpeg2000_added) || (jpeg_added))
            //{
            //    if (jpeg_added)
            //    {
            //        Resource.Metadata.Behaviors.Add_View(View_Enum.JPEG);
            //        if ( jpeg_files > 1 )
            //            Resource.Metadata.Behaviors.Add_View(View_Enum.RELATED_IMAGES);
            //        if ((jpeg_files >= 4) && (Settings.Builder.Add_PageTurner_ItemViewer))
            //            Resource.Metadata.Behaviors.Add_View(View_Enum.PAGE_TURNER);
            //        if (jpeg2000_added)
            //            Resource.Metadata.Behaviors.Add_View(View_Enum.JPEG2000);
            //    }
            //    else
            //    {
            //        Resource.Metadata.Behaviors.Add_View(View_Enum.JPEG2000);
            //    }
            //}

            // THIS IS A TEMPORARY FIX FOR THUMBNAILS ACCIDENTALLY ADDED
            List <abstract_TreeNode> allPages = Resource.Metadata.Divisions.Physical_Tree.Pages_PreOrder;

            foreach (Page_TreeNode thisPage in allPages)
            {
                // If there is only one file attached, look for the thumbnails
                if (thisPage.Files.Count == 1)
                {
                    // If the only file is a thumbnail, just CLEAR this page.  That should
                    // cause the page to be skipped
                    string fileName = thisPage.Files[0].System_Name;
                    if (fileName.IndexOf("thm.jpg", StringComparison.OrdinalIgnoreCase) > 0)
                    {
                        thisPage.Files.Clear();
                    }
                }
            }

            return(true);
        }
Пример #6
0
        /// <summary> Constructor for a new instance of the Aggregations_Mgmt_AdminViewer class </summary>
        /// <param name="RequestSpecificValues"> All the necessary, non-global data specific to the current request </param>
        /// <remarks> Postback from handling an edit or new aggregation is handled here in the constructor </remarks>
        public Aggregations_Mgmt_AdminViewer(RequestCache RequestSpecificValues) : base(RequestSpecificValues)
        {
            RequestSpecificValues.Tracer.Add_Trace("Aggregations_Mgmt_AdminViewer.Constructor", String.Empty);

            // Set some defaults
            actionMessage          = String.Empty;
            enteredCode            = String.Empty;
            enteredParent          = String.Empty;
            enteredType            = String.Empty;
            enteredShortname       = String.Empty;
            enteredName            = String.Empty;
            enteredDescription     = String.Empty;
            enteredThematicHeading = String.Empty;
            enteredIsActive        = true;
            enteredIsHidden        = false;
            addedNewCollection     = false;

            // If the user cannot edit this, go back
            if ((RequestSpecificValues.Current_User == null) || ((!RequestSpecificValues.Current_User.Is_System_Admin) && (!RequestSpecificValues.Current_User.Is_Portal_Admin)))
            {
                RequestSpecificValues.Current_Mode.Mode          = Display_Mode_Enum.My_Sobek;
                RequestSpecificValues.Current_Mode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                UrlWriterHelper.Redirect(RequestSpecificValues.Current_Mode);
                return;
            }

            // If this is a postback, handle any events first
            if (RequestSpecificValues.Current_Mode.isPostBack)
            {
                try
                {
                    // Pull the standard values
                    NameValueCollection form = HttpContext.Current.Request.Form;

                    string save_value           = form["admin_aggr_tosave"].ToUpper().Trim();
                    string new_aggregation_code = String.Empty;
                    if (form["admin_aggr_code"] != null)
                    {
                        new_aggregation_code = form["admin_aggr_code"].ToUpper().Trim();
                    }

                    // Check for reset request as well
                    string reset_aggregation_code = String.Empty;
                    if (form["admin_aggr_reset"] != null)
                    {
                        reset_aggregation_code = form["admin_aggr_reset"].ToLower().Trim();
                    }

                    string delete_aggregation_code = String.Empty;
                    if (form["admin_aggr_delete"] != null)
                    {
                        delete_aggregation_code = form["admin_aggr_delete"].ToLower().Trim();
                    }

                    // Was this to delete the aggregation?
                    if (delete_aggregation_code.Length > 0)
                    {
                        string delete_error;
                        int    errorCode = SobekCM_Database.Delete_Item_Aggregation(delete_aggregation_code, RequestSpecificValues.Current_User.Is_System_Admin, RequestSpecificValues.Current_User.Full_Name, RequestSpecificValues.Tracer, out delete_error);
                        if (errorCode <= 0)
                        {
                            string delete_folder = UI_ApplicationCache_Gateway.Settings.Servers.Base_Design_Location + "aggregations\\" + delete_aggregation_code;
                            if (!SobekCM_File_Utilities.Delete_Folders_Recursively(delete_folder))
                            {
                                actionMessage = "Deleted '" + delete_aggregation_code.ToUpper() + "' aggregation<br /><br />Unable to remove aggregation directory<br /><br />Some of the files may be in use";
                            }
                            else
                            {
                                actionMessage = "Deleted '" + delete_aggregation_code.ToUpper() + "' aggregation";
                            }
                        }
                        else
                        {
                            actionMessage = delete_error;
                        }

                        CachedDataManager.Aggregations.Clear();

                        // Reload the list of all codes, to include this new one and the new hierarchy
                        lock (UI_ApplicationCache_Gateway.Aggregations)
                        {
                            Engine_Database.Populate_Code_Manager(UI_ApplicationCache_Gateway.Aggregations, RequestSpecificValues.Tracer);
                        }
                    }


                    // If there is a reset request here, purge the aggregation from the cache
                    if (reset_aggregation_code.Length > 0)
                    {
                        CachedDataManager.Aggregations.Remove_Item_Aggregation(reset_aggregation_code, RequestSpecificValues.Tracer);
                    }

                    // If there was a save value continue to pull the rest of the data
                    if (save_value.Length > 0)
                    {
                        bool is_active = false;
                        bool is_hidden = true;


                        // Was this to save a new aggregation (from the main page) or edit an existing (from the popup form)?
                        if (save_value == new_aggregation_code)
                        {
                            addedNewCollection = true;

                            // Pull the values from the submitted form
                            string new_type             = form["admin_aggr_type"];
                            string new_parent           = form["admin_aggr_parent"].Trim();
                            string new_name             = form["admin_aggr_name"].Trim();
                            string new_shortname        = form["admin_aggr_shortname"].Trim();
                            string new_description      = form["admin_aggr_desc"].Trim();
                            string new_link             = form["admin_aggr_link"].Trim();
                            string new_thematic_heading = form["admin_aggr_heading"].Trim();

                            object temp_object = form["admin_aggr_isactive"];
                            if (temp_object != null)
                            {
                                is_active = true;
                            }

                            temp_object = form["admin_aggr_ishidden"];
                            if (temp_object != null)
                            {
                                is_hidden = false;
                            }

                            // Convert to the integer id for the parent and begin to do checking
                            List <string> errors = new List <string>();
                            if (String.IsNullOrEmpty(new_parent))
                            {
                                errors.Add("You must select a PARENT for this new aggregation");
                            }

                            // Validate the code

                            if (new_aggregation_code.Length > 20)
                            {
                                errors.Add("New aggregation code must be twenty characters long or less");
                            }
                            else if (new_aggregation_code.Length == 0)
                            {
                                errors.Add("You must enter a CODE for this item aggregation");
                            }
                            else if (UI_ApplicationCache_Gateway.Aggregations[new_aggregation_code.ToUpper()] != null)
                            {
                                errors.Add("New code must be unique... <i>" + new_aggregation_code + "</i> already exists");
                            }
                            else if (UI_ApplicationCache_Gateway.Settings.Static.Reserved_Keywords.Contains(new_aggregation_code.ToLower()))
                            {
                                errors.Add("That code is a system-reserved keyword.  Try a different code.");
                            }
                            else
                            {
                                bool alphaNumericTest = new_aggregation_code.All(C => Char.IsLetterOrDigit(C) || C == '_' || C == '-');
                                if (!alphaNumericTest)
                                {
                                    errors.Add("New aggregation code must be only letters and numbers");
                                    new_aggregation_code = new_aggregation_code.Replace("\"", "");
                                }
                            }

                            // Was there a type and name
                            if (new_type.Length == 0)
                            {
                                errors.Add("You must select a TYPE for this new aggregation");
                            }
                            if (new_description.Length == 0)
                            {
                                errors.Add("You must enter a DESCRIPTION for this new aggregation");
                            }
                            if (new_name.Length == 0)
                            {
                                errors.Add("You must enter a NAME for this new aggregation");
                            }
                            else
                            {
                                if (new_shortname.Length == 0)
                                {
                                    new_shortname = new_name;
                                }
                            }

                            if (errors.Count > 0)
                            {
                                // Create the error message
                                actionMessage = "ERROR: Invalid entry for new item aggregation<br />";
                                foreach (string error in errors)
                                {
                                    actionMessage = actionMessage + "<br />" + error;
                                }

                                // Save all the values that were entered
                                enteredCode            = new_aggregation_code;
                                enteredDescription     = new_description;
                                enteredIsActive        = is_active;
                                enteredIsHidden        = is_hidden;
                                enteredName            = new_name;
                                enteredParent          = new_parent;
                                enteredShortname       = new_shortname;
                                enteredType            = new_type;
                                enteredLink            = new_link;
                                enteredThematicHeading = new_thematic_heading;
                            }
                            else
                            {
                                // Get the correct type
                                string correct_type = "Collection";
                                switch (new_type)
                                {
                                case "coll":
                                    correct_type = "Collection";
                                    break;

                                case "group":
                                    correct_type = "Collection Group";
                                    break;

                                case "subcoll":
                                    correct_type = "SubCollection";
                                    break;

                                case "inst":
                                    correct_type = "Institution";
                                    break;

                                case "exhibit":
                                    correct_type = "Exhibit";
                                    break;

                                case "subinst":
                                    correct_type = "Institutional Division";
                                    break;
                                }
                                // Make sure inst and subinst start with 'i'
                                if (new_type.IndexOf("inst") >= 0)
                                {
                                    if (new_aggregation_code[0] == 'I')
                                    {
                                        new_aggregation_code = "i" + new_aggregation_code.Substring(1);
                                    }
                                    if (new_aggregation_code[0] != 'i')
                                    {
                                        new_aggregation_code = "i" + new_aggregation_code;
                                    }
                                }

                                // Get the thematic heading id (no checks here)
                                string thematicHeading = null;
                                if (form["admin_aggr_heading"] != null)
                                {
                                    int thematicHeadingId = Convert.ToInt32(form["admin_aggr_heading"]);
                                    foreach (Thematic_Heading thisHeading in UI_ApplicationCache_Gateway.Thematic_Headings)
                                    {
                                        if (thisHeading.ID == thematicHeadingId)
                                        {
                                            thematicHeading = thisHeading.Text;
                                            break;
                                        }
                                    }
                                }

                                // Create the new aggregation argument object
                                New_Aggregation_Arguments args = new New_Aggregation_Arguments
                                {
                                    Active           = is_active,
                                    Code             = new_aggregation_code,
                                    Description      = new_description,
                                    External_Link    = enteredLink,
                                    Hidden           = is_hidden,
                                    Name             = new_name,
                                    ParentCode       = new_parent,
                                    ShortName        = new_shortname,
                                    Thematic_Heading = thematicHeading,
                                    Type             = correct_type,
                                    User             = RequestSpecificValues.Current_User.Full_Name
                                };

                                // Try to add this aggregation
                                RestResponseMessage msg = SobekEngineClient.Aggregations.Add_New_Aggregation(args);

                                // We are going to save some of the values here anyway, to assist with bulk adds
                                enteredIsActive        = is_active;
                                enteredIsHidden        = is_hidden;
                                enteredParent          = new_parent;
                                enteredType            = new_type;
                                enteredLink            = new_link;
                                enteredThematicHeading = new_thematic_heading;

                                if (msg.ErrorTypeEnum == ErrorRestTypeEnum.Successful)
                                {
                                    RequestSpecificValues.Current_Mode.Mode        = Display_Mode_Enum.Aggregation;
                                    RequestSpecificValues.Current_Mode.Aggregation = new_aggregation_code;
                                    actionMessage = "New item aggregation (" + new_aggregation_code.ToUpper() + ") saved successfully.<br /><br /><a href=\"" + UrlWriterHelper.Redirect_URL(RequestSpecificValues.Current_Mode, true) + "\" target=\"" + new_aggregation_code + "_AGGR\">Click here to view the new aggregation</a>";
                                    RequestSpecificValues.Current_Mode.Mode       = Display_Mode_Enum.Administrative;
                                    RequestSpecificValues.Current_Mode.Admin_Type = Admin_Type_Enum.Aggregations_Mgmt;

                                    // Clear all aggregation information (and thematic heading info) from the cache as well
                                    CachedDataManager.Aggregations.Clear();
                                }
                                else
                                {
                                    actionMessage      = msg.Message;
                                    enteredCode        = new_aggregation_code;
                                    enteredShortname   = new_shortname;
                                    enteredName        = new_name;
                                    enteredDescription = new_description;
                                }
                            }
                        }
                    }
                }
                catch
                {
                    actionMessage = "General error while reading postback information";
                }
            }
        }
        /// <summary> Constructor for a new instance of the Wordmarks_AdminViewer class </summary>
        /// <param name="User"> Authenticated user information </param>
        /// <param name="Current_Mode"> Mode / navigation information for the current request</param>
        /// <param name="Tracer">Trace object keeps a list of each method executed and important milestones in rendering</param>
        /// <remarks> Postback from editing an existing wordmark, deleting a wordmark, or creating a new wordmark is handled here in the constructor </remarks>
        public Wordmarks_AdminViewer(User_Object User, SobekCM_Navigation_Object Current_Mode, Custom_Tracer Tracer) : base(User)
        {
            Tracer.Add_Trace("Wordmarks_AdminViewer.Constructor", String.Empty);

            // Save the mode and settings  here
            currentMode = Current_Mode;

            // Set action message to nothing to start
            actionMessage = String.Empty;

            // If the user cannot edit this, go back
            if ((user == null) || ((!user.Is_System_Admin) && (!user.Is_Portal_Admin)))
            {
                currentMode.Mode          = Display_Mode_Enum.My_Sobek;
                currentMode.My_Sobek_Type = My_Sobek_Type_Enum.Home;
                currentMode.Redirect();
                return;
            }

            // Get the wordmark directory and ensure it exists
            wordmarkDirectory = HttpContext.Current.Server.MapPath("design/wordmarks");
            if (!Directory.Exists(wordmarkDirectory))
            {
                Directory.CreateDirectory(wordmarkDirectory);
            }

            // Get the list of all wordmarks
            wordmarks = new Dictionary <string, Wordmark_Icon>();
            SobekCM_Database.Populate_Icon_List(wordmarks, Tracer);

            // If this is a postback, handle any events first
            // if (currentMode.isPostBack)
            // {
            try
            {
                // Pull the standard values
                NameValueCollection form = HttpContext.Current.Request.Form;
                if (form["admin_wordmark_code_delete"] != null)
                {
                    string delete_value      = form["admin_wordmark_code_delete"].ToUpper().Trim();
                    string save_value        = form["admin_wordmark_code_tosave"].ToUpper().Trim();
                    string new_wordmark_code = form["admin_wordmark_code"].ToUpper().Trim();

                    // Was this a reset request?
                    if (delete_value.Length > 0)
                    {
                        // If the value to delete does not have a period, then it has no extension,
                        // so this is to delete a USED wordmark which is both a file AND in the database
                        if (delete_value.IndexOf(".") < 0)
                        {
                            Tracer.Add_Trace("Wordmarks_AdminViewer.Constructor", "Delete wordmark '" + delete_value + "' from the database");

                            // Get the wordmark, so we can also delete the file
                            Wordmark_Icon deleteIcon = wordmarks[delete_value];

                            // Delete from the database
                            if (SobekCM_Database.Delete_Icon(delete_value, Tracer))
                            {
                                // Set the deleted wordmark message
                                actionMessage = "Deleted wordmark <i>" + delete_value + "</i>";

                                // Try to delete the file related to this wordmark now
                                if ((deleteIcon != null) && (File.Exists(wordmarkDirectory + "\\" + deleteIcon.Image_FileName)))
                                {
                                    try
                                    {
                                        File.Delete(wordmarkDirectory + "\\" + deleteIcon.Image_FileName);
                                    }
                                    catch (Exception)
                                    {
                                        actionMessage = "Deleted wordmark <i>" + delete_value + "</i> but unable to delete the file <i>" + deleteIcon.Image_FileName + "</i>";
                                    }
                                }

                                // Repull the wordmark list now
                                wordmarks = new Dictionary <string, Wordmark_Icon>();
                                SobekCM_Database.Populate_Icon_List(wordmarks, Tracer);
                            }
                            else
                            {
                                // Report the error
                                if (SobekCM_Database.Last_Exception == null)
                                {
                                    actionMessage = "Unable to delete wordmark <i>" + delete_value + "</i> since it is in use";
                                }
                                else
                                {
                                    actionMessage = "Unknown error while deleting wordmark <i>" + delete_value + "</i>";
                                }
                            }
                        }
                        else
                        {
                            // This is to delete just a file, which presumably is unused by the system
                            // and does not appear in the database
                            // Try to delete the file related to this wordmark now
                            if (File.Exists(wordmarkDirectory + "\\" + delete_value))
                            {
                                try
                                {
                                    File.Delete(wordmarkDirectory + "\\" + delete_value);
                                    actionMessage = "Deleted unused image file <i>" + delete_value + "</i>";
                                }
                                catch (Exception)
                                {
                                    actionMessage = "Unable to delete unused image <i>" + delete_value + "</i>";
                                }
                            }
                        }
                    }
                    else
                    {
                        // Or.. was this a save request
                        if (save_value.Length > 0)
                        {
                            Tracer.Add_Trace("Wordmarks_AdminViewer.Constructor", "Save wordmark '" + save_value + "'");

                            // Was this to save a new interface (from the main page) or edit an existing (from the popup form)?
                            if (save_value == new_wordmark_code)
                            {
                                string new_file  = form["admin_wordmark_file"].Trim();
                                string new_link  = form["admin_wordmark_link"].Trim();
                                string new_title = form["admin_wordmark_title"].Trim();

                                // Save this new wordmark
                                if (SobekCM_Database.Save_Icon(new_wordmark_code, new_file, new_link, new_title, Tracer) > 0)
                                {
                                    actionMessage = "Saved new wordmark <i>" + save_value + "</i>";
                                }
                                else
                                {
                                    actionMessage = "Unable to save new wordmark <i>" + save_value + "</i>";
                                }
                            }
                            else
                            {
                                string edit_file  = form["form_wordmark_file"].Trim();
                                string edit_link  = form["form_wordmark_link"].Trim();
                                string edit_title = form["form_wordmark_title"].Trim();

                                // Save this existing wordmark
                                if (SobekCM_Database.Save_Icon(save_value, edit_file, edit_link, edit_title, Tracer) > 0)
                                {
                                    actionMessage = "Edited existing wordmark <i>" + save_value + "</i>";
                                }
                                else
                                {
                                    actionMessage = "Unable to edit existing wordmark <i>" + save_value + "</i>";
                                }
                            }

                            // Repull the wordmark list now
                            wordmarks = new Dictionary <string, Wordmark_Icon>();
                            SobekCM_Database.Populate_Icon_List(wordmarks, Tracer);
                        }
                    }
                }
            }
            catch (Exception)
            {
                actionMessage = "Unknown error caught while handing request.";
            }
            //}

            // Get the list of wordmarks in the directory
            string[] allFiles = SobekCM_File_Utilities.GetFiles(wordmarkDirectory, "*.jpg|*.jpeg|*.png|*.gif|*.bmp");
            loweredFiles = allFiles.Select(ThisFileName => new FileInfo(ThisFileName)).Select(ThisFileInfo => ThisFileInfo.Name.ToLower()).ToList();
            loweredFiles.Sort();

            // Get the list of all assigned wordmark files
            foreach (Wordmark_Icon thisWordmark in wordmarks.Values)
            {
                if (loweredFiles.Contains(thisWordmark.Image_FileName.ToLower()))
                {
                    loweredFiles.Remove(thisWordmark.Image_FileName.ToLower());
                }
            }
        }