Revision 912:5e80956cc792 .svn/pristine/05

View differences:

.svn/pristine/05/05366a1767d0cebdb112d7b0a839d8704040e98a.svn-base
1
#!/usr/bin/env ruby
2
#
3
# You may specify the path to the FastCGI crash log (a log of unhandled
4
# exceptions which forced the FastCGI instance to exit, great for debugging)
5
# and the number of requests to process before running garbage collection.
6
#
7
# By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log
8
# and the GC period is nil (turned off).  A reasonable number of requests
9
# could range from 10-100 depending on the memory footprint of your app.
10
#
11
# Example:
12
#   # Default log path, normal GC behavior.
13
#   RailsFCGIHandler.process!
14
#
15
#   # Default log path, 50 requests between GC.
16
#   RailsFCGIHandler.process! nil, 50
17
#
18
#   # Custom log path, normal GC behavior.
19
#   RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log'
20
#
21
require File.dirname(__FILE__) + "/../config/environment"
22
require 'fcgi_handler'
23

  
24
RailsFCGIHandler.process!
.svn/pristine/05/053c71b830593b5a759e13f9676269b7c9bf4645.svn-base
1
# Redmine - project management software
2
# Copyright (C) 2006-2011  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
class IssueCategory < ActiveRecord::Base
19
  belongs_to :project
20
  belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
21
  has_many :issues, :foreign_key => 'category_id', :dependent => :nullify
22

  
23
  validates_presence_of :name
24
  validates_uniqueness_of :name, :scope => [:project_id]
25
  validates_length_of :name, :maximum => 30
26
  
27
  attr_protected :project_id
28

  
29
  named_scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
30

  
31
  alias :destroy_without_reassign :destroy
32

  
33
  # Destroy the category
34
  # If a category is specified, issues are reassigned to this category
35
  def destroy(reassign_to = nil)
36
    if reassign_to && reassign_to.is_a?(IssueCategory) && reassign_to.project == self.project
37
      Issue.update_all("category_id = #{reassign_to.id}", "category_id = #{id}")
38
    end
39
    destroy_without_reassign
40
  end
41

  
42
  def <=>(category)
43
    name <=> category.name
44
  end
45

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

  
20
module AccountHelper
21
end
.svn/pristine/05/058be0b3a53e81bfbd2f18f23f7014355fe7cd0a.svn-base
1
# Redmine - project management software
2
# Copyright (C) 2006-2011  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
require File.expand_path('../../test_helper', __FILE__)
19

  
20
class MemberTest < ActiveSupport::TestCase
21
  fixtures :projects, :trackers, :issue_statuses, :issues,
22
           :enumerations, :users, :issue_categories,
23
           :projects_trackers,
24
           :roles,
25
           :member_roles,
26
           :members,
27
           :enabled_modules,
28
           :workflows,
29
           :groups_users,
30
           :watchers,
31
           :journals, :journal_details,
32
           :messages,
33
           :wikis, :wiki_pages, :wiki_contents, :wiki_content_versions,
34
           :boards
35

  
36
  def setup
37
    @jsmith = Member.find(1)
38
  end
39

  
40
  def test_create
41
    member = Member.new(:project_id => 1, :user_id => 4, :role_ids => [1, 2])
42
    assert member.save
43
    member.reload
44

  
45
    assert_equal 2, member.roles.size
46
    assert_equal Role.find(1), member.roles.sort.first
47
  end
48

  
49
  def test_update
50
    assert_equal "eCookbook", @jsmith.project.name
51
    assert_equal "Manager", @jsmith.roles.first.name
52
    assert_equal "jsmith", @jsmith.user.login
53

  
54
    @jsmith.mail_notification = !@jsmith.mail_notification
55
    assert @jsmith.save
56
  end
57

  
58
  def test_update_roles
59
    assert_equal 1, @jsmith.roles.size
60
    @jsmith.role_ids = [1, 2]
61
    assert @jsmith.save
62
    assert_equal 2, @jsmith.reload.roles.size
63
  end
64

  
65
  def test_validate
66
    member = Member.new(:project_id => 1, :user_id => 2, :role_ids => [2])
67
    # same use can't have more than one membership for a project
68
    assert !member.save
69

  
70
    member = Member.new(:project_id => 1, :user_id => 2, :role_ids => [])
71
    # must have one role at least
72
    assert !member.save
73
  end
74

  
75
  def test_destroy
76
    assert_difference 'Member.count', -1 do
77
      assert_difference 'MemberRole.count', -1 do
78
        @jsmith.destroy
79
      end
80
    end
81

  
82
    assert_raise(ActiveRecord::RecordNotFound) { Member.find(@jsmith.id) }
83
  end
84

  
85
  context "removing permissions" do
86
    setup do
87
      Watcher.delete_all("user_id = 9")
88
      user = User.find(9)
89
      # public
90
      Watcher.create!(:watchable => Issue.find(1), :user => user)
91
      # private
92
      Watcher.create!(:watchable => Issue.find(4), :user => user)
93
      Watcher.create!(:watchable => Message.find(7), :user => user)
94
      Watcher.create!(:watchable => Wiki.find(2), :user => user)
95
      Watcher.create!(:watchable => WikiPage.find(3), :user => user)
96
    end
97

  
98
    context "of user" do
99
      setup do
100
        @member = Member.create!(:project => Project.find(2), :principal => User.find(9), :role_ids => [1, 2])
101
      end
102

  
103
      context "by deleting membership" do
104
        should "prune watchers" do
105
          assert_difference 'Watcher.count', -4 do
