Project

General

Profile

Patch #1700 » macros.rb

My local macro.rb file with extras - Robert Shell, 2008-07-28 18:31

 
1
# redMine - project management software
2
# Copyright (C) 2006-2007  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
# 
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
# 
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

    
18
module Redmine
19
  module WikiFormatting
20
    module Macros
21
      module Definitions
22
        def exec_macro(name, obj, args)
23
          method_name = "macro_#{name}"
24
          send(method_name, obj, args) if respond_to?(method_name)
25
        end
26
      end
27
      
28
      @@available_macros = {}
29
      
30
      class << self
31
        # Called with a block to define additional macros.
32
        # Macro blocks accept 2 arguments:
33
        # * obj: the object that is rendered
34
        # * args: macro arguments
35
        # 
36
        # Plugins can use this method to define new macros:
37
        # 
38
        #   Redmine::WikiFormatting::Macros.register do
39
        #     desc "This is my macro"
40
        #     macro :my_macro do |obj, args|
41
        #       "My macro output"
42
        #     end
43
        #   end
44
        def register(&block)
45
          class_eval(&block) if block_given?
46
        end
47
        
48
        private
49
        # Defines a new macro with the given name and block.
50
        def macro(name, &block)
51
          name = name.to_sym if name.is_a?(String)
52
          @@available_macros[name] = @@desc || ''
53
          @@desc = nil
54
          raise "Can not create a macro without a block!" unless block_given?
55
          Definitions.send :define_method, "macro_#{name}".downcase, &block
56
        end
57
        
58
        # Sets description for the next macro to be defined
59
        def desc(txt)
60
          @@desc = txt
61
        end
62
      end
63
      
64
      # Builtin macros
65
      desc "Sample macro."
66
      macro :hello_world do |obj, args|
67
        "Hello world! Object: #{obj.class.name}, " + (args.empty? ? "Called with no argument." : "Arguments: #{args.join(', ')}")
68
      end
69
      
70
      desc "Displays a list of all available macros, including description if available."
71
      macro :macro_list do
72
        out = ''
73
        @@available_macros.keys.collect(&:to_s).sort.each do |macro|
74
          out << content_tag('dt', content_tag('code', macro))
75
          out << content_tag('dd', textilizable(@@available_macros[macro.to_sym]))
76
        end
77
        content_tag('dl', out)
78
      end
79
      
80
      desc "Displays a list of child pages."
81
      macro :child_pages do |obj, args|
82
        raise 'This macro applies to wiki pages only.' unless obj.is_a?(WikiContent)
83
        render_page_hierarchy(obj.page.descendants.group_by(&:parent_id), obj.page.id)
84
      end
85
      
86
      desc "Include a wiki page. Example:\n\n  !{{include(Foo)}}\n\nor to include a page of a specific project wiki:\n\n  !{{include(projectname:Foo)}}"
87
      macro :include do |obj, args|
88
        project = @project
89
        title = args.first.to_s
90
        if title =~ %r{^([^\:]+)\:(.*)$}
91
          project_identifier, title = $1, $2
92
          project = Project.find_by_identifier(project_identifier) || Project.find_by_name(project_identifier)
93
        end
94
        raise 'Unknow project' unless project && User.current.allowed_to?(:view_wiki_pages, project)
95
        raise 'No wiki for this project' unless !project.wiki.nil?
96
        page = project.wiki.find_page(title)
97
        raise "Page #{args.first} doesn't exist" unless page && page.content
98
        @included_wiki_pages ||= []
99
        raise 'Circular inclusion detected' if @included_wiki_pages.include?(page.title)
100
        @included_wiki_pages << page.title
101
        out = textilizable(page.content, :text, :attachments => page.attachments)
102
        @included_wiki_pages.pop
103
        out
104
      end
105
      
106
      #[[TitleIndex]]
107
      #
108
      #    Inserts an alphabetic list of all wiki pages into the output.
109
      #
110
      #    Accepts a prefix string as parameter: if provided, only pages with names that start with the prefix 
111
      #    are included in the resulting list. If this parameter is omitted, all pages are listed.
112
      #
113
      
