<commit_before>module Zena
  module Use
    module Zafu
      module Common

        # Return a template's content from an url. If the url does not start with a '/', we try by replacing the
        # first element with the current skin_name and if it does not work, we try with the full url. If the url
        # start with a '/' we use the full url directly.
        # tested in MainControllerTest
        def get_template_text(opts)
          return nil unless res = find_document_for_template(opts)
          doc, url = *res
          # TODO: could we use this for caching or will we loose dynamic context based loading ?
          self.expire_with_nodes[url] = doc
          text = dev_mode? ? doc.version.text : doc.version(true).text
          return text, url, doc
        end

        # Return the zen_path ('/en/image34.png') for an asset given its name ('img/footer.png').
        # The rule is not the same whether we are rendering a template and find <img/> <link rel='stylesheet'/> tags
        # or if we are parsing assets in a CSS file.
        def template_url_for_asset(opts)
          src = opts[:src]
          if src =~ /\A(.*)\.(\w+)\Z/
            src, format = $1, $2
          end

          if opts[:parse_assets]
            current_folder = opts[:current_folder] || ''
            current_folder = current_folder[1..-1] if current_folder[0..0] == '/'

            if src =~ /\A(.*)_(\w+)\Z/
              # if the element was not found, maybe it was not a name with underscore but it was an image mode
              src2, mode2 = $1, $2
            end

            paths = []
            if src[0..0] == '/'
              paths << src[1..-1]
              paths << src2[1..-1] if src2
            else
              paths << (current_folder + '/' + src)
              paths << (current_folder + '/' + src2) if src2
            end

            # make sure path elements are url_names
            paths.map! do |path|
              res = []
              path.split('/').each do |e|
                if e == '..'
                  res.pop
                else
                  res << e.url_name
                end
              end
              res.join('/')
            end

            if asset = secure(Document) { Document.find_by_path(paths[0]) }
            elsif src2 && (asset = secure(Document) { Document.find_by_path(paths[1]) })
              mode = mode2
            else
              return nil
            end
          else
            if src =~ /\A(.*)_(\w+)\Z/
              src, mode = $1, $2
            end

            src2 = opts[:src].split('/').map {|s| s.url_name!}.join('/')

            unless res = find_document_for_template(opts)
              # '_...' did not mean mode but was an old name.
              mode = nil
              return nil unless res = find_document_for_template(opts.merge(:src => src2))
            end

            asset, url = *res
            self.renamed_assets[url] = asset
          end

          data_path(asset, :mode => mode)
        end



        # TODO: test
        def save_erb_to_url(template, template_url)
          path = fullpath_from_template_url(template_url)
          path += ".erb" unless path =~ /\.\w+\Z/
          FileUtils.mkpath(File.dirname(path)) unless File.exists?(File.dirname(path))
          File.open(path, "wb") { |f| f.syswrite(template) }
          ""
        end

        # Return the full path from a template's url.
        # The expected url is of the form '/skin/Klass-mode/partial'
        def fullpath_from_template_url(template_url=params[:t_url])
          "#{SITES_ROOT}#{template_path_from_template_url(template_url)}"
        end

        # Return the template path without '.erb' extension in case we need to append '_form'
        # from a template's url. The expected url is of the form '/skin/Klass-mode/partial'
        def template_path_from_template_url(template_url=params[:t_url])
          if template_url =~ /\A\.|[^\w\+\._\-\/]/
            raise Zena::AccessViolation.new("'template_url' contains illegal characters : #{template_url.inspect}")
          end

          template_url = template_url[1..-1].split('/')
          path = "/#{template_url[0]}/#{template_url[1]}/#{dev_mode? ? "dev_#{lang}" : lang}/#{template_url[2..-1].join('/')}"

          "/#{current_site.host}/zafu#{path}"
        end

        # Make sure some vital templates never get broken
        def valid_template?(content, opts)
          mode = opts[:mode]
          case mode
          when '+login'
            content =~ %r{<form[^>]* action\s*=\s*./user_session}
          when '+adminLayout'
            content =~ %r{<%= content_for_layout %>} && %r{show_link(:admin_links)}
          else
            true
          end
        end

        # Default template content for a specified mode
        def default_zafu_template(mode)
          if mode =~ /\A\.|[^\w\+\._\-\/]/
            raise Zena::AccessViolation.new("'mode' contains illegal characters : #{mode.inspect}")
          end
          File.read(File.join(Zena::ROOT, 'app', 'views', 'templates', 'defaults', "#{mode}.zafu"))
        end


        # opts should contain :current_template and :src. The source is a path like 'default/Node-+index'
        # ('skin/template/path'). If the path starts with a slash, the skin_name in the path is searched first. Otherwise,
        # the current skin is searched first.
        # <r:include template='Node'/>
        #   find: #{skin_path(main_skin)}/Node<commit_msg>In Zafu, use Session controller, instead of UserSession.<commit_after>module Zena
  module Use
    module Zafu
      module Common

        # Return a template's content from an url. If the url does not start with a '/', we try by replacing the
        # first element with the current skin_name and if it does not work, we try with the full url. If the url
        # start with a '/' we use the full url directly.
        # tested in MainControllerTest
        def get_template_text(opts)
          return nil unless res = find_document_for_template(opts)
          doc, url = *res
          # TODO: could we use this for caching or will we loose dynamic context based loading ?
          self.expire_with_nodes[url] = doc
          text = dev_mode? ? doc.version.text : doc.version(true).text
          return text, url, doc
        end

        # Return the zen_path ('/en/image34.png') for an asset given its name ('img/footer.png').
        # The rule is not the same whether we are rendering a template and find <img/> <link rel='stylesheet'/> tags
        # or if we are parsing assets in a CSS file.
        def template_url_for_asset(opts)
          src = opts[:src]
          if src =~ /\A(.*)\.(\w+)\Z/
            src, format = $1, $2
          end

          if opts[:parse_assets]
            current_folder = opts[:current_folder] || ''
            current_folder = current_folder[1..-1] if current_folder[0..0] == '/'

            if src =~ /\A(.*)_(\w+)\Z/
              # if the element was not found, maybe it was not a name with underscore but it was an image mode
              src2, mode2 = $1, $2
            end

            paths = []
            if src[0..0] == '/'
              paths << src[1..-1]
              paths << src2[1..-1] if src2
            else
              paths << (current_folder + '/' + src)
              paths << (current_folder + '/' + src2) if src2
            end

            # make sure path elements are url_names
            paths.map! do |path|
              res = []
              path.split('/').each do |e|
                if e == '..'
                  res.pop
                else
                  res << e.url_name
                end
              end
              res.join('/')
            end

            if asset = secure(Document) { Document.find_by_path(paths[0]) }
            elsif src2 && (asset = secure(Document) { Document.find_by_path(paths[1]) })
              mode = mode2
            else
              return nil
            end
          else
            if src =~ /\A(.*)_(\w+)\Z/
              src, mode = $1, $2
            end

            src2 = opts[:src].split('/').map {|s| s.url_name!}.join('/')

            unless res = find_document_for_template(opts)
              # '_...' did not mean mode but was an old name.
              mode = nil
              return nil unless res = find_document_for_template(opts.merge(:src => src2))
            end

            asset, url = *res
            self.renamed_assets[url] = asset
          end

          data_path(asset, :mode => mode)
        end



        # TODO: test
        def save_erb_to_url(template, template_url)
          path = fullpath_from_template_url(template_url)
          path += ".erb" unless path =~ /\.\w+\Z/
          FileUtils.mkpath(File.dirname(path)) unless File.exists?(File.dirname(path))
          File.open(path, "wb") { |f| f.syswrite(template) }
          ""
        end

        # Return the full path from a template's url.
        # The expected url is of the form '/skin/Klass-mode/partial'
        def fullpath_from_template_url(template_url=params[:t_url])
          "#{SITES_ROOT}#{template_path_from_template_url(template_url)}"
        end

        # Return the template path without '.erb' extension in case we need to append '_form'
        # from a template's url. The expected url is of the form '/skin/Klass-mode/partial'
        def template_path_from_template_url(template_url=params[:t_url])
          if template_url =~ /\A\.|[^\w\+\._\-\/]/
            raise Zena::AccessViolation.new("'template_url' contains illegal characters : #{template_url.inspect}")
          end

          template_url = template_url[1..-1].split('/')
          path = "/#{template_url[0]}/#{template_url[1]}/#{dev_mode? ? "dev_#{lang}" : lang}/#{template_url[2..-1].join('/')}"

          "/#{current_site.host}/zafu#{path}"
        end

        # Make sure some vital templates never get broken
        def valid_template?(content, opts)
          #puts content
          mode = opts[:mode]
          case mode
          when '+login'
            content =~ %r{<form[^>]* action\s*=\s*./session}
          when '+adminLayout'
            content =~ %r{<%= content_for_layout %>} && %r{show_link(:admin_links)}
          else
            true
          end
        end

        # Default template content for a specified mode
        def default_zafu_template(mode)
          if mode =~ /\A\.|[^\w\+\._\-\/]/
            raise Zena::AccessViolation.new("'mode' contains illegal characters : #{mode.inspect}")
          end
          File.read(File.join(Zena::ROOT, 'app', 'views', 'templates', 'defaults', "#{mode}.zafu"))
        end


        # opts should contain :current_template and :src. The source is a path like 'default/Node-+index'
        # ('skin/template/path'). If the path starts with a slash, the skin_name in the path is searched first. Otherwise,
        # the current skin is searched first.
        # <r:include template='Node'/>
        #   find: #{skin_path(main_skin)}/Node
{'fraction_non_alphanumeric': 0.12197325623418866, 'fraction_numerical': 0.006505240332490061, 'mean_word_length': 1.7418875402526628, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4782935', 'n_tokens_mistral': 3237, 'n_tokens_neox': 3168, 'n_words': 942}