106
            @member.destroy
107
          end
108
        end
109
      end
110

  
111
      context "by updating roles" do
112
        should "prune watchers" do
113
          Role.find(2).remove_permission! :view_wiki_pages
114
          member = Member.first(:order => 'id desc')
115
          assert_difference 'Watcher.count', -2 do
116
            member.role_ids = [2]
117
            member.save
118
          end
119
          assert !Message.find(7).watched_by?(@user)
120
        end
121
      end
122
    end
123

  
124
    context "of group" do
125
      setup do
126
        group = Group.find(10)
127
        @member = Member.create!(:project => Project.find(2), :principal => group, :role_ids => [1, 2])
128
        group.users << User.find(9)
129
      end
130

  
131
      context "by deleting membership" do
132
        should "prune watchers" do
133
          assert_difference 'Watcher.count', -4 do
134
            @member.destroy
135
          end
136
        end
137
      end
138

  
139
      context "by updating roles" do
140
        should "prune watchers" do
141
          Role.find(2).remove_permission! :view_wiki_pages
142
          assert_difference 'Watcher.count', -2 do
143
            @member.role_ids = [2]
144
            @member.save
145
          end
146
        end
147
      end
148
    end
149
  end
150
end
.svn/pristine/05/05d53773172688f95b7f90e6ffa69f1cbdf7504b.svn-base
1
<div class="contextual">
2
  &#171;
3
  <% unless @changeset.previous.nil? -%>
4
    <%= link_to_revision(@changeset.previous, @project, :text => l(:label_previous)) %>
5
  <% else -%>
6
    <%= l(:label_previous) %>
7
  <% end -%>
8
|
9
  <% unless @changeset.next.nil? -%>
10
    <%= link_to_revision(@changeset.next, @project, :text => l(:label_next)) %>
11
  <% else -%>
12
    <%= l(:label_next) %>
13
  <% end -%>
14
  &#187;&nbsp;
15

  
16
  <% form_tag({:controller => 'repositories',
17
               :action     => 'revision',
18
               :id         => @project,
19
               :rev        => nil},
20
               :method     => :get) do %>
21
    <%= text_field_tag 'rev', @rev, :size => 8 %>
22
    <%= submit_tag 'OK', :name => nil %>
23
  <% end %>
24
</div>
25

  
26
<h2><%= l(:label_revision) %> <%= format_revision(@changeset) %></h2>
27

  
28
<table class="revision-info">
29
  <% if @changeset.scmid %>
30
    <tr>
31
      <td>ID</td><td><%= h(@changeset.scmid) %></td>
32
    </tr>
33
  <% end %>
34
  <% unless @changeset.parents.blank? %>
35
    <tr>
36
      <td><%= l(:label_parent_revision) %></td>
37
      <td>
38
        <%= @changeset.parents.collect{
39
              |p| link_to_revision(p, @project, :text => format_revision(p))
40
            }.join(", ") %>
41
      </td>
42
    </tr>
43
  <% end %>
44
  <% unless @changeset.children.blank? %>
45
    <tr>
46
      <td><%= l(:label_child_revision) %></td>
47
      <td>
48
       <%= @changeset.children.collect{
49
              |p| link_to_revision(p, @project, :text => format_revision(p))
50
             }.join(", ") %>
51
      </td>
52
    </tr>
53
  <% end %>
54
</table>
55
<p>
56
<span class="author">
57
<%= authoring(@changeset.committed_on, @changeset.author) %>
58
</span>
59
</p>
60

  
61
<%= textilizable @changeset.comments %>
62

  
63
<% if @changeset.issues.visible.any? %>
64
<h3><%= l(:label_related_issues) %></h3>
65
<ul>
66
<% @changeset.issues.visible.each do |issue| %>
67
  <li><%= link_to_issue issue %></li>
68
<% end %>
69
</ul>
70
<% end %>
71

  
72
<% if User.current.allowed_to?(:browse_repository, @project) %>
73
<h3><%= l(:label_attachment_plural) %></h3>
74
<ul id="changes-legend">
75
<li class="change change-A"><%= l(:label_added)    %></li>
76
<li class="change change-M"><%= l(:label_modified) %></li>
77
<li class="change change-C"><%= l(:label_copied)   %></li>
78
<li class="change change-R"><%= l(:label_renamed)  %></li>
79
<li class="change change-D"><%= l(:label_deleted)  %></li>
80
</ul>
81

  
82
<p><%= link_to(l(:label_view_diff),
83
               :action => 'diff',
84
               :id     => @project,
85
               :path   => "",
86
               :rev    => @changeset.identifier) if @changeset.changes.any? %></p>
87

  
88
<div class="changeset-changes">
89
<%= render_changeset_changes %>
90
</div>
91
<% end %>
92

  
93
<% content_for :header_tags do %>
94
<%= stylesheet_link_tag "scm" %>
95
<% end %>
96

  
97
<% html_title("#{l(:label_revision)} #{format_revision(@changeset)}") -%>
.svn/pristine/05/05e06f37663175a7e86aab01c766edf25f24a007.svn-base
1
class CreateWikiContents < ActiveRecord::Migration
2
  def self.up
3
    create_table :wiki_contents do |t|
4
      t.column :page_id, :integer, :null => false
5
      t.column :author_id, :integer
6
      t.column :text, :text
7
      t.column :comments, :string, :limit => 255, :default => ""
8
      t.column :updated_on, :datetime, :null => false
9
      t.column :version, :integer, :null => false
10
    end
