private void CheckPermissions(Category category, Permission perm, bool layout)
    {
        if ((bool)Session[Constants.IS_ROOT])
            return;
        if (!layout)
            LayoutName = null;

        if (category == null)
        {
            throw new Unauthorized("Null category!");
        }

        User user = null;
        if (Session.Contains(Constants.USER))
        {
            user = (User) Session[Constants.USER];

            IDictionary categoryAcl = category.GetPermissionsHash(user);
            if (!((bool) categoryAcl[perm]))
                throw new Unauthorized("");
        }
        else    // anonymous user
        {
            if (!category.AnonRole.Can(perm))
            {
                throw new Unauthorized("");
            }
        }
    }
 public Content(Category __category, Language __lang, bool __published, bool __f, bool __sf, DateTime __dt)
 {
     _category = __category;
     _lang = __lang;
     _published = __published;
     _frontpage = __f;
     _sectionFrontpage = __sf;
     _creationdate = __dt;
 }
 public Menu(string __Name, string __Description, string __Code, int __Ordering, 
             string __Url, Menu __Parent, Category __Category, int __Show)
 {
     _Name = __Name;
     _Description = __Description;
     _Code = __Code; 
     _Ordering = __Ordering;
     _Url = __Url;
     _Show= __Show;
     _Parent = __Parent;
     if (__Category != null)
         _CategoryId = __Category.Id;
     else
         _CategoryId = 0;
 }
    public string CategoryDescription(Category category, string lang)
    {
        if (category != null)
        {
            if ((lang != null) && (lang.Length > 0))
            {
                Language language = Language.FindByName(lang);
                CategoryTranslation ct = CategoryTranslation.FindByCategoryAndLang(category, language);

               if ((ct != null) && (ct.Translation.Length > 0))
                    return ct.Translation;
                else
                    return category.Description;
            }
            else
                return category.Description;
        }
        else
            return String.Empty;
    }
		public void MergeEmptyTemplates()
		{
		    Console.WriteLine("*** MergeEmptyTemplates");
		    CastlePortal.Template[] templates = CastlePortal.Template.FindAll();
		    Category category = new Category();
		    foreach (CastlePortal.Template template in templates)
		    {
		        category.Name = "just testing...";
		        category.Template = template;
		        Console.WriteLine("Template:" + template.Id +","+ template.Name);
		        string path = Path.Combine(TestsCommons.TEMPLATESDIR, TestsCommons.GENERALTEMPLATES);
		        path = Path.Combine(path, template.Name);
		        path += TestsCommons.EXTENSION;
		        NVelocity.Template nvtemplate = velocity.GetTemplate(path);
		        VelocityContext context = new VelocityContext();
		        context.Put(TestsCommons.TEMPLATESDIRVAR, TestsCommons.TEMPLATESDIR);
                context.Put(TestsCommons.CATEGORYVAR, category);
                StringWriter writer = new StringWriter();
                nvtemplate.Merge(context, writer);
            }
		}
 public new static Menu FindByCategory(Category c)
 {
     Menu m = null;
     do 
     {
         if ( c == null ) break;
         m = FindByCategoryId(c.Id);
         c = c.Parent;
     } while (m == null);
     return m;
 }
    public static CategoryTranslation[] FindByCategory(Category category)
    {
        CategoryTranslation[] translations = (CategoryTranslation[]) ActiveRecordBase.FindAll( typeof(CategoryTranslation),
                               Expression.Eq("Category", category));
        if ((translations != null) && (translations.Length > 0))
            return translations;
        else
            return null;
        
				/*SimpleQuery q = new SimpleQuery(typeof(CategoryTranslation), @"
            from CategoryTranslation T
            where T.Category = ?", category);

        return (CategoryTranslation[]) ExecuteQuery(q);
				*/
    }
    private void SavePortalCategory(int id, string name, string desc, 
                              string info, int ownerId, int parentId, 
                              int tempId, int roleId, string aclString)
    {
        Category category, parentCategory;
        if (parentId < 0)
        {
            parentCategory = null;
        }
        else
        {
            parentCategory = Category.Find(parentId);
        }
        if (id != 0)
        {
            category = Category.Find (id);
            CheckPermissions(category, Permission.Modify);
        }
        else
        {
            if (parentId > 0)
            {
                CheckPermissions(parentCategory, Permission.Create);
            }
            category = new Category();
        }
        User sessionUser = (User) Session[Constants.USER];
        category.Name = name;
        category.Description = desc;
        category.Information = info;
        if (ownerId > 0)
        {
            User tmpUser = User.Find(ownerId);
            if (tmpUser != null)
            {
                category.Owner = tmpUser;
            }   
        }
        else
        {
            if (sessionUser != null)
            {
                category.Owner = sessionUser;
            }
        }
        category.Parent = parentCategory; 
        if (tempId > 0)
        {
            Template tmpTemplate = Template.Find(tempId);
            if (tmpTemplate != null)
            {
                category.Template = tmpTemplate;
            }
        }
        else
        {
            category.Template = Template.GetDefault();
        }
        category.AnonRole = null;
        if (roleId > 0)
        {
            Role tmpRole = Role.Find(roleId);
            if (tmpRole != null)
            {
                category.AnonRole = tmpRole;
            }
        }
        //string aclString = (string) Request.Form["af[]"];
        //ArrayList aux = GetAclsFromFormattedString(aFields);
        if ((aclString != null) && (aclString.Length > 0))
        {
            category.AclSet = new HashedSet();
            string[] acls = aclString.Split(',');
            if (acls != null)
            {
                foreach (string i in acls)
                {
                    Acl acl = Acl.Find(int.Parse(i));
                    if (acl != null)
                    {
                        category.AclSet.Add(acl);
                    }
                }
            }
        }
        else
        {
            Group tempGroup = Group.FindByExactName(
                                  config.GetValue(Constants.ADMIN_GROUP));
            Role tempRole = Role.FindByName(config.GetValue(Constants.ALL_PRIVILEDGES));
            category.AclSet = new HashedSet();
            category.AclSet.Add(Acl.FindByGroupRole (tempGroup.Id, tempRole.Id));
        }

        if (id != 0)
        {
            category.Save();
        }
        else
        {
            category.Create();
            id = category.Id;
#if CACHE
            category.Parent.Children.Add(category);
            category.Parent.Save();
#endif
        }
    }
	public string BuildTreeMapaWeb (string givenMenu, Category currentCategory, string currentLanguage, string styleClass)
	{
		Menu menu = new Menu("", "", "showAllChilds", 0, "", null, null, 0);

      User user = (User) Controller.Context.Session[Constants.USER];
		Tree mw = new Tree (givenMenu, currentCategory, menu, user);

		return mw.BuildTree(currentLanguage, 999, styleClass);
	}
		public TreeTable (string menuName, Category currentCategory, Menu actualMenu, User user) {
			_givenMenu = Menu.FindByName (menuName);
			_currentCategory = currentCategory;
			_actualMenu = actualMenu;
			_user = user;
		}
		public TreeTable (Menu givenMenu, Category currentCategory, Menu actualMenu, User user) {
			_givenMenu = givenMenu;
			_currentCategory = currentCategory;
			_actualMenu = actualMenu;
			_user = user;
		}
		public TreeLeftWithVinyetas (Menu givenMenu, Category currentCategory, Menu actualMenu, User user) {
			_givenMenu = givenMenu;
			_currentCategory = currentCategory;
			_actualMenu = actualMenu;
			_user = user;
		}
		protected string GetDescription (Category category)
		{
			CategoryTranslation ct = CategoryTranslation.FindByCategoryAndLang(category, Language.FindByName(this.language));
			string description;

			if (ct != null)
				description = ct.Translation;
			else
				description = category.Description;

			return description;
		}
 public static CategoryTranslation FindByCategoryAndLang(Category category, Language lang)
 {
     CategoryTranslation[] translations = (CategoryTranslation[]) ActiveRecordBase.FindAll( typeof(CategoryTranslation),
                            Expression.Eq("Category", category), Expression.Eq("Lang", lang));
     if ((translations != null) && (translations.Length > 0))
         return translations[0];
     else
         return null;
 }
 public CategoryTranslation(Language lang, Category category, string translation)
 {
     _lang = lang;
     _category = category;
     _translation = translation;
 }
    private static string ReadContent(XmlNode node, Category c)
    {
        string  keys = NodeGetString(node, "keys");
        string  vals = NodeGetString(node, "vals");

        string[] colname = keys.Split(',');
        string[] namedescr = vals.Split(',');

        int l = colname.Length;

        Field [] f = new Field[l];
        for (int i=0; i<l; i++)
            f[i] = Field.GetByName(colname[i]);

        Content r = new Content(c);
        r.Save();

        for (int i=0; i<l; i++)
        {
            DataModel d = new DataModel(r, f[i], namedescr[i]);
            d.Save();
        }

        return null;

    }
    private static string ReadCategory(XmlNode node, Category parent)
    {
        if (node.Name == "Category")
        {
            string name = NodeGetString(node, "name");
            string visiblename = NodeGetString(node, "visiblename");
            string code = NodeGetString(node, "code");
//            Category parent = (Category) NodeGetObject(node, "parentcode", categories);
//            if (parent == null)
//                parent = (Category) NodeGetObject(node, "category", categories);
            Template t = (Template) NodeGetObject(node, "template", templates);
            Role r = (Role) NodeGetObject(node, "role", roles);
            //	string ayuda = NodeGetString(node, "ayuda");

            Category c = new Category ();
            if (name != "" && visiblename == "")
                visiblename = name;
            if (name == "" && visiblename != "")
                name = visiblename;
            c.Name = name;
            c.Description = visiblename;
            c.Code = code;
            if (parent != null)
                c.Parent = parent;
            c.Template = t;
            c.AnonRole = r;
            //c.Information = ayuda;
            c.Save();

            System.Console.WriteLine ("Categoria: "+ name);
            c.AclSet = NodeGetObjectSet(node, "Acl", acls);

            c.Save();
            categories[name] = c;
            if (categories[code] == null)
                categories[code] = c;
            else
                System.Console.WriteLine("Hay otra categoría con el mismo CODE ({0})", c.Description);

            foreach (XmlNode n in node.ChildNodes)
            {
                if (n.Name == "Category")
                    ReadCategory(n, c);
                else
                {
                    if (n.Name == "Content")
                        ReadContent(n, c);
                }
            }
        }
        return null;
    }
	public string MakeMenu(string givenMenu, Category currentCategory, string currentLanguage, string styleClass)
	{
		Menu menu = new Menu(); //("", "", "", 0, "", null, null, 0);

      User user = (User) Controller.Context.Session[Constants.USER];
		Tree mw = new Tree (givenMenu, currentCategory, menu, user);

		return mw.BuildTree(currentLanguage, 1, styleClass);
	}
		public void PopulateAllTemplates()
		{
		    Console.WriteLine("*** PopulateAllTemplates");
		    CastlePortal.Template[] templates = CastlePortal.Template.FindAll();
		    foreach (CastlePortal.Template template in templates)
		    {
		        Category category = new Category();
		        category.Name = "just testing...";
		        category.Template = template;
		        //category.Save();
		        Content content = new Content();
                content.Category = category;
                //content.Save();
		        category.ContentList = new System.Collections.ArrayList();
		        DataModel data = null;
		        if (template.Fields.Count > 0)
		        {
		            //Console.WriteLine("total fields= :" + template.Fields.Count);
		            foreach(CastlePortal.FieldTemplate fieldTemplate in template.Fields)
		            {
		                //Console.WriteLine("FIELD =" + fieldTemplate.Field.Name);
		                string name = fieldTemplate.Field.Name;
		                if ((name != "file") && (name != "image"))
		                {
		                    data = new DataModel(content, fieldTemplate.Field, "just a test field");
		                    content.DataHash[fieldTemplate.Field.Name] = data;
		                }
		                //data.Save();
		            }
		        }
		        category.ContentList.Add(content);
		        Console.WriteLine("Template:" + template.Id +","+ template.Name);
		        string path = Path.Combine(TestsCommons.TEMPLATESDIR, TestsCommons.GENERALTEMPLATES);
		        path = Path.Combine(path, template.Name);
		        path += TestsCommons.EXTENSION;
		        NVelocity.Template nvtemplate = velocity.GetTemplate(path);
		        VelocityContext context = new VelocityContext();
		        context.Put(TestsCommons.TEMPLATESDIRVAR, TestsCommons.TEMPLATESDIR);
                context.Put(TestsCommons.CATEGORYVAR, category);
                StringWriter writer = new StringWriter();
                nvtemplate.Merge(context, writer);
                if (data != null)
                {
                    //data.Delete();
                }
                //content.Delete();
                //category.Delete();
            }
		}
	public string BuildTreeLeftWithVinyetas (string givenMenu, Menu actualMenu, Category currentCategory, int depth_level, string currentLanguage, string styleClass)
	{
      User user = (User) Controller.Context.Session[Constants.USER];
		TreeLeftWithVinyetas wv = new TreeLeftWithVinyetas (givenMenu, currentCategory, actualMenu, user);

		return wv.BuildTree(currentLanguage, depth_level, styleClass);
	}
 public void ViewCategory(Category category)
 {
     CheckPermissions(category, Permission.Read);
     PropertyBag[Constants.MENU]  = Menu.FindByCategory(category);
     PropertyBag[Constants.CATEGORY]  = category;
 }
 public static Content[] GetCategoryContents (Category c)
 {
     return (Content[]) ActiveRecordBase.FindAll(
                typeof(Content),
                Expression.Eq("Category", c )
            );
 }
 public Content (Category category)
 {
     _category = category;
     _creationdate = System.DateTime.Now;
 }
 public static CategoryTranslation FindByCategoryAndLang(Category category, string lang)
 {
     return null;
 }