114
      desc "Inserts an alphabetic list of all wiki pages into the output.  \n\n  !{{title_list(title-prefix)}}\n\n "
115
      macro :title_list do |obj, args|
116
        filter = "#{args.first}%"
117
        limit = 20 || args.second
118
        out = ''
119
        @pages = @wiki.pages.find(:all, 
120
                                  :conditions => ["#{WikiPage.table_name}.title like ?",filter],
121
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
122
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
123
        :order => 'title',
124
        :limit => limit)
125
        @pages.each do |page|
126
          out << content_tag('li',link_to(page.pretty_title, {:action => 'index',:page => page.title}))
127
        end
128
        content_tag('ul', out)
129
      end
130
      #
131
      # This generates a breadcrumb bar from a dash separated list of elements from page title
132
      # Analysis-UseCase-ManagingSamples => 3 level table of links
133
      #  
134
      #   {{#breadcrumb(title)}}
135
      #
136
      desc "split title as dash separates into also labeled links to parent pages  \n\n  !{{breadcrumb(title)}}\n\n "
137
      macro :breadcrumb do |obj, args|
138
        filter = "#{args.first}"
139
        crumbs =filter.split("-")
140
        crumbs = crumbs.each_index{|x|crumbs[x]="#{crumbs[x-1]}-#{crumbs[x]}" if x>0}.collect{|i|"'#{i}'"}
141
        @pages = @wiki.pages.find(:all, 
142
                                  :conditions => ["#{WikiPage.table_name}.title in (#{crumbs.join(',')})"],
143
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
144
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
145
        :order => 'title')
146
        out = []
147
        @pages.each do |page|
148
          text = page.title.split("-").last
149
          out << content_tag('span',link_to(WikiPage.pretty_title(text), {:action => 'index',:page => page.title}))
150
        end
151
        content_tag('p', out.join(">"),{:class=>'breadcrumb'})
152
      end
153
      #
154
      #  {{title_menu(prefix,depth,max,style)}}
155
      #  prefix for pages
156
      #  max number in menu defaults to 20
157
      #  css style to use defaults to toc
158
      #
159
      # Buils a Toc style menu out of child pages
160
      # This builds a vertial menu of items based on a prefix
161
      #
162
      #  {{title_menu(Analysis-UseCase-,10,'toc right')}}
163
      #
164
      # This would find all pages with the prefix 'title_menu(Analysis-UseCase-' and generate a toc right style menu of these
165
      # sorted by name with the prefix removed. limited to first 10 matches
166
      #
167
      desc "Inserts an alphabetic menu of all wiki pages into the output. \n\n  !{{title_menu(title-prefix,level,max,css-sytle)}}\n\n "
168
      macro :title_menu do |obj, args|
169
        filter = "#{args.first}"
170
        top = filter.count("-")
171
        depth=   args[1].to_i+1
172
        limit = args[2]||50
173
        style = args[3]||'toc'
174
        out = ''
175
        @pages = @wiki.pages.find(:all, 
176
                                  :conditions => ["#{WikiPage.table_name}.title like ?","#{filter}%"],
177
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
178
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
179
        :order => 'title')
180
        
181
        @pages.each do |page|
182
          elements = page.title.split("-")
183
          level = elements.size - top 
184
          level = elements.size - top -1
185
          text = (level>0 ? "-"*level : '')+ " "+ elements.last 
186
          text = text.gsub(/\_/," ")
187
          text = text.gsub(/([a-z])([A-Z])/,'\1 \2')
188
          unless level> depth
189
             out << content_tag('li',link_to(text, {:action => 'index',:page => page.title}))
190
          end
191
        end
192
        content_tag('ul', out,{:class=>style})
193
      end
194
      #
195
      #
196
      #  {{title_bar(prefix,depth,max,style)}}
197
      #  prefix for pages
198
      #  max number in menu defaults to 20
199
      #  css style to use defaults to toc
200
      #
201
      # Buils a single row table links to child pages
202
      #
203
      #  {{title_bar(Analysis-UseCase-,1exit,10,'table')}}
204
      #
205
      # This would find all pages with the prefix 'title_menu(Analysis-UseCase-' and generate a toc right style menu of these