11
    add_index :wiki_contents, :page_id, :name => :wiki_contents_page_id
12

  
13
    create_table :wiki_content_versions do |t|
14
      t.column :wiki_content_id, :integer, :null => false
15
      t.column :page_id, :integer, :null => false
16
      t.column :author_id, :integer
17
      t.column :data, :binary
18
      t.column :compression, :string, :limit => 6, :default => ""
19
      t.column :comments, :string, :limit => 255, :default => ""
20
      t.column :updated_on, :datetime, :null => false
21
      t.column :version, :integer, :null => false
22
    end
23
    add_index :wiki_content_versions, :wiki_content_id, :name => :wiki_content_versions_wcid
24
  end
25

  
26
  def self.down
27
    drop_table :wiki_contents
28
    drop_table :wiki_content_versions
29
  end
30
end
.svn/pristine/05/05f81f90a3570490e6ea8a94e643c12e2ec9cbe3.svn-base
1
# Redmine - project management software
2
# Copyright (C) 2006-2011  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
class Project < ActiveRecord::Base
19
  include Redmine::SafeAttributes
20

  
21
  # Project statuses
22
  STATUS_ACTIVE     = 1
23
  STATUS_ARCHIVED   = 9
24

  
25
  # Maximum length for project identifiers
26
  IDENTIFIER_MAX_LENGTH = 100
27

  
28
  # Specific overidden Activities
29
  has_many :time_entry_activities
30
  has_many :members, :include => [:user, :roles], :conditions => "#{User.table_name}.type='User' AND #{User.table_name}.status=#{User::STATUS_ACTIVE}"
31
  has_many :memberships, :class_name => 'Member'
32
  has_many :member_principals, :class_name => 'Member',
33
                               :include => :principal,
34
                               :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{User::STATUS_ACTIVE})"
35
  has_many :users, :through => :members
36
  has_many :principals, :through => :member_principals, :source => :principal
37

  
38
  has_many :enabled_modules, :dependent => :delete_all
39
  has_and_belongs_to_many :trackers, :order => "#{Tracker.table_name}.position"
40
  has_many :issues, :dependent => :destroy, :order => "#{Issue.table_name}.created_on DESC", :include => [:status, :tracker]
41
  has_many :issue_changes, :through => :issues, :source => :journals
42
  has_many :versions, :dependent => :destroy, :order => "#{Version.table_name}.effective_date DESC, #{Version.table_name}.name DESC"
43
  has_many :time_entries, :dependent => :delete_all
44
  has_many :queries, :dependent => :delete_all
45
  has_many :documents, :dependent => :destroy
46
  has_many :news, :dependent => :destroy, :include => :author
47
  has_many :issue_categories, :dependent => :delete_all, :order => "#{IssueCategory.table_name}.name"
48
  has_many :boards, :dependent => :destroy, :order => "position ASC"
49
  has_one :repository, :dependent => :destroy
50
  has_many :changesets, :through => :repository
51
  has_one :wiki, :dependent => :destroy
52
  # Custom field for the project issues
53
  has_and_belongs_to_many :issue_custom_fields,
54
                          :class_name => 'IssueCustomField',
55
                          :order => "#{CustomField.table_name}.position",
56
                          :join_table => "#{table_name_prefix}custom_fields_projects#{table_name_suffix}",
57
                          :association_foreign_key => 'custom_field_id'
58

  
59
  acts_as_nested_set :order => 'name', :dependent => :destroy
60
  acts_as_attachable :view_permission => :view_files,
61
                     :delete_permission => :manage_files
62

  
63
  acts_as_customizable
64
  acts_as_searchable :columns => ['name', 'identifier', 'description'], :project_key => 'id', :permission => nil
65
  acts_as_event :title => Proc.new {|o| "#{l(:label_project)}: #{o.name}"},
66
                :url => Proc.new {|o| {:controller => 'projects', :action => 'show', :id => o}},
67
                :author => nil
68

  
69
  attr_protected :status
70

  
71
  validates_presence_of :name, :identifier
72
  validates_uniqueness_of :identifier
73
  validates_associated :repository, :wiki
74
  validates_length_of :name, :maximum => 255
75
  validates_length_of :homepage, :maximum => 255
76
  validates_length_of :identifier, :in => 1..IDENTIFIER_MAX_LENGTH
77
  # donwcase letters, digits, dashes but not digits only
78
  validates_format_of :identifier, :with => /^(?!\d+$)[a-z0-9\-]*$/, :if => Proc.new { |p| p.identifier_changed? }
79
  # reserved words
80
  validates_exclusion_of :identifier, :in => %w( new )
81

  
82
  before_destroy :delete_all_members
83

  
84
  named_scope :has_module, lambda { |mod| { :conditions => ["#{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name=?)", mod.to_s] } }
85
  named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
86
  named_scope :all_public, { :conditions => { :is_public => true } }
87
  named_scope :visible, lambda {|*args| {:conditions => Project.visible_condition(args.shift || User.current, *args) }}
88

  
89
  def initialize(attributes = nil)
90
    super
91

  
92
    initialized = (attributes || {}).stringify_keys
93
    if !initialized.key?('identifier') && Setting.sequential_project_identifiers?
94
      self.identifier = Project.next_identifier
95
    end
96
    if !initialized.key?('is_public')
97
      self.is_public = Setting.default_projects_public?
98
    end
99
    if !initialized.key?('enabled_module_names')
100
      self.enabled_module_names = Setting.default_projects_modules
101
    end
102
    if !initialized.key?('trackers') && !initialized.key?('tracker_ids')
