File: var.rb

package info (click to toggle)
ruby-wikicloth 0.8.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, stretch
  • size: 588 kB
  • ctags: 278
  • sloc: ruby: 2,548; makefile: 14
file content (307 lines) | stat: -rw-r--r-- 9,349 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
require 'expression_parser'
require 'digest/md5'
require 'uri'

module WikiCloth

class WikiBuffer::Var < WikiBuffer

  def initialize(data="",options={})
    super(data,options)
    self.buffer_type = "var"
    @in_quotes = false
    @tag_start = true
    @tag_size = 2
    @close_size = 2
    @fname = nil
  end

  def tag_size
    @tag_size
  end

  def tag_size=(val)
    @tag_size = val
  end

  def skip_links?
    false
  end

  def skip_html?
    false
  end

  def tag_start
    @tag_start
  end

  def tag_start=(val)
    @tag_start = val
  end

  def function_name
    @fname.nil? ? nil : @fname.strip
  end

  def to_html
    return "" if will_not_be_rendered

    if self.is_function?
      if Extension.function_exists?(function_name)
        return Extension.functions[function_name][:klass].new(@options).instance_exec( params.collect { |p| p.strip }, &Extension.functions[function_name][:block] ).to_s
      end
      ret = default_functions(function_name,params.collect { |p| p.strip })
      ret ||= @options[:link_handler].function(function_name, params.collect { |p| p.strip })
      ret.to_s
    elsif self.is_param?
      ret = nil
      @options[:buffer].buffers.reverse.each do |b|
        ret = b.get_param(params[0],params[1]) if b.instance_of?(WikiBuffer::HTMLElement) && b.element_name == "template"
        break unless ret.nil?
      end
      ret.to_s
    else
      # put template at beginning of buffer
      template_stack = @options[:buffer].buffers.collect { |b| b.get_param("__name") if b.instance_of?(WikiBuffer::HTMLElement) && 
        b.element_name == "template" }.compact
      if template_stack.last == params[0]
        debug_tree = @options[:buffer].buffers.collect { |b| b.debug }.join("-->")
        "<span class=\"error\">#{I18n.t('template loop detected', :tree => debug_tree)}</span>"
      else
        key = params[0].to_s.strip
        key_options = params[1..-1].collect { |p| p.is_a?(Hash) ? { :name => p[:name].strip, :value => p[:value].strip } : p.strip }
        key_options ||= []
        key_digest = Digest::MD5.hexdigest(key_options.to_a.sort {|x,y| (x.is_a?(Hash) ? x[:name] : x) <=> (y.is_a?(Hash) ? y[:name] : y) }.inspect)

        return @options[:params][key] if @options[:params].has_key?(key)
        # if we have a valid cache fragment use it
        return @options[:cache][key][key_digest] unless @options[:cache].nil? || @options[:cache][key].nil? || @options[:cache][key][key_digest].nil?

        ret = @options[:link_handler].include_resource(key,key_options).to_s

        ret.gsub!(/<!--(.|\s)*?-->/,"")
        count = 0
        tag_attr = key_options.collect { |p|
          if p.instance_of?(Hash)
            "#{p[:name]}=\"#{p[:value].gsub(/"/,'&quot;')}\""
          else
            count += 1
            "#{count}=\"#{p.gsub(/"/,'&quot;')}\""
          end
        }.join(" ")

        self.data = ret.blank? ? "" : "<template __name=\"#{key}\" __hash=\"#{key_digest}\" #{tag_attr}>#{ret}</template>"
        ""
      end
    end
  end

  def will_not_be_rendered
    @options[:buffer].buffers.reverse.each do |buffer|
      if buffer.instance_of?(WikiBuffer::Var) && buffer.is_function?
        return true if buffer.function_name == "#if" && buffer.params.size == 2 && buffer.params[0].strip.blank?
        return true if buffer.function_name == "#if" && buffer.params.size == 3 && !buffer.params[0].strip.blank?
      end
    end
    false
  end

  def default_functions(name,params)
    case name
    when "#if"
      params.first.blank? ? params[2] : params[1]
    when "#switch"
      match = params.first
      default = nil
      for p in params[1..-1]
        temp = p.split("=")
        if p !~ /=/ && temp.length == 1 && p == params.last
          return p
        elsif temp.instance_of?(Array) && temp.length > 0
          test = temp.first.strip
          default = temp[1..-1].join("=").strip if test == "#default"
          return temp[1..-1].join("=").strip if test == match || (test == "none" && match.blank?)
        end
      end
      default.nil? ? "" : default
    when "#expr"
      begin
        ExpressionParser::Parser.new.parse(params.first)
      rescue RuntimeError
        I18n.t('expression error', :error => $!)
      end
    when "#ifexpr"
      val = false
      begin
        val = ExpressionParser::Parser.new.parse(params.first)
      rescue RuntimeError
      end
      if val
        params[1]
      else
        params[2]
      end
    when "#ifeq"
      if params[0] =~ /^[0-9A-Fa-f]+$/ && params[1] =~ /^[0-9A-Fa-f]+$/
        params[0].to_i == params[1].to_i ? params[2] : params[3]
      else
        params[0] == params[1] ? params[2] : params[3]
      end
    when "#len"
      params.first.length
    when "#sub"
      params.first[params[1].to_i,params[2].to_i]
    when "#pad"
      case params[3]
      when "right"
        params[0].ljust(params[1].to_i,params[2])
      when "center"
        params[0].center(params[1].to_i,params[2])
      else
        params[0].rjust(params[1].to_i,params[2])
      end
    when "#iferror"
      params.first =~ /error/ ? params[1] : params[2]
    when "#capture"
      @options[:params][params.first] = params[1]
      ""
    when "urlencode"
      URI.escape(params.first, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
    when "lc"
      params.first.downcase
    when "uc"
      params.first.upcase
    when "ucfirst"
      params.first.capitalize
    when "lcfirst"
      params.first[0,1].downcase + params.first[1..-1]
    when "anchorencode"
      params.first.gsub(/\s+/,'_')
    when "plural"
      begin
        expr_value = ExpressionParser::Parser.new.parse(params.first)
        expr_value.to_i == 1 ? params[1] : params[2]
      rescue RuntimeError
        I18n.t('expression error', :error => $!)
      end
    when "ns"
      values = {
        "" => "", "0" => "",
        "1" => localise_ns("Talk"), "talk" => localise_ns("Talk"),
        "6" => localise_ns("File"), "file" => localise_ns("File"), "image" => localise_ns("File"),
        "10" => localise_ns("Template"), "template" => localise_ns("Template"),
        "14" => localise_ns("Category"), "category" => localise_ns("Category"),
        "-1" => localise_ns("Special"), "special" => localise_ns("Special"),
        "12" => localise_ns("Help"), "help" => localise_ns("Help"),
        "-2" => localise_ns("Media"), "media" => localise_ns("Media") }

      values[localise_ns(params.first,:en).gsub(/\s+/,'_').downcase]
    when "#language"
      WikiNamespaces.language_name(params.first)
    when "#tag"
      return "" if params.empty?
      elem = Builder::XmlMarkup.new
      return elem.tag!(params.first) if params.length == 1
      return elem.tag!(params.first) { |e| e << params.last } if params.length == 2
      tag_attrs = {}
      params[1..-2].each do |attr|
        tag_attrs[$1] = $2 if attr =~ /^\s*([\w]+)\s*=\s*"(.*)"\s*$/
      end
      elem.tag!(params.first,tag_attrs) { |e| e << params.last }
    when "debug"
      ret = nil
      case params.first
      when "param"
        @options[:buffer].buffers.reverse.each do |b|
          if b.instance_of?(WikiBuffer::HTMLElement) && b.element_name == "template"
             ret = b.get_param(params[1])
          end
        end
        ret
      when "buffer"
        ret = "<pre>"
        buffer = @options[:buffer].buffers
        buffer.each do |b|
          ret += " --- #{b.class}"
          ret += b.instance_of?(WikiBuffer::HTMLElement) ? " -- #{b.element_name}\n" : " -- #{b.data}\n"
        end
        "#{ret}</pre>"
      end
    end
  end

  def localise_ns(name,lang=nil)
    WikiNamespaces.localise_ns(name,lang)
  end

  def is_param?
    @tag_size == 3 ? true : false
  end

  def is_function?
    self.function_name.nil? || self.function_name.blank? ? false : true
  end

  protected
  def function_name=(val)
    @fname = val
  end

  def new_char()
    case
    when current_char == '|' && @in_quotes == false
      self.current_param = self.data
      self.data = ""
      self.params << ""

    # Start of either a function or a namespace change
    when current_char == ':' && @in_quotes == false && self.params.size <= 1
      if self.data.blank? || self.data.include?(":")
	self.data << current_char
      else
        self.function_name = self.data
        self.data = ""
      end

    # Dealing with variable names within functions
    # and variables
    when current_char == '=' && @in_quotes == false && !is_function?
      self.current_param = self.data
      self.data = ""
      self.name_current_param()

    # End of a template, variable, or function
    when current_char == '}' && previous_char == '}'
      if @close_size == @tag_size
        self.data.chop!
        self.current_param = self.data
        self.data = ""
        return false
      else
        @close_size += 1
      end

    else
      self.data << current_char
      if @tag_start
        # FIXME: template params and templates colliding
        if @tag_size > 3
          if @tag_size == 5
            @options[:buffer].buffers << WikiBuffer::Var.new(self.data,@options)
            @options[:buffer].buffers[-1].tag_start = false
            self.data = ""
            @tag_size = 3
            return true
          end
        end
        @tag_start = false
      end
    end

    return true
  end

end

end