206
      # sorted by name with the prefix removed. limited to first 10 matches
207
      #
208
      desc "Inserts an alphabetic menu of all wiki pages into the output.\n\n  !{{title_bar(title-prefix,level,max,css-sytle)}}\n\n "
209
      macro :title_bar do |obj, args|
210
        filter = "#{args.first}"
211
        top = filter.count("-")
212
        depth=   args[1].to_i+1
213
        limit =  args[2]||50
214
        style =  args[3]||'menu_bar'
215
        @pages = @wiki.pages.find(:all, 
216
                                  :conditions => ["#{WikiPage.table_name}.title like ?","#{filter}%"],
217
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
218
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
219
        :order => 'title',
220
        :limit => limit)
221
        cell = ""
222
        out = ''
223
        @pages.each do |page|
224
          elements = page.title.split("-")
225
          level = elements.size - top -1
226
          text = (level>0 ? "-"*level : '')+ " "+ elements.last 
227
          text = text.gsub(/\_/," ")
228
          text = text.gsub(/([a-z])([A-Z])/,'\1 \2')
229
          if level <= depth
230
             if level>= top 
231
               cell << content_tag('li',link_to(text, {:action => 'index',:page => page.title})) 
232
             else
233
               out << content_tag("td",content_tag("ul",cell,{:class=>style})) if cell.size>0
234
               cell = content_tag('li',link_to(text, {:action => 'index',:page => page.title})) 
235
             end
236
          end
237
        end
238
        out << content_tag("td",content_tag("ul",cell,{:class=>style})) if cell.size>0
239
        content_tag('table', content_tag("tr",out),{:class=>style})
240
      end
241

    
242
      
243
      desc "title_index  boxed up titles by letter to create a glossary or index \n\n  !{{title_menu(title-prefix,columns,max)}}\n\n "
244
      macro :title_index do |obj, args|
245
        filter = "#{args.first}"
246
        top = filter.count("-")
247
        columns =  args[1].to_i||4
248
        limit =  args[2]||1000
249
        style =  args[3]||'menu_bar'
250
        @pages = @wiki.pages.find(:all, 
251
                                  :conditions => ["#{WikiPage.table_name}.title like ?","#{filter}%"],
252
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
253
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
254
        :order => 'title',
255
        :limit => limit)
256
        cell = {}
257
        out = ''
258
        @pages.each do |page|
259
          text = page.title 
260
          text[filter]='' if text[filter] 
261
          letter =text.first
262
          old ||= letter
263
          text = text.gsub(/\_/," ")
264
          text = text.gsub(/([a-z])([A-Z])/,'\1 \2')
265
          cell[letter] ||= ""
266
          cell[letter] << content_tag('li',link_to(text, {:action => 'index',:page => page.title})) 
267
        end
268
        row =""
269
        n=0
270
        for key in cell.keys.sort do
271
          row << content_tag("td",content_tag("strong",key) << content_tag("ul",cell[key],{:class=>style}))
272
          n+=1
273
          if n>=columns
274
            out << content_tag("tr",row)
275
            row =""
276
            n=0
277
          end
278
        end  
279
        out << content_tag("tr",row) if row.size>0
280
        content_tag('table', content_tag("tr",out),{:class=>style})
281
      end
282

    
283
      #[[RecentChanges]] 
284
      #
285
      #    Lists all pages that have recently been modified, grouping them by the day they were last modified.
286
      #
287
      #    This macro accepts two parameters. The first is a prefix string: if provided, only pages with
288
      #     names that start with the prefix are included in the resulting list. If this parameter 
289
      #     is omitted, all pages are listed.
290
      #
291
      
292
      desc " Lists all pages that have recently been modified, grouping them by the day they were last modified"
293
      macro :recent_changes do |obj, args|
294
        filter = "#{args.first}%"
295
        limit = 5||args.second
296
        out = ''
297
        @pages = @wiki.pages.find(:all, 
298
                                  :conditions => ["#{WikiPage.table_name}.title like ?",filter],
299
        :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
300
        :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
301
        :order => "#{WikiContent.table_name}.updated_on desc",
302
        :limit => limit)
303
        @pages.each do |page|