103
      self.trackers = Tracker.all
104
    end
105
  end
106

  
107
  def identifier=(identifier)
108
    super unless identifier_frozen?
109
  end
110

  
111
  def identifier_frozen?
112
    errors[:identifier].nil? && !(new_record? || identifier.blank?)
113
  end
114

  
115
  # returns latest created projects
116
  # non public projects will be returned only if user is a member of those
117
  def self.latest(user=nil, count=5)
118
    visible(user).find(:all, :limit => count, :order => "created_on DESC")	
119
  end	
120

  
121
  # Returns true if the project is visible to +user+ or to the current user.
122
  def visible?(user=User.current)
123
    user.allowed_to?(:view_project, self)
124
  end
125

  
126
  # Returns a SQL conditions string used to find all projects visible by the specified user.
127
  #
128
  # Examples:
129
  #   Project.visible_condition(admin)        => "projects.status = 1"
130
  #   Project.visible_condition(normal_user)  => "((projects.status = 1) AND (projects.is_public = 1 OR projects.id IN (1,3,4)))"
131
  #   Project.visible_condition(anonymous)    => "((projects.status = 1) AND (projects.is_public = 1))"
132
  def self.visible_condition(user, options={})
133
    allowed_to_condition(user, :view_project, options)
134
  end
135

  
136
  # Returns a SQL conditions string used to find all projects for which +user+ has the given +permission+
137
  #
138
  # Valid options:
139
  # * :project => limit the condition to project
140
  # * :with_subprojects => limit the condition to project and its subprojects
141
  # * :member => limit the condition to the user projects
142
  def self.allowed_to_condition(user, permission, options={})
143
    base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
144
    if perm = Redmine::AccessControl.permission(permission)
145
      unless perm.project_module.nil?
146
        # If the permission belongs to a project module, make sure the module is enabled
147
        base_statement << " AND #{Project.table_name}.id IN (SELECT em.project_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.project_module}')"
148
      end
149
    end
150
    if options[:project]
151
      project_statement = "#{Project.table_name}.id = #{options[:project].id}"
152
      project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
153
      base_statement = "(#{project_statement}) AND (#{base_statement})"
154
    end
155

  
156
    if user.admin?
157
      base_statement
158
    else
159
      statement_by_role = {}
160
      unless options[:member]
161
        role = user.logged? ? Role.non_member : Role.anonymous
162
        if role.allowed_to?(permission)
163
          statement_by_role[role] = "#{Project.table_name}.is_public = #{connection.quoted_true}"
164
        end
165
      end
166
      if user.logged?
167
        user.projects_by_role.each do |role, projects|
168
          if role.allowed_to?(permission)
169
            statement_by_role[role] = "#{Project.table_name}.id IN (#{projects.collect(&:id).join(',')})"
170
          end
171
        end
172
      end
173
      if statement_by_role.empty?
174
        "1=0"
175
      else
176
        if block_given?
177
          statement_by_role.each do |role, statement|
178
            if s = yield(role, user)
179
              statement_by_role[role] = "(#{statement} AND (#{s}))"
180
            end
181
          end
182
        end
183
        "((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))"
184
      end
185
    end
186
  end
187

  
188
  # Returns the Systemwide and project specific activities
189
  def activities(include_inactive=false)
190
    if include_inactive
191
      return all_activities
192
    else
193
      return active_activities
194
    end
195
  end
196

  
197
  # Will create a new Project specific Activity or update an existing one
198
  #
199
  # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
200
  # does not successfully save.
201
  def update_or_create_time_entry_activity(id, activity_hash)
202
    if activity_hash.respond_to?(:has_key?) && activity_hash.has_key?('parent_id')
203
      self.create_time_entry_activity_if_needed(activity_hash)
204
    else
205
      activity = project.time_entry_activities.find_by_id(id.to_i)
206
      activity.update_attributes(activity_hash) if activity
207
    end
208
  end
209

  
210
  # Create a new TimeEntryActivity if it overrides a system TimeEntryActivity
211
  #
212
  # This will raise a ActiveRecord::Rollback if the TimeEntryActivity
213
  # does not successfully save.
214
  def create_time_entry_activity_if_needed(activity)
215
    if activity['parent_id']
216

  
217
      parent_activity = TimeEntryActivity.find(activity['parent_id'])
218
      activity['name'] = parent_activity.name
219
      activity['position'] = parent_activity.position
220

  
221
      if Enumeration.overridding_change?(activity, parent_activity)
222
        project_activity = self.time_entry_activities.create(activity)
223

  
224
        if project_activity.new_record?
225
          raise ActiveRecord::Rollback, "Overridding TimeEntryActivity was not successfully saved"
226
        else
227
          self.time_entries.update_all("activity_id = #{project_activity.id}", ["activity_id = ?", parent_activity.id])
228
        end
229
      end
230
    end
231
  end
232

  
233
  # Returns a :conditions SQL string that can be used to find the issues associated with this project.
234
  #
235
  # Examples:
236
  #   project.project_condition(true)  => "(projects.id = 1 OR (projects.lft > 1 AND projects.rgt < 10))"
237
  #   project.project_condition(false) => "projects.id = 1"
238
  def project_condition(with_subprojects)
239
    cond = "#{Project.table_name}.id = #{id}"
240
    cond = "(#{cond} OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt}))" if with_subprojects
241
    cond
242
  end
243

  
244
  def self.find(*args)
245
    if args.first && args.first.is_a?(String) && !args.first.match(/^\d*$/)
246
      project = find_by_identifier(*args)
247
      raise ActiveRecord::RecordNotFound, "Couldn't find Project with identifier=#{args.first}" if project.nil?
248
      project
249
    else
250
      super
251
    end
252
  end
253

  
254
  def to_param
255
    # id is used for projects with a numeric identifier (compatibility)
256
    @to_param ||= (identifier.to_s =~ %r{^\d*$} ? id : identifier)
257
  end
258

  
259
  def active?
260
    self.status == STATUS_ACTIVE
261
  end
262

  
263
  def archived?
264
    self.status == STATUS_ARCHIVED
265
  end
266

  
267
  # Archives the project and its descendants
268
  def archive
269
    # Check that there is no issue of a non descendant project that is assigned
270
    # to one of the project or descendant versions
271
    v_ids = self_and_descendants.collect {|p| p.version_ids}.flatten
272
    if v_ids.any? && Issue.find(:first, :include => :project,
273
                                        :conditions => ["(#{Project.table_name}.lft < ? OR #{Project.table_name}.rgt > ?)" +
274
                                                        " AND #{Issue.table_name}.fixed_version_id IN (?)", lft, rgt, v_ids])
275
      return false
276
    end
277
    Project.transaction do
278
      archive!
279
    end
280
    true
281
  end
282

  
283
  # Unarchives the project
284
  # All its ancestors must be active
285
  def unarchive
286
    return false if ancestors.detect {|a| !a.active?}
287
    update_attribute :status, STATUS_ACTIVE
288
  end
289

  
290
  # Returns an array of projects the project can be moved to
291
  # by the current user
292
  def allowed_parents
293
    return @allowed_parents if @allowed_parents
294
    @allowed_parents = Project.find(:all, :conditions => Project.allowed_to_condition(User.current, :add_subprojects))
295
    @allowed_parents = @allowed_parents - self_and_descendants
296
    if User.current.allowed_to?(:add_project, nil, :global => true) || (!new_record? && parent.nil?)
297
      @allowed_parents << nil
298
    end
299
    unless parent.nil? || @allowed_parents.empty? || @allowed_parents.include?(parent)
300
      @allowed_parents << parent
301
    end
302
    @allowed_parents
303
  end
304

  
305
  # Sets the parent of the project with authorization check
306
  def set_allowed_parent!(p)
307
    unless p.nil? || p.is_a?(Project)
308
      if p.to_s.blank?
309
        p = nil
310
      else
311
        p = Project.find_by_id(p)
312
        return false unless p
313
      end
314
    end
315
    if p.nil?
316
      if !new_record? && allowed_parents.empty?
317
        return false
318
      end
319
    elsif !allowed_parents.include?(p)
320
      return false
321
    end
322
    set_parent!(p)
323
  end
324

  
325
  # Sets the parent of the project
326
  # Argument can be either a Project, a String, a Fixnum or nil
327
  def set_parent!(p)
328
    unless p.nil? || p.is_a?(Project)
329
      if p.to_s.blank?
330
        p = nil
331
      else
332
        p = Project.find_by_id(p)
333
        return false unless p
334
      end
335
    end
336
    if p == parent && !p.nil?
337
      # Nothing to do
338
      true
339
    elsif p.nil? || (p.active? && move_possible?(p))
340
      # Insert the project so that target's children or root projects stay alphabetically sorted
341
      sibs = (p.nil? ? self.class.roots : p.children)
342
      to_be_inserted_before = sibs.detect {|c| c.name.to_s.downcase > name.to_s.downcase }
343
      if to_be_inserted_before
344
        move_to_left_of(to_be_inserted_before)
345
      elsif p.nil?
346
        if sibs.empty?
347
          # move_to_root adds the project in first (ie. left) position
348
          move_to_root
349
        else
350
          move_to_right_of(sibs.last) unless self == sibs.last
351
        end
352
      else
353
        # move_to_child_of adds the project in last (ie.right) position
354
        move_to_child_of(p)
355
      end
356
      Issue.update_versions_from_hierarchy_change(self)
357
      true
358
    else
359
      # Can not move to the given target
360
      false
361
    end
362
  end
363

  
364
  # Returns an array of the trackers used by the project and its active sub projects
365
  def rolled_up_trackers
366
    @rolled_up_trackers ||=
367
      Tracker.find(:all, :joins => :projects,
368
                         :select => "DISTINCT #{Tracker.table_name}.*",
369
                         :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
370
                         :order => "#{Tracker.table_name}.position")
371
  end
372

  
373
  # Closes open and locked project versions that are completed
374
  def close_completed_versions
375
    Version.transaction do
376
      versions.find(:all, :conditions => {:status => %w(open locked)}).each do |version|
377
        if version.completed?
378
          version.update_attribute(:status, 'closed')
379
        end
380
      end
381
    end
382
  end
383

  
384
  # Returns a scope of the Versions on subprojects
385
  def rolled_up_versions
386
    @rolled_up_versions ||=
387
      Version.scoped(:include => :project,
388
                     :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt])
389
  end
390

  
391
  # Returns a scope of the Versions used by the project
392
  def shared_versions
393
    @shared_versions ||= begin
394
      r = root? ? self : root
395
      Version.scoped(:include => :project,
396
                     :conditions => "#{Project.table_name}.id = #{id}" +
397
                                    " OR (#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND (" +
398
                                          " #{Version.table_name}.sharing = 'system'" +
399
                                          " OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" +
400
                                          " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
401
                                          " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
402
                                          "))")
403
    end
404
  end
405

  
406
  # Returns a hash of project users grouped by role