304
          out << content_tag('li',link_to(page.pretty_title, {:action => 'index',:page => page.title}))
305
        end
306
        content_tag('ul', out)
307
      end
308
      
309
      #
310
      # Issues Lists
311
      #
312
      #
313
      desc "Lists Issues. Example:\n\n  !{{issue_list(tracker,category,status,user,max) }}\n\n"
314
      macro :issue_list do |obj, args|
315
        
316
        conditions=[]
317
        conditions << " trackers.name like '#{args[1]}%'"         unless args[0].blank?
318
        conditions << " issue_categories.name like '#{args[1]}%'" unless args[1].blank? 
319
        conditions << " issue_statuses.name like '#{args[2]}%'"   unless args[2].blank?
320
        conditions << " users.login like '#{args[3]}%'"   unless args[3].blank?
321
        limit = 10||args[3]
322
        out = ''
323
        @issues = @project.issues.find(:all, 
324
                                       :conditions => conditions.join(" and "),
325
        :include=>[:status,:tracker,:assigned_to,:category],:order=>'issues.id desc',:limit => limit)
326
        @issues.each do |issue|
327
          item = "<b>#{issue.id}</b> [#{issue.status.name}/#{issue.assigned_to.login}]  #{issue.subject}"
328
          out << content_tag('li',link_to(item, {:controller=>'issues',:action => 'show',:id => issue.id}))
329
        end
330
        content_tag('ul', out)
331
      end
332
      #
333
      # Free format issues query with name=value based parameter to filters to apply 
334
      #
335
      #
336
      desc "Query Issues. Example:\n\n  !{{issue_query(tracker=dddd&category=dsdd&status=dddd&owner=ssss&max=10) }}\n\n"
337
      macro :issue_query do |obj, args|
338
        params ={}
339
        args.collect do |v| 
340
          key,value = v.split("=")
341
          params[key] = value
342
        end
343
        conditions=[]
344
        conditions << " trackers.name like '#{params['tracker']}%'"         unless params['tracker'].blank?
345
        conditions << " issue_categories.name like '#{params['category']}%'"         unless params['category'].blank? 
346
        conditions << " issue_statuses.name like '#{params['status']}%'"   unless params['status'].blank?
347
        conditions << " users.login like '#params['owner']}%'"     unless params['owner'].blank?
348
        if params[:order]
349
          order =  params[:order] 
350
        else
351
          order = 'issues.id desc'
352
        end
353
        limit = 10 || params['max']
354
        out = ''
355
        @issues = @project.issues.find(:all, 
356
                                       :conditions => conditions.join(" and "),
357
        :order => order,
358
        :include=>[:status,:tracker,:assigned_to,:category],
359
        :limit => limit)
360
        
361
        @issues.each do |issue|
362
          item = "<b>#{issue.id}</b> [#{issue.status.name}/#{issue.assigned_to.login}]  #{issue.subject}"
363
          out << content_tag('li',link_to(item, {:controller=>'issues',:action => 'show',:id => issue.id}))
364
        end
365
        content_tag('ul', out)
366
      end
367
      #
368
      # Simple metre
369
      #
370
      desc "Count Issues. Example:\n  !{{issue_count(tracker=xxx,category=xxx,status=xxxx) }}\n\n "
371
      macro :issue_count do |obj, args|
372
        params ={}
373
        args.collect do |v| 
374
          key,value = v.split("=")
375
          params[key] = value
376
        end
377
        conditions=[]
378
        conditions << " trackers.name like '#{params['tracker']}%'"         unless params['tracker'].blank?
379
        conditions << " issue_categories.name like '#{params['category']}%'"         unless params['category'].blank? 
380
        conditions << " issue_statuses.name like '#{params['status']}%'"   unless params['status'].blank?
381
        conditions << " users.login like '#params['owner']}%'"     unless params['owner'].blank?
382
        
383
        num = @project.issues.count(
384
                                    :conditions => conditions.join(" and "),
385
        :include=>[:status,:tracker,:assigned_to,:category])             
386
        content_tag('b', "#{num}")
387
      end
388
      
389
    end
390
  end
391
end
(2-2/3)