407
  def users_by_role
408
    members.find(:all, :include => [:user, :roles]).inject({}) do |h, m|
409
      m.roles.each do |r|
410
        h[r] ||= []
411
        h[r] << m.user
412
      end
413
      h
414
    end
415
  end
416

  
417
  # Deletes all project's members
418
  def delete_all_members
419
    me, mr = Member.table_name, MemberRole.table_name
420
    connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.project_id = #{id})")
421
    Member.delete_all(['project_id = ?', id])
422
  end
423

  
424
  # Users/groups issues can be assigned to
425
  def assignable_users
426
    assignable = Setting.issue_group_assignment? ? member_principals : members
427
    assignable.select {|m| m.roles.detect {|role| role.assignable?}}.collect {|m| m.principal}.sort
428
  end
429

  
430
  # Returns the mail adresses of users that should be always notified on project events
431
  def recipients
432
    notified_users.collect {|user| user.mail}
433
  end
434

  
435
  # Returns the users that should be notified on project events
436
  def notified_users
437
    # TODO: User part should be extracted to User#notify_about?
438
    members.select {|m| m.mail_notification? || m.user.mail_notification == 'all'}.collect {|m| m.user}
439
  end
440

  
441
  # Returns an array of all custom fields enabled for project issues
442
  # (explictly associated custom fields and custom fields enabled for all projects)
443
  def all_issue_custom_fields
444
    @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
445
  end
446

  
447
  # Returns an array of all custom fields enabled for project time entries
448
  # (explictly associated custom fields and custom fields enabled for all projects)
449
  def all_time_entry_custom_fields
450
    @all_time_entry_custom_fields ||= (TimeEntryCustomField.for_all + time_entry_custom_fields).uniq.sort
451
  end
452

  
453
  def project
454
    self
455
  end
456

  
457
  def <=>(project)
458
    name.downcase <=> project.name.downcase
459
  end
460

  
461
  def to_s
462
    name
463
  end
464

  
465
  # Returns a short description of the projects (first lines)
466
  def short_description(length = 255)
467
    description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
468
  end
469

  
470
  def css_classes
471
    s = 'project'
472
    s << ' root' if root?
473
    s << ' child' if child?
474
    s << (leaf? ? ' leaf' : ' parent')
475
    s
476
  end
477

  
478
  # The earliest start date of a project, based on it's issues and versions
479
  def start_date
480
    [
481
     issues.minimum('start_date'),
482
     shared_versions.collect(&:effective_date),
483
     shared_versions.collect(&:start_date)
484
    ].flatten.compact.min
485
  end
486

  
487
  # The latest due date of an issue or version
488
  def due_date
489
    [
490
     issues.maximum('due_date'),
491
     shared_versions.collect(&:effective_date),
492
     shared_versions.collect {|v| v.fixed_issues.maximum('due_date')}
493
    ].flatten.compact.max
494
  end
495

  
496
  def overdue?
497
    active? && !due_date.nil? && (due_date < Date.today)
498
  end
499

  
500
  # Returns the percent completed for this project, based on the
501
  # progress on it's versions.
502
  def completed_percent(options={:include_subprojects => false})
503
    if options.delete(:include_subprojects)
504
      total = self_and_descendants.collect(&:completed_percent).sum
505

  
506
      total / self_and_descendants.count
507
    else
508
      if versions.count > 0
509
        total = versions.collect(&:completed_pourcent).sum
510

  
511
        total / versions.count
512
      else
513
        100
514
      end
515
    end
516
  end
517

  
518
  # Return true if this project is allowed to do the specified action.
519
  # action can be:
520
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
521
  # * a permission Symbol (eg. :edit_project)
522
  def allows_to?(action)
523
    if action.is_a? Hash
524
      allowed_actions.include? "#{action[:controller]}/#{action[:action]}"
525
    else
526
      allowed_permissions.include? action
527
    end
528
  end
529

  
530
  def module_enabled?(module_name)
531
    module_name = module_name.to_s
532
    enabled_modules.detect {|m| m.name == module_name}
533
  end
534

  
535
  def enabled_module_names=(module_names)
536
    if module_names && module_names.is_a?(Array)
537
      module_names = module_names.collect(&:to_s).reject(&:blank?)
538
      self.enabled_modules = module_names.collect {|name| enabled_modules.detect {|mod| mod.name == name} || EnabledModule.new(:name => name)}
539
    else
540
      enabled_modules.clear
541
    end
542
  end
543

  
544
  # Returns an array of the enabled modules names
545
  def enabled_module_names
546
    enabled_modules.collect(&:name)
547
  end
548

  
549
  # Enable a specific module
550
  #
551
  # Examples:
552
  #   project.enable_module!(:issue_tracking)
553
  #   project.enable_module!("issue_tracking")
554
  def enable_module!(name)
555
    enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name)
556
  end
557

  
558
  # Disable a module if it exists
559
  #
560
  # Examples:
561
  #   project.disable_module!(:issue_tracking)
562
  #   project.disable_module!("issue_tracking")
563
  #   project.disable_module!(project.enabled_modules.first)
564
  def disable_module!(target)
565
    target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target)
566
    target.destroy unless target.blank?
567
  end
568

  
569
  safe_attributes 'name',
570
    'description',
571
    'homepage',
572
    'is_public',
573
    'identifier',
574
    'custom_field_values',
575
    'custom_fields',
576
    'tracker_ids',
577
    'issue_custom_field_ids'
578

  
579
  safe_attributes 'enabled_module_names',
580
    :if => lambda {|project, user| project.new_record? || user.allowed_to?(:select_project_modules, project) }
581

  
582
  # Returns an array of projects that are in this project's hierarchy
583
  #
584
  # Example: parents, children, siblings
585
  def hierarchy
586
    parents = project.self_and_ancestors || []
587
    descendants = project.descendants || []
588
    project_hierarchy = parents | descendants # Set union
589
  end
590

  
591
  # Returns an auto-generated project identifier based on the last identifier used
592
  def self.next_identifier
593
    p = Project.find(:first, :order => 'created_on DESC')
594
    p.nil? ? nil : p.identifier.to_s.succ
595
  end
596

  
597
  # Copies and saves the Project instance based on the +project+.
598
  # Duplicates the source project's:
599
  # * Wiki
600
  # * Versions
601
  # * Categories
602
  # * Issues
603
  # * Members
604
  # * Queries
605
  #
606
  # Accepts an +options+ argument to specify what to copy
607
  #
608
  # Examples:
609
  #   project.copy(1)                                    # => copies everything
610
  #   project.copy(1, :only => 'members')                # => copies members only
611
  #   project.copy(1, :only => ['members', 'versions'])  # => copies members and versions
612
  def copy(project, options={})
613
    project = project.is_a?(Project) ? project : Project.find(project)
614

  
615
    to_be_copied = %w(wiki versions issue_categories issues members queries boards)
616
    to_be_copied = to_be_copied & options[:only].to_a unless options[:only].nil?
617

  
618
    Project.transaction do
619
      if save
620
        reload
621
        to_be_copied.each do |name|
622
          send "copy_#{name}", project
623
        end
624
        Redmine::Hook.call_hook(:model_project_copy_before_save, :source_project => project, :destination_project => self)
625
        save
626
      end
627
    end
628
  end
629

  
630

  
631
  # Copies +project+ and returns the new instance.  This will not save
632
  # the copy
633
  def self.copy_from(project)
634
    begin
635
      project = project.is_a?(Project) ? project : Project.find(project)
636
      if project
637
        # clear unique attributes
638
        attributes = project.attributes.dup.except('id', 'name', 'identifier', 'status', 'parent_id', 'lft', 'rgt')
639
        copy = Project.new(attributes)
640
        copy.enabled_modules = project.enabled_modules
641
        copy.trackers = project.trackers
642
        copy.custom_values = project.custom_values.collect {|v| v.clone}
643
        copy.issue_custom_fields = project.issue_custom_fields
644
        return copy
645
      else
646
        return nil
647
      end
648
    rescue ActiveRecord::RecordNotFound
649
      return nil
650
    end
651
  end
652

  
653
  # Yields the given block for each project with its level in the tree
654
  def self.project_tree(projects, &block)
655
    ancestors = []
656
    projects.sort_by(&:lft).each do |project|
657
      while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
658
        ancestors.pop
659
      end
660
      yield project, ancestors.size
661
      ancestors << project
662
    end
663
  end
664

  
665
  private
666

  
667
  # Copies wiki from +project+
668
  def copy_wiki(project)
669
    # Check that the source project has a wiki first
670
    unless project.wiki.nil?
671
      self.wiki ||= Wiki.new
672
      wiki.attributes = project.wiki.attributes.dup.except("id", "project_id")
673
      wiki_pages_map = {}
674
      project.wiki.pages.each do |page|
675
        # Skip pages without content
676
        next if page.content.nil?
677
        new_wiki_content = WikiContent.new(page.content.attributes.dup.except("id", "page_id", "updated_on"))
678
        new_wiki_page = WikiPage.new(page.attributes.dup.except("id", "wiki_id", "created_on", "parent_id"))
679
        new_wiki_page.content = new_wiki_content
680
        wiki.pages << new_wiki_page
681
        wiki_pages_map[page.id] = new_wiki_page
682
      end
683
      wiki.save
684
      # Reproduce page hierarchy
685
      project.wiki.pages.each do |page|
686
        if page.parent_id && wiki_pages_map[page.id]
687
          wiki_pages_map[page.id].parent = wiki_pages_map[page.parent_id]
688
          wiki_pages_map[page.id].save
689
        end
690
      end
691
    end
692
  end
693

  
694
  # Copies versions from +project+
695
  def copy_versions(project)
696
    project.versions.each do |version|
697
      new_version = Version.new
698
      new_version.attributes = version.attributes.dup.except("id", "project_id", "created_on", "updated_on")
699
      self.versions << new_version
700
    end
701
  end
702

  
703
  # Copies issue categories from +project+
704
  def copy_issue_categories(project)
705
    project.issue_categories.each do |issue_category|
706
      new_issue_category = IssueCategory.new
707
      new_issue_category.attributes = issue_category.attributes.dup.except("id", "project_id")
708
      self.issue_categories << new_issue_category
709
    end
710
  end
711

  
712
  # Copies issues from +project+
713
  # Note: issues assigned to a closed version won't be copied due to validation rules
714
  def copy_issues(project)
715
    # Stores the source issue id as a key and the copied issues as the
716
    # value.  Used to map the two togeather for issue relations.
717
    issues_map = {}
718

  
719
    # Get issues sorted by root_id, lft so that parent issues
720
    # get copied before their children
721
    project.issues.find(:all, :order => 'root_id, lft').each do |issue|
722
      new_issue = Issue.new
723
      new_issue.copy_from(issue)
724
      new_issue.project = self
725
      # Reassign fixed_versions by name, since names are unique per
726
      # project and the versions for self are not yet saved
727
      if issue.fixed_version
728
        new_issue.fixed_version = self.versions.select {|v| v.name == issue.fixed_version.name}.first
729
      end
730
      # Reassign the category by name, since names are unique per
731
      # project and the categories for self are not yet saved
732
      if issue.category
733
        new_issue.category = self.issue_categories.select {|c| c.name == issue.category.name}.first
734
      end
735
      # Parent issue
736
      if issue.parent_id
737
        if copied_parent = issues_map[issue.parent_id]
738
          new_issue.parent_issue_id = copied_parent.id
739
        end
740
      end
741

  
742
      self.issues << new_issue
743
      if new_issue.new_record?
744
        logger.info "Project#copy_issues: issue ##{issue.id} could not be copied: #{new_issue.errors.full_messages}" if logger && logger.info
745
      else
746
        issues_map[issue.id] = new_issue unless new_issue.new_record?
747
      end
748
    end
749

  
750
    # Relations after in case issues related each other
751
    project.issues.each do |issue|
752
      new_issue = issues_map[issue.id]
753
      unless new_issue
754
        # Issue was not copied
755
        next
756
      end
757

  
758
      # Relations
759
      issue.relations_from.each do |source_relation|
760
        new_issue_relation = IssueRelation.new
761
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
762
        new_issue_relation.issue_to = issues_map[source_relation.issue_to_id]
763
        if new_issue_relation.issue_to.nil? && Setting.cross_project_issue_relations?
764
          new_issue_relation.issue_to = source_relation.issue_to
765
        end
766
        new_issue.relations_from << new_issue_relation
767
      end
768

  
769
      issue.relations_to.each do |source_relation|
770
        new_issue_relation = IssueRelation.new
771
        new_issue_relation.attributes = source_relation.attributes.dup.except("id", "issue_from_id", "issue_to_id")
772
        new_issue_relation.issue_from = issues_map[source_relation.issue_from_id]
773
        if new_issue_relation.issue_from.nil? && Setting.cross_project_issue_relations?
774
          new_issue_relation.issue_from = source_relation.issue_from
775
        end
776
        new_issue.relations_to << new_issue_relation
777
      end
778
    end
779
  end
780

  
781
  # Copies members from +project+
782
  def copy_members(project)
783
    # Copy users first, then groups to handle members with inherited and given roles
784
    members_to_copy = []
785
    members_to_copy += project.memberships.select {|m| m.principal.is_a?(User)}
786
    members_to_copy += project.memberships.select {|m| !m.principal.is_a?(User)}
787

  
788
    members_to_copy.each do |member|
789
      new_member = Member.new
790
      new_member.attributes = member.attributes.dup.except("id", "project_id", "created_on")
791
      # only copy non inherited roles
792
      # inherited roles will be added when copying the group membership
793
      role_ids = member.member_roles.reject(&:inherited?).collect(&:role_id)
794
      next if role_ids.empty?
795
      new_member.role_ids = role_ids
796
      new_member.project = self
797
      self.members << new_member
798
    end
799
  end
800

  
801
  # Copies queries from +project+
802
  def copy_queries(project)
803
    project.queries.each do |query|
804
      new_query = Query.new
805
      new_query.attributes = query.attributes.dup.except("id", "project_id", "sort_criteria")
806
      new_query.sort_criteria = query.sort_criteria if query.sort_criteria
807
      new_query.project = self
808
      new_query.user_id = query.user_id
809
      self.queries << new_query
810
    end
811
  end
812

  
813
  # Copies boards from +project+
814
  def copy_boards(project)
815
    project.boards.each do |board|
816
      new_board = Board.new
817
      new_board.attributes = board.attributes.dup.except("id", "project_id", "topics_count", "messages_count", "last_message_id")
818
      new_board.project = self
819
      self.boards << new_board
820
    end
821
  end
822

  
823
  def allowed_permissions
824
    @allowed_permissions ||= begin
825
      module_names = enabled_modules.all(:select => :name).collect {|m| m.name}
826
      Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name}
827
    end
828
  end
829

  
830
  def allowed_actions
831
    @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten
832
  end
833

  
834
  # Returns all the active Systemwide and project specific activities
835
  def active_activities
836
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
837

  
838
    if overridden_activity_ids.empty?
839
      return TimeEntryActivity.shared.active
840
    else
841
      return system_activities_and_project_overrides
842
    end
843
  end
844

  
845
  # Returns all the Systemwide and project specific activities
846
  # (inactive and active)
847
  def all_activities
848
    overridden_activity_ids = self.time_entry_activities.collect(&:parent_id)
849

  
850
    if overridden_activity_ids.empty?
851
      return TimeEntryActivity.shared
852
    else
853
      return system_activities_and_project_overrides(true)
854
    end
855
  end
856

  
857
  # Returns the systemwide active activities merged with the project specific overrides
858
  def system_activities_and_project_overrides(include_inactive=false)
859
    if include_inactive
860
      return TimeEntryActivity.shared.
861
        find(:all,
862
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
863
        self.time_entry_activities
864
    else
865
      return TimeEntryActivity.shared.active.
866
        find(:all,
867
             :conditions => ["id NOT IN (?)", self.time_entry_activities.collect(&:parent_id)]) +
868
        self.time_entry_activities.active
869
    end
870
  end
871

  
872
  # Archives subprojects recursively
873
  def archive!
874
    children.each do |subproject|
875
      subproject.send :archive!
876
    end
877
    update_attribute :status, STATUS_ARCHIVED
878
  end
879
end

Also available in: Unified diff