Compare commits

..
125 Commits
Author SHA1 Message Date
Jean-Philippe Lang 7e5ef18503 tagged version 1.1.3
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/tags/1.1.3@5594 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 09:37:47 +00:00
Jean-Philippe Lang 3f302b66ce Updates for 1.1.3 release.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5592 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 09:23:34 +00:00
Jean-Philippe Lang 32022267af Merged r5285 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5591 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 09:07:40 +00:00
Jean-Philippe Lang f078f7127c Merged r5283 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5590 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 09:06:32 +00:00
Jean-Philippe Lang c2cd4b7f48 Merged r5176 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5589 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 09:02:29 +00:00
Jean-Philippe Lang 0b5b8bebd1 Merged r5171 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5588 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 09:01:37 +00:00
Jean-Philippe Lang 9f36f18b39 Merged r4735 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5587 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 08:59:30 +00:00
Jean-Philippe Lang fab0774c4b Fixes Prototypejs Form.serialize() for multiple selects (#7954).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5586 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:38:24 +00:00
Jean-Philippe Lang 93c0b120de Merged r5469 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5585 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:37:03 +00:00
Jean-Philippe Lang e20191e666 Backported r5581 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5584 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:34:09 +00:00
Jean-Philippe Lang 8d3b32644b Merged r5330 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5583 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:31:21 +00:00
Jean-Philippe Lang 6153d5ab83 Merged r5265 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5582 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:29:23 +00:00
Jean-Philippe Lang f49904569d Merged r5215 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5580 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:16:39 +00:00
Jean-Philippe Lang f48460da4f Merged r5300 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5579 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:15:46 +00:00
Jean-Philippe Lang bd55d7f815 Merged r5232 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5578 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:14:52 +00:00
Jean-Philippe Lang 4402e7e232 Merged r5214 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5577 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:13:59 +00:00
Jean-Philippe Lang b43ebcbdc4 Merged r5186 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5576 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:12:52 +00:00
Jean-Philippe Lang 55fd2f5562 Merged r5185 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5575 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:11:56 +00:00
Jean-Philippe Lang 8a734f9997 Merged r5157 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5574 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:10:27 +00:00
Jean-Philippe Lang d60949ca87 Merged r5181 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5573 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:09:19 +00:00
Jean-Philippe Lang aef8228b0e Merged r5100 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5572 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:08:39 +00:00
Jean-Philippe Lang 20e6652109 Merged r5236 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5571 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:07:28 +00:00
Jean-Philippe Lang d2bc5a9473 Merged r5105 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5570 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:05:41 +00:00
Jean-Philippe Lang 23e75d87d3 Merged r5097 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5569 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:04:23 +00:00
Jean-Philippe Lang 8a13595c64 Merged r5230 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5568 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:02:26 +00:00
Jean-Philippe Lang 7845843596 Merged r5225 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5567 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-29 07:00:16 +00:00
Toshi MARUYAMA f26a504045 Merged r5557 from trunk.
Delete doc/git.rdoc.

http://www.redmine.org/projects/redmine/wiki/Contribute?version=27 has the github mirror link.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5558 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-27 22:43:42 +00:00
Toshi MARUYAMA f274193893 Merged r5555 from trunk.
Remove obsolete github descriptions from doc/git.rdoc.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5556 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-27 14:08:01 +00:00
Toshi MARUYAMA 0ba400834c Merged r5553 from trunk.
Fix notice_failed_to_save_issues format in es, gl and ca locales.

Contributed by Jose M. Prieto.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5554 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-27 10:51:10 +00:00
Toshi MARUYAMA e6148cfdd4 Merged r5502 from trunk.
Simplified Chinese translation updated by Peng Wang.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5503 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-18 04:29:28 +00:00
Toshi MARUYAMA 99b1b95222 Merged r5500 from trunk.
Czech translation updated by Lubor Nosek.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5501 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-17 23:42:31 +00:00
Toshi MARUYAMA a9a5870d25 Merged r4901 from trunk.
Updated basque and czech translations. Contributed by Ales Zabala Alava and Michal Gebauer.

#7390 depends on this commit.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5497 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-17 16:26:53 +00:00
Toshi MARUYAMA f09f2e8e63 scm: git: backout r5336 (#8081, #8083).
Git on Redmine CI Server does not support "--no-decorate" option of "git log".

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5347 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-06 06:59:50 +00:00
Toshi MARUYAMA 2a1203bfef scm: git: backout r5340 (#8081, #8083).
Git on Redmine CI Server does not support "--no-decorate" option of "git log".

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5346 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-06 06:58:47 +00:00
Toshi MARUYAMA f6918d0242 Merged r5338 from trunk.
scm: git: add "decorate = short" in config log section of test repository.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5340 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-06 02:52:59 +00:00
Toshi MARUYAMA e338f522dd Merged r5334 from trunk.
scm: git: add "--no-decorate" option in "git log".

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5336 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-05 23:18:29 +00:00
Jean-Philippe Lang ab10e187a6 Merged r5322 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5323 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-05 12:17:43 +00:00
Toshi MARUYAMA 12801275a8 Merged r5281 from trunk.
r5256 in trunk and r5271 in 1.1-stable fixed #7794 completely.
r5253 (r5183) in trunk and r5184 effect the width of the ASCII character of Japanese PDF.

Contributed by Jun NAITOH.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5282 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-01 15:54:05 +00:00
Toshi MARUYAMA e35e04de8e PDF: fix the width of the ASCII character of Japanese PDF (#7794).
r5256 in trunk has this change.
So, there is no need to commit in trunk.

Contributed by Jun NAITOH.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5271 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-04-01 01:26:38 +00:00
Toshi MARUYAMA 3ca48e1ecf Merged r5233 from trunk.
i18n: fix typo general_pdf_encoding "UFT-8" in sl.yml.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5234 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-28 01:14:15 +00:00
Toshi MARUYAMA f49bbf48e7 Merged r5183 from trunk.
Fix an internal server error on formatting an issue as a PDF in Japanese.

Contributed by Yuki Sonoda.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5184 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-21 06:17:06 +00:00
Toshi MARUYAMA 891ed84fe3 Merged r5091 from trunk.
scm: mercurial: add :order => 'id DESC' explicitly for MySQL test fails.

Because :order => 'id DESC' is defined at 'has_many',
there is no need to set 'order'.
But, MySQL test fails.
Sqlite3 and PostgreSQL pass.
Is this MySQL bug?

MySQL svn trunk test on Redmine CI server fails.
But, svn 1.1-stable passes.
If this is MySQL bug, this effects 1.1-stable, too.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5092 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-11 07:46:23 +00:00
Jean-Philippe Lang 78a4a995e6 Merged r5030 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5031 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-07 19:27:14 +00:00
Jean-Philippe Lang 465534a298 Merged r5021 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5022 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 16:12:27 +00:00
Jean-Philippe Lang d5f1bd07b2 Updates for 1.1.2 release.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5020 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 13:19:48 +00:00
Jean-Philippe Lang 50863117b8 Translations updates.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5018 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 13:12:50 +00:00
Jean-Philippe Lang c6693fc78b Merged r4937 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5017 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 13:08:02 +00:00
Jean-Philippe Lang 1e01711e3d Merged r4946 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5015 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 12:57:03 +00:00
Jean-Philippe Lang 1ab7f6f930 Merged r4820 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5014 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 12:54:59 +00:00
Jean-Philippe Lang f6f7467cdd Merged r4913, r4914, r4916 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5013 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 12:51:10 +00:00
Jean-Philippe Lang 4d0a955d3c Merged r5004 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5012 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 12:48:40 +00:00
Jean-Philippe Lang c45044f13c Merged r4888 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5011 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 12:47:05 +00:00
Jean-Philippe Lang 4761e55691 Merged r4951 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@5010 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-03-06 12:45:56 +00:00
Jean-Philippe Lang af7fb657f4 Merged r4889 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4973 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-28 20:36:06 +00:00
Jean-Philippe Lang 0805ab943e Merged r4890 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4972 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-28 20:34:31 +00:00
Jean-Philippe Lang 9589c0bcad Merged r4811 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4971 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-28 20:33:31 +00:00
Jean-Philippe Lang 91295ea6cd Merged r4935 and r4947 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4970 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-28 20:32:25 +00:00
Jean-Philippe Lang d0f4b5aa50 Merged r4968 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4969 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-28 20:27:44 +00:00
Jean-Philippe Lang 008e8d4fbf Merged r4965 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4966 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-28 16:45:02 +00:00
Toshi MARUYAMA 1e50fea55a Merged r4860 from trunk.
scm: fix diff revision param validation.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4877 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-18 13:48:29 +00:00
Toshi MARUYAMA 008d38d6b4 Merged r4816 from trunk.
scm: fix non ASCII filename downloaded from repo is broken on Internet Explorer.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4819 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-12 09:51:43 +00:00
Toshi MARUYAMA c61c9e6471 Merged r4815 from trunk.
scm: cvs: fix most binary files become corrupted on Windows.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4818 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-12 09:51:21 +00:00
Jean-Baptiste Barth e5b5b61d6e Merged r4813 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4814 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-12 09:03:36 +00:00
Jean-Baptiste Barth 6a8cdf54b3 Removed .project file and added it to svn:ignore'd files. #7497
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4812 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-12 08:56:19 +00:00
Jean-Baptiste Barth e43d98a6f5 Merged r4799 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4800 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-02-06 00:34:21 +00:00
Jean-Philippe Lang 11b774d39d Merged r4784 from trunk (update for 1.1.1 release).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4785 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 14:38:25 +00:00
Jean-Philippe Lang 77c4667dbc Merged r4782 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4783 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 09:13:36 +00:00
Jean-Philippe Lang f05fdd5cfa Merged r4780 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4781 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:54:51 +00:00
Jean-Philippe Lang a0bb70ed2d Merged r4765 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4779 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:45:15 +00:00
Jean-Philippe Lang 1d5c3f7fba Translations updates.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4778 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:43:27 +00:00
Jean-Philippe Lang 8b83aa1470 Merged r4775 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4776 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:32:10 +00:00
Jean-Philippe Lang 3a92721af4 Merged r4739 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4774 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:22:38 +00:00
Jean-Philippe Lang b3218ba4d4 Merged r4700 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4773 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:16:06 +00:00
Jean-Philippe Lang 975ee2b522 Merged r4701 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4772 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:11:51 +00:00
Jean-Philippe Lang 27a319e66d Merged r4727 and r4730 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4771 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:10:36 +00:00
Jean-Philippe Lang 7be5bf6e4d Merged r4741 and r4764 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4770 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:08:01 +00:00
Jean-Philippe Lang c73d4042d1 Merged r4677 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4769 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:05:54 +00:00
Jean-Philippe Lang 8270ad1e64 Merged r4736 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4768 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:04:40 +00:00
Jean-Philippe Lang 26016fbf43 Merged r4761 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4767 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:02:16 +00:00
Jean-Philippe Lang 307e4ceaa2 Merged r4708 and r4709 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4766 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-30 06:00:56 +00:00
Jean-Philippe Lang 03085e85f9 Merged r4720, r4724, r4738 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4763 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-27 17:51:01 +00:00
Jean-Philippe Lang 1f4e0dc10c Merged r4719 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4762 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-27 17:44:40 +00:00
Toshi MARUYAMA f69c95306d Merged r4749 from trunk.
scm: darcs: fix Darcs adapter recognizes new files as modified files above Darcs 2.4.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4751 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-23 04:21:57 +00:00
Toshi MARUYAMA 634ede3e8b Merged r4748 from trunk.
scm: darcs: add compatible test of Darcs 2.3 and 2.4.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4750 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-23 04:21:34 +00:00
Toshi MARUYAMA c2a2979189 Merged r4744 from trunk.
scm: darcs: switch '.' or @url at entries() in darcs version.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4747 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-23 04:03:04 +00:00
Toshi MARUYAMA 9800469943 Merged r4743 from trunk.
scm: darcs: change io.gets to io.read and add darcs version unit test.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4746 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-23 04:02:41 +00:00
Toshi MARUYAMA e47f1d5595 Merged r4742 from trunk.
scm: darcs: add unit lib test.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4745 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-23 04:02:15 +00:00
Jean-Philippe Lang 135fe04d02 Merged r4681 from trunk (missing fixtures breaking tests).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4732 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-16 16:39:19 +00:00
Jean-Philippe Lang 794d7c0959 Merged r4680 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4728 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-16 14:44:38 +00:00
Toshi MARUYAMA b8f365f2a1 Merged r4713 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4717 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-14 23:37:50 +00:00
Toshi MARUYAMA 6188b9eddb Merged r4710 and r4714 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4716 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-14 23:37:30 +00:00
Toshi MARUYAMA 96c4dc3f1e Merged r4712 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4715 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-14 23:37:10 +00:00
Toshi MARUYAMA b877215261 Merged r4703 from trunk (scm: fix error on revision page for empty revision).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4707 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-13 12:10:52 +00:00
Toshi MARUYAMA 788b143596 Merged r4665 from trunk.
scm: add compatible functional test fof changing diff revisions label at SCM adapter level.

git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4706 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-13 12:10:30 +00:00
Toshi MARUYAMA 6a261eb5a0 Merged r4691 from trunk (fix assert_equal parameter order in subversion and git unit test).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4693 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-11 15:28:23 +00:00
Toshi MARUYAMA 007fbc00cf Merged r4687 from trunk (fix setup mercurial test repository).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4689 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-11 08:46:27 +00:00
Toshi MARUYAMA 9b8b4b3bfc Merged r4683 from trunk (test:scm:setup:mercurial task can be simpler).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4685 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-11 04:22:52 +00:00
Toshi MARUYAMA 6734f91a72 Merged r4676 from trunk (change mercurial test repository from tar.gz to bundle).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4684 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-11 04:22:31 +00:00
Jean-Philippe Lang 5266346315 Set the version to stable (#7259).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4678 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-10 18:13:09 +00:00
Toshi MARUYAMA d426e4452b Merged r4644 and r4674 from trunk (mercurial unit app test).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4675 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-09 23:39:46 +00:00
Jean-Philippe Lang f8af1bebd7 Merged r4670 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4671 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-09 15:58:15 +00:00
Jean-Philippe Lang 6e695a4d1a Merged r4645 to r4651 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4660 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-08 10:14:00 +00:00
Jean-Philippe Lang e5b7c94cb4 Merged r4643 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4659 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-08 10:09:04 +00:00
Jean-Philippe Lang 9028e664c4 Merged r4656 and r4657 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4658 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-08 10:04:38 +00:00
Toshi MARUYAMA 6318affd31 Merged r4652 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4653 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-08 00:24:43 +00:00
Jean-Philippe Lang 8794cd3344 Merged r4610 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4649 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-06 21:04:24 +00:00
Toshi MARUYAMA 2fcd4e5271 Merged r4636 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4642 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-05 15:12:08 +00:00
Toshi MARUYAMA ea60705ca7 Merged r4635 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4641 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-05 15:11:47 +00:00
Toshi MARUYAMA 90bce4e366 Merged r4634 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4640 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-05 15:11:21 +00:00
Toshi MARUYAMA 9f7cc355ad Merged r4633 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4639 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-05 15:10:58 +00:00
Toshi MARUYAMA 6ee4c0bac7 Merged r4632 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4638 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-05 15:10:38 +00:00
Toshi MARUYAMA b0f0bd1848 Merged r4631 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4637 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-05 15:10:17 +00:00
Toshi MARUYAMA fe563a8802 Merged r4629 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4630 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-04 16:39:45 +00:00
Toshi MARUYAMA 8ebab00767 Merged r4625 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4628 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-03 10:55:07 +00:00
Toshi MARUYAMA d97297e45d Merged r4624 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4627 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-03 10:54:29 +00:00
Toshi MARUYAMA f06500dcce Merged r4623 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4626 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-03 10:53:47 +00:00
Jean-Philippe Lang b098e2b63f Merged r4621 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4622 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-02 14:37:55 +00:00
Jean-Philippe Lang 151a49b319 Merged r4618 and r4619 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4620 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-02 12:17:39 +00:00
Jean-Philippe Lang ded234794e Merged r4615 and r4616 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4617 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-02 11:44:19 +00:00
Toshi MARUYAMA 119732c3ee Merged r4613 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4614 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-02 09:52:29 +00:00
Toshi MARUYAMA 730fcef844 Merged r4611 from trunk (Mercurial sorting).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4612 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-02 06:14:59 +00:00
Toshi MARUYAMA 1cb33f3a95 Merged r4608 from trunk (repository: switch darcs cat test if cat supports).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4609 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-01 22:05:48 +00:00
Toshi MARUYAMA 69edd3c53f Merged r4606 from trunk (.hgignore).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4607 e93f8b46-1217-0410-a6f0-8f06a7374b81
2011-01-01 21:20:25 +00:00
Jean-Philippe Lang ad784e2146 Merged locales updates (r4592 to 4595) from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4596 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-12-30 15:54:47 +00:00
Jean-Philippe Lang c783ae4b3d 1.1-stable branch added
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/1.1-stable@4585 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-12-30 15:09:18 +00:00
556 changed files with 13325 additions and 43572 deletions
-3
View File
@@ -1,7 +1,6 @@
/.project /.project
/.loadpath /.loadpath
/config/additional_environment.rb /config/additional_environment.rb
/config/configuration.yml
/config/database.yml /config/database.yml
/config/email.yml /config/email.yml
/config/initializers/session_store.rb /config/initializers/session_store.rb
@@ -10,8 +9,6 @@
/db/*.sqlite3 /db/*.sqlite3
/db/schema.rb /db/schema.rb
/files/* /files/*
/lib/redmine/scm/adapters/mercurial/redminehelper.pyc
/lib/redmine/scm/adapters/mercurial/redminehelper.pyo
/log/*.log* /log/*.log*
/log/mongrel_debug /log/mongrel_debug
/public/dispatch.* /public/dispatch.*
-5
View File
@@ -3,7 +3,6 @@ syntax: glob
.project .project
.loadpath .loadpath
config/additional_environment.rb config/additional_environment.rb
config/configuration.yml
config/database.yml config/database.yml
config/email.yml config/email.yml
config/initializers/session_store.rb config/initializers/session_store.rb
@@ -12,8 +11,6 @@ db/*.db
db/*.sqlite3 db/*.sqlite3
db/schema.rb db/schema.rb
files/* files/*
lib/redmine/scm/adapters/mercurial/redminehelper.pyc
lib/redmine/scm/adapters/mercurial/redminehelper.pyo
log/*.log* log/*.log*
log/mongrel_debug log/mongrel_debug
public/dispatch.* public/dispatch.*
@@ -25,5 +22,3 @@ tmp/sockets/*
tmp/test/* tmp/test/*
vendor/rails vendor/rails
*.rbc *.rbc
.svn/
.git/
+2 -14
View File
@@ -203,24 +203,12 @@ class AccountController < ApplicationController
self.logged_user = user self.logged_user = user
# generate a key and set cookie if autologin # generate a key and set cookie if autologin
if params[:autologin] && Setting.autologin? if params[:autologin] && Setting.autologin?
set_autologin_cookie(user) token = Token.create(:user => user, :action => 'autologin')
cookies[:autologin] = { :value => token.value, :expires => 1.year.from_now }
end end
call_hook(:controller_account_success_authentication_after, {:user => user }) call_hook(:controller_account_success_authentication_after, {:user => user })
redirect_back_or_default :controller => 'my', :action => 'page' redirect_back_or_default :controller => 'my', :action => 'page'
end end
def set_autologin_cookie(user)
token = Token.create(:user => user, :action => 'autologin')
cookie_name = Redmine::Configuration['autologin_cookie_name'] || 'autologin'
cookie_options = {
:value => token.value,
:expires => 1.year.from_now,
:path => (Redmine::Configuration['autologin_cookie_path'] || '/'),
:secure => (Redmine::Configuration['autologin_cookie_secure'] ? true : false),
:httponly => true
}
cookies[cookie_name] = cookie_options
end
# Onthefly creation failed, display the registration form to fill/fix attributes # Onthefly creation failed, display the registration form to fill/fix attributes
def onthefly_creation_failed(user, auth_source_options = { }) def onthefly_creation_failed(user, auth_source_options = { })
+8 -24
View File
@@ -1,28 +1,11 @@
# Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class ActivitiesController < ApplicationController class ActivitiesController < ApplicationController
menu_item :activity menu_item :activity
before_filter :find_optional_project before_filter :find_optional_project
accept_rss_auth :index accept_key_auth :index
def index def index
@days = Setting.activity_days_default.to_i @days = Setting.activity_days_default.to_i
if params[:from] if params[:from]
begin; @date_to = params[:from].to_date + 1; rescue; end begin; @date_to = params[:from].to_date + 1; rescue; end
end end
@@ -31,18 +14,18 @@ class ActivitiesController < ApplicationController
@date_from = @date_to - @days @date_from = @date_to - @days
@with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1') @with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1')
@author = (params[:user_id].blank? ? nil : User.active.find(params[:user_id])) @author = (params[:user_id].blank? ? nil : User.active.find(params[:user_id]))
@activity = Redmine::Activity::Fetcher.new(User.current, :project => @project, @activity = Redmine::Activity::Fetcher.new(User.current, :project => @project,
:with_subprojects => @with_subprojects, :with_subprojects => @with_subprojects,
:author => @author) :author => @author)
@activity.scope_select {|t| !params["show_#{t}"].nil?} @activity.scope_select {|t| !params["show_#{t}"].nil?}
@activity.scope = (@author.nil? ? :default : :all) if @activity.scope.empty? @activity.scope = (@author.nil? ? :default : :all) if @activity.scope.empty?
events = @activity.events(@date_from, @date_to) events = @activity.events(@date_from, @date_to)
if events.empty? || stale?(:etag => [@activity.scope, @date_to, @date_from, @with_subprojects, @author, events.first, User.current, current_language]) if events.empty? || stale?(:etag => [@activity.scope, @date_to, @date_from, @with_subprojects, @author, events.first, User.current, current_language])
respond_to do |format| respond_to do |format|
format.html { format.html {
@events_by_day = events.group_by(&:event_date) @events_by_day = events.group_by(&:event_date)
render :layout => false if request.xhr? render :layout => false if request.xhr?
} }
@@ -57,7 +40,7 @@ class ActivitiesController < ApplicationController
} }
end end
end end
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
@@ -72,4 +55,5 @@ class ActivitiesController < ApplicationController
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
end end
+12 -10
View File
@@ -17,7 +17,9 @@
class AdminController < ApplicationController class AdminController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin before_filter :require_admin
helper :sort helper :sort
include SortHelper include SortHelper
@@ -28,20 +30,22 @@ class AdminController < ApplicationController
def projects def projects
@status = params[:status] ? params[:status].to_i : 1 @status = params[:status] ? params[:status].to_i : 1
c = ARCondition.new(@status == 0 ? "status <> 0" : ["status = ?", @status]) c = ARCondition.new(@status == 0 ? "status <> 0" : ["status = ?", @status])
unless params[:name].blank? unless params[:name].blank?
name = "%#{params[:name].strip.downcase}%" name = "%#{params[:name].strip.downcase}%"
c << ["LOWER(identifier) LIKE ? OR LOWER(name) LIKE ?", name, name] c << ["LOWER(identifier) LIKE ? OR LOWER(name) LIKE ?", name, name]
end end
@projects = Project.find :all, :order => 'lft', @projects = Project.find :all, :order => 'lft',
:conditions => c.conditions :conditions => c.conditions
render :action => "projects", :layout => false if request.xhr? render :action => "projects", :layout => false if request.xhr?
end end
def plugins def plugins
@plugins = Redmine::Plugin.all @plugins = Redmine::Plugin.all
end end
# Loads the default configuration # Loads the default configuration
# (roles, trackers, statuses, workflow, enumerations) # (roles, trackers, statuses, workflow, enumerations)
def default_configuration def default_configuration
@@ -55,7 +59,7 @@ class AdminController < ApplicationController
end end
redirect_to :action => 'index' redirect_to :action => 'index'
end end
def test_email def test_email
raise_delivery_errors = ActionMailer::Base.raise_delivery_errors raise_delivery_errors = ActionMailer::Base.raise_delivery_errors
# Force ActionMailer to raise delivery errors so we can catch it # Force ActionMailer to raise delivery errors so we can catch it
@@ -69,16 +73,14 @@ class AdminController < ApplicationController
ActionMailer::Base.raise_delivery_errors = raise_delivery_errors ActionMailer::Base.raise_delivery_errors = raise_delivery_errors
redirect_to :controller => 'settings', :action => 'edit', :tab => 'notifications' redirect_to :controller => 'settings', :action => 'edit', :tab => 'notifications'
end end
def info def info
@db_adapter_name = ActiveRecord::Base.connection.adapter_name @db_adapter_name = ActiveRecord::Base.connection.adapter_name
@checklist = [ @checklist = [
[:text_default_administrator_account_changed, [:text_default_administrator_account_changed, User.find(:first, :conditions => ["login=? and hashed_password=?", 'admin', User.hash_password('admin')]).nil?],
User.find(:first,
:conditions => ["login=? and hashed_password=?", 'admin', User.hash_password('admin')]).nil?],
[:text_file_repository_writable, File.writable?(Attachment.storage_path)], [:text_file_repository_writable, File.writable?(Attachment.storage_path)],
[:text_plugin_assets_writable, File.writable?(Engines.public_directory)], [:text_plugin_assets_writable, File.writable?(Engines.public_directory)],
[:text_rmagick_available, Object.const_defined?(:Magick)] [:text_rmagick_available, Object.const_defined?(:Magick)]
] ]
end end
end end
+41 -76
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -18,37 +18,34 @@
require 'uri' require 'uri'
require 'cgi' require 'cgi'
class Unauthorized < Exception; end
class ApplicationController < ActionController::Base class ApplicationController < ActionController::Base
include Redmine::I18n include Redmine::I18n
layout 'base' layout 'base'
exempt_from_layout 'builder', 'rsb' exempt_from_layout 'builder', 'rsb'
# Remove broken cookie after upgrade from 0.8.x (#4292) # Remove broken cookie after upgrade from 0.8.x (#4292)
# See https://rails.lighthouseapp.com/projects/8994/tickets/3360 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
# TODO: remove it when Rails is fixed # TODO: remove it when Rails is fixed
before_filter :delete_broken_cookies before_filter :delete_broken_cookies
def delete_broken_cookies def delete_broken_cookies
if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/ if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
cookies.delete '_redmine_session' cookies.delete '_redmine_session'
redirect_to home_path redirect_to home_path
return false return false
end end
end end
before_filter :user_setup, :check_if_login_required, :set_localization before_filter :user_setup, :check_if_login_required, :set_localization
filter_parameter_logging :password filter_parameter_logging :password
protect_from_forgery protect_from_forgery
rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
rescue_from ::Unauthorized, :with => :deny_access
include Redmine::Search::Controller include Redmine::Search::Controller
include Redmine::MenuManager::MenuController include Redmine::MenuManager::MenuController
helper Redmine::MenuManager::MenuHelper helper Redmine::MenuManager::MenuHelper
Redmine::Scm::Base.all.each do |scm| Redmine::Scm::Base.all.each do |scm|
require_dependency "repository/#{scm.underscore}" require_dependency "repository/#{scm.underscore}"
end end
@@ -59,7 +56,7 @@ class ApplicationController < ActionController::Base
# Find the current user # Find the current user
User.current = find_current_user User.current = find_current_user
end end
# Returns the current user or nil if no user is logged in # Returns the current user or nil if no user is logged in
# and starts a session if needed # and starts a session if needed
def find_current_user def find_current_user
@@ -71,11 +68,11 @@ class ApplicationController < ActionController::Base
user = User.try_to_autologin(cookies[:autologin]) user = User.try_to_autologin(cookies[:autologin])
session[:user_id] = user.id if user session[:user_id] = user.id if user
user user
elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth? elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action])
# RSS key authentication does not start a session # RSS key authentication does not start a session
User.find_by_rss_key(params[:key]) User.find_by_rss_key(params[:key])
elsif Setting.rest_api_enabled? && accept_api_auth? elsif Setting.rest_api_enabled? && api_request?
if (key = api_key_from_request) if (key = api_key_from_request) && accept_key_auth_actions.include?(params[:action])
# Use API key # Use API key
User.find_by_api_key(key) User.find_by_api_key(key)
else else
@@ -97,14 +94,14 @@ class ApplicationController < ActionController::Base
User.current = User.anonymous User.current = User.anonymous
end end
end end
# check if login is globally required to access the application # check if login is globally required to access the application
def check_if_login_required def check_if_login_required
# no check needed if user is already logged in # no check needed if user is already logged in
return true if User.current.logged? return true if User.current.logged?
require_login if Setting.login_required? require_login if Setting.login_required?
end end
def set_localization def set_localization
lang = nil lang = nil
if User.current.logged? if User.current.logged?
@@ -120,7 +117,7 @@ class ApplicationController < ActionController::Base
lang ||= Setting.default_language lang ||= Setting.default_language
set_language_if_valid(lang) set_language_if_valid(lang)
end end
def require_login def require_login
if !User.current.logged? if !User.current.logged?
# Extract only the basic url parameters on non-GET requests # Extract only the basic url parameters on non-GET requests
@@ -149,7 +146,7 @@ class ApplicationController < ActionController::Base
end end
true true
end end
def deny_access def deny_access
User.current.logged? ? render_403 : require_login User.current.logged? ? render_403 : require_login
end end
@@ -200,7 +197,7 @@ class ApplicationController < ActionController::Base
# Finds and sets @project based on @object.project # Finds and sets @project based on @object.project
def find_project_from_association def find_project_from_association
render_404 unless @object.present? render_404 unless @object.present?
@project = @object.project @project = @object.project
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
@@ -224,16 +221,12 @@ class ApplicationController < ActionController::Base
def find_issues def find_issues
@issues = Issue.find_all_by_id(params[:id] || params[:ids]) @issues = Issue.find_all_by_id(params[:id] || params[:ids])
raise ActiveRecord::RecordNotFound if @issues.empty? raise ActiveRecord::RecordNotFound if @issues.empty?
if @issues.detect {|issue| !issue.visible?}
deny_access
return
end
@projects = @issues.collect(&:project).compact.uniq @projects = @issues.collect(&:project).compact.uniq
@project = @projects.first if @projects.size == 1 @project = @projects.first if @projects.size == 1
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
# Check if project is unique before bulk operations # Check if project is unique before bulk operations
def check_project_uniqueness def check_project_uniqueness
unless @project unless @project
@@ -242,7 +235,7 @@ class ApplicationController < ActionController::Base
return false return false
end end
end end
# make sure that the user is a member of the project (or admin) if project is private # make sure that the user is a member of the project (or admin) if project is private
# used as a before_filter for actions that do not require any particular permission on the project # used as a before_filter for actions that do not require any particular permission on the project
def check_project_privacy def check_project_privacy
@@ -278,28 +271,27 @@ class ApplicationController < ActionController::Base
end end
end end
redirect_to default redirect_to default
false
end end
def render_403(options={}) def render_403(options={})
@project = nil @project = nil
render_error({:message => :notice_not_authorized, :status => 403}.merge(options)) render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
return false return false
end end
def render_404(options={}) def render_404(options={})
render_error({:message => :notice_file_not_found, :status => 404}.merge(options)) render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
return false return false
end end
# Renders an error response # Renders an error response
def render_error(arg) def render_error(arg)
arg = {:message => arg} unless arg.is_a?(Hash) arg = {:message => arg} unless arg.is_a?(Hash)
@message = arg[:message] @message = arg[:message]
@message = l(@message) if @message.is_a?(Symbol) @message = l(@message) if @message.is_a?(Symbol)
@status = arg[:status] || 500 @status = arg[:status] || 500
respond_to do |format| respond_to do |format|
format.html { format.html {
render :template => 'common/error', :layout => use_layout, :status => @status render :template => 'common/error', :layout => use_layout, :status => @status
@@ -317,15 +309,15 @@ class ApplicationController < ActionController::Base
def use_layout def use_layout
request.xhr? ? false : 'base' request.xhr? ? false : 'base'
end end
def invalid_authenticity_token def invalid_authenticity_token
if api_request? if api_request?
logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)." logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
end end
render_error "Invalid form authenticity token." render_error "Invalid form authenticity token."
end end
def render_feed(items, options={}) def render_feed(items, options={})
@items = items || [] @items = items || []
@items.sort! {|x,y| y.event_datetime <=> x.event_datetime } @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
@items = @items.slice(0, Setting.feeds_limit.to_i) @items = @items.slice(0, Setting.feeds_limit.to_i)
@@ -333,42 +325,15 @@ class ApplicationController < ActionController::Base
render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml' render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
end end
# TODO: remove in Redmine 1.4
def self.accept_key_auth(*actions) def self.accept_key_auth(*actions)
ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead." actions = actions.flatten.map(&:to_s)
accept_rss_auth(*actions) write_inheritable_attribute('accept_key_auth_actions', actions)
end end
# TODO: remove in Redmine 1.4
def accept_key_auth_actions def accept_key_auth_actions
ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth_actions is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead." self.class.read_inheritable_attribute('accept_key_auth_actions') || []
self.class.accept_rss_auth
end end
def self.accept_rss_auth(*actions)
if actions.any?
write_inheritable_attribute('accept_rss_auth_actions', actions)
else
read_inheritable_attribute('accept_rss_auth_actions') || []
end
end
def accept_rss_auth?(action=action_name)
self.class.accept_rss_auth.include?(action.to_sym)
end
def self.accept_api_auth(*actions)
if actions.any?
write_inheritable_attribute('accept_api_auth_actions', actions)
else
read_inheritable_attribute('accept_api_auth_actions') || []
end
end
def accept_api_auth?(action=action_name)
self.class.accept_api_auth.include?(action.to_sym)
end
# Returns the number of objects that should be displayed # Returns the number of objects that should be displayed
# on the paginated list # on the paginated list
def per_page_option def per_page_option
@@ -404,10 +369,10 @@ class ApplicationController < ActionController::Base
offset = 0 if offset < 0 offset = 0 if offset < 0
end end
offset ||= 0 offset ||= 0
[offset, limit] [offset, limit]
end end
# qvalues http header parser # qvalues http header parser
# code taken from webrick # code taken from webrick
def parse_qvalues(value) def parse_qvalues(value)
@@ -428,16 +393,16 @@ class ApplicationController < ActionController::Base
rescue rescue
nil nil
end end
# Returns a string that can be used as filename value in Content-Disposition header # Returns a string that can be used as filename value in Content-Disposition header
def filename_for_content_disposition(name) def filename_for_content_disposition(name)
request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
end end
def api_request? def api_request?
%w(xml json).include? params[:format] %w(xml json).include? params[:format]
end end
# Returns the API key present in the request # Returns the API key present in the request
def api_key_from_request def api_key_from_request
if params[:key].present? if params[:key].present?
@@ -494,7 +459,7 @@ class ApplicationController < ActionController::Base
) )
render options render options
end end
# Overrides #default_template so that the api template # Overrides #default_template so that the api template
# is used automatically if it exists # is used automatically if it exists
def default_template(action_name = self.action_name) def default_template(action_name = self.action_name)
@@ -508,7 +473,7 @@ class ApplicationController < ActionController::Base
end end
super super
end end
# Overrides #pick_layout so that #render with no arguments # Overrides #pick_layout so that #render with no arguments
# doesn't use the layout for api requests # doesn't use the layout for api requests
def pick_layout(*args) def pick_layout(*args)
+15 -15
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2008 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -19,9 +19,9 @@ class AttachmentsController < ApplicationController
before_filter :find_project before_filter :find_project
before_filter :file_readable, :read_authorize, :except => :destroy before_filter :file_readable, :read_authorize, :except => :destroy
before_filter :delete_authorize, :only => :destroy before_filter :delete_authorize, :only => :destroy
verify :method => :post, :only => :destroy verify :method => :post, :only => :destroy
def show def show
if @attachment.is_diff? if @attachment.is_diff?
@diff = File.new(@attachment.diskfile, "rb").read @diff = File.new(@attachment.diskfile, "rb").read
@@ -33,19 +33,19 @@ class AttachmentsController < ApplicationController
download download
end end
end end
def download def download
if @attachment.container.is_a?(Version) || @attachment.container.is_a?(Project) if @attachment.container.is_a?(Version) || @attachment.container.is_a?(Project)
@attachment.increment_download @attachment.increment_download
end end
# images are sent inline # images are sent inline
send_file @attachment.diskfile, :filename => filename_for_content_disposition(@attachment.filename), send_file @attachment.diskfile, :filename => filename_for_content_disposition(@attachment.filename),
:type => detect_content_type(@attachment), :type => detect_content_type(@attachment),
:disposition => (@attachment.image? ? 'inline' : 'attachment') :disposition => (@attachment.image? ? 'inline' : 'attachment')
end end
def destroy def destroy
# Make sure association callbacks are called # Make sure association callbacks are called
@attachment.container.attachments.delete(@attachment) @attachment.container.attachments.delete(@attachment)
@@ -53,7 +53,7 @@ class AttachmentsController < ApplicationController
rescue ::ActionController::RedirectBackError rescue ::ActionController::RedirectBackError
redirect_to :controller => 'projects', :action => 'show', :id => @project redirect_to :controller => 'projects', :action => 'show', :id => @project
end end
private private
def find_project def find_project
@attachment = Attachment.find(params[:id]) @attachment = Attachment.find(params[:id])
@@ -63,20 +63,20 @@ private
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
# Checks that the file exists and is readable # Checks that the file exists and is readable
def file_readable def file_readable
@attachment.readable? ? true : render_404 @attachment.readable? ? true : render_404
end end
def read_authorize def read_authorize
@attachment.visible? ? true : deny_access @attachment.visible? ? true : deny_access
end end
def delete_authorize def delete_authorize
@attachment.deletable? ? true : deny_access @attachment.deletable? ? true : deny_access
end end
def detect_content_type(attachment) def detect_content_type(attachment)
content_type = attachment.content_type content_type = attachment.content_type
if content_type.blank? if content_type.blank?
+3 -3
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -18,7 +18,7 @@
class BoardsController < ApplicationController class BoardsController < ApplicationController
default_search_scope :messages default_search_scope :messages
before_filter :find_project, :find_board_if_available, :authorize before_filter :find_project, :find_board_if_available, :authorize
accept_rss_auth :index, :show accept_key_auth :index, :show
helper :messages helper :messages
include MessagesHelper include MessagesHelper
+5 -17
View File
@@ -1,20 +1,3 @@
# Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class CalendarsController < ApplicationController class CalendarsController < ApplicationController
menu_item :calendar menu_item :calendar
before_filter :find_optional_project before_filter :find_optional_project
@@ -53,4 +36,9 @@ class CalendarsController < ApplicationController
render :action => 'show', :layout => false if request.xhr? render :action => 'show', :layout => false if request.xhr?
end end
def update
show
end
end end
+1 -15
View File
@@ -1,6 +1,5 @@
class ContextMenusController < ApplicationController class ContextMenusController < ApplicationController
helper :watchers helper :watchers
helper :issues
def issues def issues
@issues = Issue.visible.all(:conditions => {:id => params[:ids]}, :include => :project) @issues = Issue.visible.all(:conditions => {:id => params[:ids]}, :include => :project)
@@ -41,18 +40,5 @@ class ContextMenusController < ApplicationController
render :layout => false render :layout => false
end end
def time_entries
@time_entries = TimeEntry.all(
:conditions => {:id => params[:ids]}, :include => :project)
@projects = @time_entries.collect(&:project).compact.uniq
@project = @projects.first if @projects.size == 1
@activities = TimeEntryActivity.shared.active
@can = {:edit => User.current.allowed_to?(:log_time, @projects),
:update => User.current.allowed_to?(:log_time, @projects),
:delete => User.current.allowed_to?(:log_time, @projects)
}
@back = back_url
render :layout => false
end
end end
+2 -4
View File
@@ -38,9 +38,8 @@ class CustomFieldsController < ApplicationController
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
call_hook(:controller_custom_fields_new_after_save, :params => params, :custom_field => @custom_field) call_hook(:controller_custom_fields_new_after_save, :params => params, :custom_field => @custom_field)
redirect_to :action => 'index', :tab => @custom_field.class.name redirect_to :action => 'index', :tab => @custom_field.class.name
else
@trackers = Tracker.find(:all, :order => 'position')
end end
@trackers = Tracker.find(:all, :order => 'position')
end end
def edit def edit
@@ -49,9 +48,8 @@ class CustomFieldsController < ApplicationController
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
call_hook(:controller_custom_fields_edit_after_save, :params => params, :custom_field => @custom_field) call_hook(:controller_custom_fields_edit_after_save, :params => params, :custom_field => @custom_field)
redirect_to :action => 'index', :tab => @custom_field.class.name redirect_to :action => 'index', :tab => @custom_field.class.name
else
@trackers = Tracker.find(:all, :order => 'position')
end end
@trackers = Tracker.find(:all, :order => 'position')
end end
def destroy def destroy
@@ -75,12 +75,10 @@ class EnumerationsController < ApplicationController
# No associated objects # No associated objects
@enumeration.destroy @enumeration.destroy
redirect_to :action => 'index' redirect_to :action => 'index'
return
elsif params[:reassign_to_id] elsif params[:reassign_to_id]
if reassign_to = @enumeration.class.find_by_id(params[:reassign_to_id]) if reassign_to = @enumeration.class.find_by_id(params[:reassign_to_id])
@enumeration.destroy(reassign_to) @enumeration.destroy(reassign_to)
redirect_to :action => 'index' redirect_to :action => 'index'
return
end end
end end
@enumerations = @enumeration.class.find(:all) - [@enumeration] @enumerations = @enumeration.class.find(:all) - [@enumeration]
+1 -1
View File
@@ -13,7 +13,7 @@ class FilesController < ApplicationController
'created_on' => "#{Attachment.table_name}.created_on", 'created_on' => "#{Attachment.table_name}.created_on",
'size' => "#{Attachment.table_name}.filesize", 'size' => "#{Attachment.table_name}.filesize",
'downloads' => "#{Attachment.table_name}.downloads" 'downloads' => "#{Attachment.table_name}.downloads"
@containers = [ Project.find(@project.id, :include => :attachments, :order => sort_clause)] @containers = [ Project.find(@project.id, :include => :attachments, :order => sort_clause)]
@containers += @project.versions.find(:all, :include => :attachments, :order => sort_clause).sort.reverse @containers += @project.versions.find(:all, :include => :attachments, :order => sort_clause).sort.reverse
render :layout => !request.xhr? render :layout => !request.xhr?
+5 -17
View File
@@ -1,20 +1,3 @@
# Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class GanttsController < ApplicationController class GanttsController < ApplicationController
menu_item :gantt menu_item :gantt
before_filter :find_optional_project before_filter :find_optional_project
@@ -45,4 +28,9 @@ class GanttsController < ApplicationController
format.pdf { send_data(@gantt.to_pdf, :type => 'application/pdf', :filename => "#{basename}.pdf") } format.pdf { send_data(@gantt.to_pdf, :type => 'application/pdf', :filename => "#{basename}.pdf") }
end end
end end
def update
show
end
end end
+1 -1
View File
@@ -132,7 +132,7 @@ class GroupsController < ApplicationController
def autocomplete_for_user def autocomplete_for_user
@group = Group.find(params[:id]) @group = Group.find(params[:id])
@users = User.active.not_in_group(@group).like(params[:q]).all(:limit => 100) @users = User.active.like(params[:q]).find(:all, :limit => 100) - @group.users
render :layout => false render :layout => false
end end
@@ -65,12 +65,10 @@ class IssueCategoriesController < ApplicationController
# No issue assigned to this category # No issue assigned to this category
@category.destroy @category.destroy
redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'categories' redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'categories'
return
elsif params[:todo] elsif params[:todo]
reassign_to = @project.issue_categories.find_by_id(params[:reassign_to_id]) if params[:todo] == 'reassign' reassign_to = @project.issue_categories.find_by_id(params[:reassign_to_id]) if params[:todo] == 'reassign'
@category.destroy(reassign_to) @category.destroy(reassign_to)
redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'categories' redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'categories'
return
end end
@categories = @project.issue_categories - [@category] @categories = @project.issue_categories - [@category]
end end
+2 -2
View File
@@ -2,7 +2,7 @@ class IssueMovesController < ApplicationController
default_search_scope :issues default_search_scope :issues
before_filter :find_issues, :check_project_uniqueness before_filter :find_issues, :check_project_uniqueness
before_filter :authorize before_filter :authorize
def new def new
prepare_for_issue_move prepare_for_issue_move
render :layout => false if request.xhr? render :layout => false if request.xhr?
@@ -48,7 +48,7 @@ class IssueMovesController < ApplicationController
@copy = params[:copy_options] && params[:copy_options][:copy] @copy = params[:copy_options] && params[:copy_options][:copy]
@allowed_projects = Issue.allowed_target_projects_on_move @allowed_projects = Issue.allowed_target_projects_on_move
@target_project = @allowed_projects.detect {|p| p.id.to_s == params[:new_project_id]} if params[:new_project_id] @target_project = @allowed_projects.detect {|p| p.id.to_s == params[:new_project_id]} if params[:new_project_id]
@target_project ||= @project @target_project ||= @project
@trackers = @target_project.trackers @trackers = @target_project.trackers
@available_statuses = Workflow.available_statuses(@project) @available_statuses = Workflow.available_statuses(@project)
@notes = params[:notes] @notes = params[:notes]
@@ -1,4 +1,4 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2007 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
+25 -36
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2008 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -18,7 +18,7 @@
class IssuesController < ApplicationController class IssuesController < ApplicationController
menu_item :new_issue, :only => [:new, :create] menu_item :new_issue, :only => [:new, :create]
default_search_scope :issues default_search_scope :issues
before_filter :find_issue, :only => [:show, :edit, :update] before_filter :find_issue, :only => [:show, :edit, :update]
before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :move, :perform_move, :destroy] before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :move, :perform_move, :destroy]
before_filter :check_project_uniqueness, :only => [:move, :perform_move] before_filter :check_project_uniqueness, :only => [:move, :perform_move]
@@ -27,14 +27,13 @@ class IssuesController < ApplicationController
before_filter :find_optional_project, :only => [:index] before_filter :find_optional_project, :only => [:index]
before_filter :check_for_default_issue_status, :only => [:new, :create] before_filter :check_for_default_issue_status, :only => [:new, :create]
before_filter :build_new_issue_from_params, :only => [:new, :create] before_filter :build_new_issue_from_params, :only => [:new, :create]
accept_rss_auth :index, :show accept_key_auth :index, :show, :create, :update, :destroy
accept_api_auth :index, :show, :create, :update, :destroy
rescue_from Query::StatementInvalid, :with => :query_statement_invalid rescue_from Query::StatementInvalid, :with => :query_statement_invalid
helper :journals helper :journals
helper :projects helper :projects
include ProjectsHelper include ProjectsHelper
helper :custom_fields helper :custom_fields
include CustomFieldsHelper include CustomFieldsHelper
helper :issue_relations helper :issue_relations
@@ -61,12 +60,12 @@ class IssuesController < ApplicationController
verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed } verify :method => :post, :only => :create, :render => {:nothing => true, :status => :method_not_allowed }
verify :method => :post, :only => :bulk_update, :render => {:nothing => true, :status => :method_not_allowed } verify :method => :post, :only => :bulk_update, :render => {:nothing => true, :status => :method_not_allowed }
verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed } verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
def index def index
retrieve_query retrieve_query
sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria) sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
sort_update(@query.sortable_columns) sort_update(@query.sortable_columns)
if @query.valid? if @query.valid?
case params[:format] case params[:format]
when 'csv', 'pdf' when 'csv', 'pdf'
@@ -78,16 +77,16 @@ class IssuesController < ApplicationController
else else
@limit = per_page_option @limit = per_page_option
end end
@issue_count = @query.issue_count @issue_count = @query.issue_count
@issue_pages = Paginator.new self, @issue_count, @limit, params['page'] @issue_pages = Paginator.new self, @issue_count, @limit, params['page']
@offset ||= @issue_pages.current.offset @offset ||= @issue_pages.current.offset
@issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version], @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],
:order => sort_clause, :order => sort_clause,
:offset => @offset, :offset => @offset,
:limit => @limit) :limit => @limit)
@issue_count_by_group = @query.issue_count_by_group @issue_count_by_group = @query.issue_count_by_group
respond_to do |format| respond_to do |format|
format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? } format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? }
format.api format.api
@@ -102,22 +101,18 @@ class IssuesController < ApplicationController
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
def show def show
@journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC") @journals = @issue.journals.find(:all, :include => [:user, :details], :order => "#{Journal.table_name}.created_on ASC")
@journals.each_with_index {|j,i| j.indice = i+1} @journals.each_with_index {|j,i| j.indice = i+1}
@journals.reverse! if User.current.wants_comments_in_reverse_order? @journals.reverse! if User.current.wants_comments_in_reverse_order?
@changesets = @issue.changesets.visible.all
if User.current.allowed_to?(:view_changesets, @project) @changesets.reverse! if User.current.wants_comments_in_reverse_order?
@changesets = @issue.changesets.visible.all
@changesets.reverse! if User.current.wants_comments_in_reverse_order?
end
@relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? } @relations = @issue.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? }
@allowed_statuses = @issue.new_statuses_allowed_to(User.current) @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
@edit_allowed = User.current.allowed_to?(:edit_issues, @project) @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
@priorities = IssuePriority.all @priorities = IssuePriority.all
@time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project) @time_entry = TimeEntry.new
respond_to do |format| respond_to do |format|
format.html { render :template => 'issues/show.rhtml' } format.html { render :template => 'issues/show.rhtml' }
format.api format.api
@@ -157,7 +152,7 @@ class IssuesController < ApplicationController
end end
end end
end end
def edit def edit
update_issue_from_params update_issue_from_params
@@ -219,7 +214,7 @@ class IssuesController < ApplicationController
set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids) set_flash_from_bulk_issue_save(@issues, unsaved_issue_ids)
redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project}) redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
end end
def destroy def destroy
@hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
if @hours > 0 if @hours > 0
@@ -256,25 +251,19 @@ class IssuesController < ApplicationController
private private
def find_issue def find_issue
# Issue.visible.find(...) can not be used to redirect user to the login form
# if the issue actually exists but requires authentication
@issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category]) @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
unless @issue.visible?
deny_access
return
end
@project = @issue.project @project = @issue.project
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
def find_project def find_project
project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id] project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id]
@project = Project.find(project_id) @project = Project.find(project_id)
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
# Used by #edit and #update to set some common instance variables # Used by #edit and #update to set some common instance variables
# from the params # from the params
# TODO: Refactor, not everything in here is needed by #edit # TODO: Refactor, not everything in here is needed by #edit
@@ -282,9 +271,9 @@ private
@allowed_statuses = @issue.new_statuses_allowed_to(User.current) @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
@priorities = IssuePriority.all @priorities = IssuePriority.all
@edit_allowed = User.current.allowed_to?(:edit_issues, @project) @edit_allowed = User.current.allowed_to?(:edit_issues, @project)
@time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project) @time_entry = TimeEntry.new
@time_entry.attributes = params[:time_entry] @time_entry.attributes = params[:time_entry]
@notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil) @notes = params[:notes] || (params[:issue].present? ? params[:issue][:notes] : nil)
@issue.init_journal(User.current, @notes) @issue.init_journal(User.current, @notes)
@issue.safe_attributes = params[:issue] @issue.safe_attributes = params[:issue]
@@ -300,9 +289,8 @@ private
else else
@issue = @project.issues.visible.find(params[:id]) @issue = @project.issues.visible.find(params[:id])
end end
@issue.project = @project @issue.project = @project
@issue.author = User.current
# Tracker must be set before custom field values # Tracker must be set before custom field values
@issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first) @issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
if @issue.tracker.nil? if @issue.tracker.nil?
@@ -316,6 +304,7 @@ private
@issue.watcher_user_ids = params[:issue]['watcher_user_ids'] @issue.watcher_user_ids = params[:issue]['watcher_user_ids']
end end
end end
@issue.author = User.current
@priorities = IssuePriority.all @priorities = IssuePriority.all
@allowed_statuses = @issue.new_statuses_allowed_to(User.current, true) @allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
end end
+8 -21
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2008 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -16,13 +16,12 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class JournalsController < ApplicationController class JournalsController < ApplicationController
before_filter :find_journal, :only => [:edit, :diff] before_filter :find_journal, :only => [:edit]
before_filter :find_issue, :only => [:new] before_filter :find_issue, :only => [:new]
before_filter :find_optional_project, :only => [:index] before_filter :find_optional_project, :only => [:index]
before_filter :authorize, :only => [:new, :edit, :diff] before_filter :authorize, :only => [:new, :edit]
accept_rss_auth :index accept_key_auth :index
menu_item :issues
helper :issues helper :issues
helper :custom_fields helper :custom_fields
helper :queries helper :queries
@@ -45,17 +44,6 @@ class JournalsController < ApplicationController
render_404 render_404
end end
def diff
@issue = @journal.issue
if params[:detail_id].present?
@detail = @journal.details.find_by_id(params[:detail_id])
else
@detail = @journal.details.detect {|d| d.prop_key == 'description'}
end
(render_404; return false) unless @issue && @detail
@diff = Redmine::Helpers::Diff.new(@detail.value, @detail.old_value)
end
def new def new
journal = Journal.find(params[:journal_id]) if params[:journal_id] journal = Journal.find(params[:journal_id]) if params[:journal_id]
if journal if journal
@@ -80,7 +68,6 @@ class JournalsController < ApplicationController
end end
def edit def edit
(render_403; return false) unless @journal.editable_by?(User.current)
if request.post? if request.post?
@journal.update_attributes(:notes => params[:notes]) if params[:notes] @journal.update_attributes(:notes => params[:notes]) if params[:notes]
@journal.destroy if @journal.details.empty? && @journal.notes.blank? @journal.destroy if @journal.details.empty? && @journal.notes.blank?
@@ -100,10 +87,10 @@ class JournalsController < ApplicationController
end end
end end
private private
def find_journal def find_journal
@journal = Journal.find(params[:id]) @journal = Journal.find(params[:id])
(render_403; return false) unless @journal.editable_by?(User.current)
@project = @journal.journalized.project @project = @journal.journalized.project
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
+8 -8
View File
@@ -1,27 +1,27 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2008 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class MailHandlerController < ActionController::Base class MailHandlerController < ActionController::Base
before_filter :check_credential before_filter :check_credential
verify :method => :post, verify :method => :post,
:only => :index, :only => :index,
:render => { :nothing => true, :status => 405 } :render => { :nothing => true, :status => 405 }
# Submits an incoming email to MailHandler # Submits an incoming email to MailHandler
def index def index
options = params.dup options = params.dup
@@ -32,9 +32,9 @@ class MailHandlerController < ActionController::Base
render :nothing => true, :status => :unprocessable_entity render :nothing => true, :status => :unprocessable_entity
end end
end end
private private
def check_credential def check_credential
User.current = nil User.current = nil
unless Setting.mail_handler_api_enabled? && params[:key].to_s == Setting.mail_handler_api_key unless Setting.mail_handler_api_enabled? && params[:key].to_s == Setting.mail_handler_api_key
+3 -6
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -23,10 +23,7 @@ class NewsController < ApplicationController
before_filter :find_project, :only => [:new, :create] before_filter :find_project, :only => [:new, :create]
before_filter :authorize, :except => [:index] before_filter :authorize, :except => [:index]
before_filter :find_optional_project, :only => :index before_filter :find_optional_project, :only => :index
accept_rss_auth :index accept_key_auth :index
accept_api_auth :index
helper :watchers
def index def index
case params[:format] case params[:format]
-17
View File
@@ -1,20 +1,3 @@
# Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class PreviewsController < ApplicationController class PreviewsController < ApplicationController
before_filter :find_project before_filter :find_project
+7 -7
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2009 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -24,8 +24,7 @@ class ProjectsController < ApplicationController
before_filter :authorize, :except => [ :index, :list, :new, :create, :copy, :archive, :unarchive, :destroy] before_filter :authorize, :except => [ :index, :list, :new, :create, :copy, :archive, :unarchive, :destroy]
before_filter :authorize_global, :only => [:new, :create] before_filter :authorize_global, :only => [:new, :create]
before_filter :require_admin, :only => [ :copy, :archive, :unarchive, :destroy ] before_filter :require_admin, :only => [ :copy, :archive, :unarchive, :destroy ]
accept_rss_auth :index accept_key_auth :index, :show, :create, :update, :destroy
accept_api_auth :index, :show, :create, :update, :destroy
after_filter :only => [:create, :edit, :update, :archive, :unarchive, :destroy] do |controller| after_filter :only => [:create, :edit, :update, :archive, :unarchive, :destroy] do |controller|
if controller.request.post? if controller.request.post?
@@ -143,7 +142,7 @@ class ProjectsController < ApplicationController
end end
@users_by_role = @project.users_by_role @users_by_role = @project.users_by_role
@subprojects = @project.children.visible.all @subprojects = @project.children.visible
@news = @project.news.find(:all, :limit => 5, :include => [ :author, :project ], :order => "#{News.table_name}.created_on DESC") @news = @project.news.find(:all, :limit => 5, :include => [ :author, :project ], :order => "#{News.table_name}.created_on DESC")
@trackers = @project.rolled_up_trackers @trackers = @project.rolled_up_trackers
@@ -156,10 +155,11 @@ class ProjectsController < ApplicationController
:include => [:project, :status, :tracker], :include => [:project, :status, :tracker],
:conditions => cond) :conditions => cond)
if User.current.allowed_to?(:view_time_entries, @project) TimeEntry.visible_by(User.current) do
@total_hours = TimeEntry.visible.sum(:hours, :include => :project, :conditions => cond).to_f @total_hours = TimeEntry.sum(:hours,
:include => :project,
:conditions => cond).to_f
end end
@key = User.current.rss_key @key = User.current.rss_key
respond_to do |format| respond_to do |format|
+4 -7
View File
@@ -25,12 +25,11 @@ class QueriesController < ApplicationController
@query.project = params[:query_is_for_all] ? nil : @project @query.project = params[:query_is_for_all] ? nil : @project
@query.user = User.current @query.user = User.current
@query.is_public = false unless User.current.allowed_to?(:manage_public_queries, @project) || User.current.admin? @query.is_public = false unless User.current.allowed_to?(:manage_public_queries, @project) || User.current.admin?
@query.add_filters(params[:fields] || params[:f], params[:operators] || params[:op], params[:values] || params[:v]) if params[:fields] || params[:f]
@query.group_by ||= params[:group_by]
@query.column_names = params[:c] if params[:c]
@query.column_names = nil if params[:default_columns] @query.column_names = nil if params[:default_columns]
@query.add_filters(params[:fields], params[:operators], params[:values]) if params[:fields]
@query.group_by ||= params[:group_by]
if request.post? && params[:confirm] && @query.save if request.post? && params[:confirm] && @query.save
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to :controller => 'issues', :action => 'index', :project_id => @project, :query_id => @query redirect_to :controller => 'issues', :action => 'index', :project_id => @project, :query_id => @query
@@ -42,12 +41,10 @@ class QueriesController < ApplicationController
def edit def edit
if request.post? if request.post?
@query.filters = {} @query.filters = {}
@query.add_filters(params[:fields] || params[:f], params[:operators] || params[:op], params[:values] || params[:v]) if params[:fields] || params[:f] @query.add_filters(params[:fields], params[:operators], params[:values]) if params[:fields]
@query.attributes = params[:query] @query.attributes = params[:query]
@query.project = nil if params[:query_is_for_all] @query.project = nil if params[:query_is_for_all]
@query.is_public = false unless User.current.allowed_to?(:manage_public_queries, @project) || User.current.admin? @query.is_public = false unless User.current.allowed_to?(:manage_public_queries, @project) || User.current.admin?
@query.group_by ||= params[:group_by]
@query.column_names = params[:c] if params[:c]
@query.column_names = nil if params[:default_columns] @query.column_names = nil if params[:default_columns]
if @query.save if @query.save
+58 -97
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2009 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -26,45 +26,33 @@ class RepositoriesController < ApplicationController
menu_item :repository menu_item :repository
menu_item :settings, :only => :edit menu_item :settings, :only => :edit
default_search_scope :changesets default_search_scope :changesets
before_filter :find_repository, :except => :edit before_filter :find_repository, :except => :edit
before_filter :find_project, :only => :edit before_filter :find_project, :only => :edit
before_filter :authorize before_filter :authorize
accept_rss_auth :revisions accept_key_auth :revisions
rescue_from Redmine::Scm::Adapters::CommandFailed, :with => :show_error_command_failed rescue_from Redmine::Scm::Adapters::CommandFailed, :with => :show_error_command_failed
def edit def edit
@repository = @project.repository @repository = @project.repository
if !@repository && !params[:repository_scm].blank? if !@repository
@repository = Repository.factory(params[:repository_scm]) @repository = Repository.factory(params[:repository_scm])
@repository.project = @project if @repository @repository.project = @project if @repository
end end
if request.post? && @repository if request.post? && @repository
p1 = params[:repository] @repository.attributes = params[:repository]
p = {}
p_extra = {}
p1.each do |k, v|
if k =~ /^extra_/
p_extra[k] = v
else
p[k] = v
end
end
@repository.attributes = p
@repository.merge_extra_info(p_extra)
@repository.save @repository.save
end end
render(:update) do |page| render(:update) do |page|
page.replace_html "tab-content-repository", page.replace_html "tab-content-repository", :partial => 'projects/settings/repository'
:partial => 'projects/settings/repository'
if @repository && !@project.repository if @repository && !@project.repository
@project.reload # needed to reload association @project.reload #needed to reload association
page.replace_html "main-menu", render_main_menu(@project) page.replace_html "main-menu", render_main_menu(@project)
end end
end end
end end
def committers def committers
@committers = @repository.committers @committers = @repository.committers
@users = @project.users @users = @project.users
@@ -79,20 +67,16 @@ class RepositoriesController < ApplicationController
redirect_to :action => 'committers', :id => @project redirect_to :action => 'committers', :id => @project
end end
end end
def destroy def destroy
@repository.destroy @repository.destroy
redirect_to :controller => 'projects', redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'repository'
:action => 'settings',
:id => @project,
:tab => 'repository'
end end
def show def show
@repository.fetch_changesets if Setting.autofetch_changesets? && @path.empty? @repository.fetch_changesets if Setting.autofetch_changesets? && @path.empty?
@entries = @repository.entries(@path, @rev) @entries = @repository.entries(@path, @rev)
@changeset = @repository.find_changeset_by_name(@rev)
if request.xhr? if request.xhr?
@entries ? render(:partial => 'dir_list_content') : render(:nothing => true) @entries ? render(:partial => 'dir_list_content') : render(:nothing => true)
else else
@@ -104,31 +88,30 @@ class RepositoriesController < ApplicationController
end end
alias_method :browse, :show alias_method :browse, :show
def changes def changes
@entry = @repository.entry(@path, @rev) @entry = @repository.entry(@path, @rev)
(show_error_not_found; return) unless @entry (show_error_not_found; return) unless @entry
@changesets = @repository.latest_changesets(@path, @rev, Setting.repository_log_display_limit.to_i) @changesets = @repository.latest_changesets(@path, @rev, Setting.repository_log_display_limit.to_i)
@properties = @repository.properties(@path, @rev) @properties = @repository.properties(@path, @rev)
@changeset = @repository.find_changeset_by_name(@rev)
end end
def revisions def revisions
@changeset_count = @repository.changesets.count @changeset_count = @repository.changesets.count
@changeset_pages = Paginator.new self, @changeset_count, @changeset_pages = Paginator.new self, @changeset_count,
per_page_option, per_page_option,
params['page'] params['page']
@changesets = @repository.changesets.find(:all, @changesets = @repository.changesets.find(:all,
:limit => @changeset_pages.items_per_page, :limit => @changeset_pages.items_per_page,
:offset => @changeset_pages.current.offset, :offset => @changeset_pages.current.offset,
:include => [:user, :repository]) :include => [:user, :repository])
respond_to do |format| respond_to do |format|
format.html { render :layout => false if request.xhr? } format.html { render :layout => false if request.xhr? }
format.atom { render_feed(@changesets, :title => "#{@project.name}: #{l(:label_revision_plural)}") } format.atom { render_feed(@changesets, :title => "#{@project.name}: #{l(:label_revision_plural)}") }
end end
end end
def entry def entry
@entry = @repository.entry(@path, @rev) @entry = @repository.entry(@path, @rev)
(show_error_not_found; return) unless @entry (show_error_not_found; return) unless @entry
@@ -138,46 +121,25 @@ class RepositoriesController < ApplicationController
@content = @repository.cat(@path, @rev) @content = @repository.cat(@path, @rev)
(show_error_not_found; return) unless @content (show_error_not_found; return) unless @content
if 'raw' == params[:format] || if 'raw' == params[:format] || @content.is_binary_data? || (@entry.size && @entry.size > Setting.file_max_size_displayed.to_i.kilobyte)
(@content.size && @content.size > Setting.file_max_size_displayed.to_i.kilobyte) ||
! is_entry_text_data?(@content, @path)
# Force the download # Force the download
send_opt = { :filename => filename_for_content_disposition(@path.split('/').last) } send_data @content, :filename => filename_for_content_disposition(@path.split('/').last)
send_type = Redmine::MimeType.of(@path)
send_opt[:type] = send_type.to_s if send_type
send_data @content, send_opt
else else
# Prevent empty lines when displaying a file with Windows style eol # Prevent empty lines when displaying a file with Windows style eol
# TODO: UTF-16
# Is this needs? AttachmentsController reads file simply.
@content.gsub!("\r\n", "\n") @content.gsub!("\r\n", "\n")
@changeset = @repository.find_changeset_by_name(@rev) end
end
end end
def is_entry_text_data?(ent, path)
# UTF-16 contains "\x00".
# It is very strict that file contains less than 30% of ascii symbols
# in non Western Europe.
return true if Redmine::MimeType.is_type?('text', path)
# Ruby 1.8.6 has a bug of integer divisions.
# http://apidock.com/ruby/v1_8_6_287/String/is_binary_data%3F
return false if ent.is_binary_data?
true
end
private :is_entry_text_data?
def annotate def annotate
@entry = @repository.entry(@path, @rev) @entry = @repository.entry(@path, @rev)
(show_error_not_found; return) unless @entry (show_error_not_found; return) unless @entry
@annotate = @repository.scm.annotate(@path, @rev) @annotate = @repository.scm.annotate(@path, @rev)
(render_error l(:error_scm_annotate); return) if @annotate.nil? || @annotate.empty? (render_error l(:error_scm_annotate); return) if @annotate.nil? || @annotate.empty?
@changeset = @repository.find_changeset_by_name(@rev)
end end
def revision def revision
raise ChangesetNotFound if @rev.blank? raise ChangesetNotFound if @rev.nil? || @rev.empty?
@changeset = @repository.find_changeset_by_name(@rev) @changeset = @repository.find_changeset_by_name(@rev)
raise ChangesetNotFound unless @changeset raise ChangesetNotFound unless @changeset
@@ -188,7 +150,7 @@ class RepositoriesController < ApplicationController
rescue ChangesetNotFound rescue ChangesetNotFound
show_error_not_found show_error_not_found
end end
def diff def diff
if params[:format] == 'diff' if params[:format] == 'diff'
@diff = @repository.diff(@path, @rev, @rev_to) @diff = @repository.diff(@path, @rev, @rev_to)
@@ -201,14 +163,14 @@ class RepositoriesController < ApplicationController
else else
@diff_type = params[:type] || User.current.pref[:diff_type] || 'inline' @diff_type = params[:type] || User.current.pref[:diff_type] || 'inline'
@diff_type = 'inline' unless %w(inline sbs).include?(@diff_type) @diff_type = 'inline' unless %w(inline sbs).include?(@diff_type)
# Save diff type as user preference # Save diff type as user preference
if User.current.logged? && @diff_type != User.current.pref[:diff_type] if User.current.logged? && @diff_type != User.current.pref[:diff_type]
User.current.pref[:diff_type] = @diff_type User.current.pref[:diff_type] = @diff_type
User.current.preference.save User.current.preference.save
end end
@cache_key = "repositories/diff/#{@repository.id}/" +
Digest::MD5.hexdigest("#{@path}-#{@rev}-#{@rev_to}-#{@diff_type}-#{current_language}") @cache_key = "repositories/diff/#{@repository.id}/" + Digest::MD5.hexdigest("#{@path}-#{@rev}-#{@rev_to}-#{@diff_type}")
unless read_fragment(@cache_key) unless read_fragment(@cache_key)
@diff = @repository.diff(@path, @rev, @rev_to) @diff = @repository.diff(@path, @rev, @rev_to)
show_error_not_found unless @diff show_error_not_found unless @diff
@@ -216,15 +178,14 @@ class RepositoriesController < ApplicationController
@changeset = @repository.find_changeset_by_name(@rev) @changeset = @repository.find_changeset_by_name(@rev)
@changeset_to = @rev_to ? @repository.find_changeset_by_name(@rev_to) : nil @changeset_to = @rev_to ? @repository.find_changeset_by_name(@rev_to) : nil
@diff_format_revisions = @repository.diff_format_revisions(@changeset, @changeset_to)
end end
end end
def stats def stats
end end
def graph def graph
data = nil data = nil
case params[:graph] case params[:graph]
when "commits_per_month" when "commits_per_month"
data = graph_commits_per_month(@repository) data = graph_commits_per_month(@repository)
@@ -238,7 +199,7 @@ class RepositoriesController < ApplicationController
render_404 render_404
end end
end end
private private
REV_PARAM_RE = %r{\A[a-f0-9]*\Z}i REV_PARAM_RE = %r{\A[a-f0-9]*\Z}i
@@ -251,7 +212,7 @@ class RepositoriesController < ApplicationController
@path ||= '' @path ||= ''
@rev = params[:rev].blank? ? @repository.default_branch : params[:rev].strip @rev = params[:rev].blank? ? @repository.default_branch : params[:rev].strip
@rev_to = params[:rev_to] @rev_to = params[:rev_to]
unless @rev.to_s.match(REV_PARAM_RE) && @rev_to.to_s.match(REV_PARAM_RE) unless @rev.to_s.match(REV_PARAM_RE) && @rev_to.to_s.match(REV_PARAM_RE)
if @repository.branches.blank? if @repository.branches.blank?
raise InvalidRevisionParam raise InvalidRevisionParam
@@ -266,31 +227,27 @@ class RepositoriesController < ApplicationController
def show_error_not_found def show_error_not_found
render_error :message => l(:error_scm_not_found), :status => 404 render_error :message => l(:error_scm_not_found), :status => 404
end end
# Handler for Redmine::Scm::Adapters::CommandFailed exception # Handler for Redmine::Scm::Adapters::CommandFailed exception
def show_error_command_failed(exception) def show_error_command_failed(exception)
render_error l(:error_scm_command_failed, exception.message) render_error l(:error_scm_command_failed, exception.message)
end end
def graph_commits_per_month(repository) def graph_commits_per_month(repository)
@date_to = Date.today @date_to = Date.today
@date_from = @date_to << 11 @date_from = @date_to << 11
@date_from = Date.civil(@date_from.year, @date_from.month, 1) @date_from = Date.civil(@date_from.year, @date_from.month, 1)
commits_by_day = repository.changesets.count( commits_by_day = repository.changesets.count(:all, :group => :commit_date, :conditions => ["commit_date BETWEEN ? AND ?", @date_from, @date_to])
:all, :group => :commit_date,
:conditions => ["commit_date BETWEEN ? AND ?", @date_from, @date_to])
commits_by_month = [0] * 12 commits_by_month = [0] * 12
commits_by_day.each {|c| commits_by_month[c.first.to_date.months_ago] += c.last } commits_by_day.each {|c| commits_by_month[c.first.to_date.months_ago] += c.last }
changes_by_day = repository.changes.count( changes_by_day = repository.changes.count(:all, :group => :commit_date, :conditions => ["commit_date BETWEEN ? AND ?", @date_from, @date_to])
:all, :group => :commit_date,
:conditions => ["commit_date BETWEEN ? AND ?", @date_from, @date_to])
changes_by_month = [0] * 12 changes_by_month = [0] * 12
changes_by_day.each {|c| changes_by_month[c.first.to_date.months_ago] += c.last } changes_by_day.each {|c| changes_by_month[c.first.to_date.months_ago] += c.last }
fields = [] fields = []
12.times {|m| fields << month_name(((Date.today.month - 1 - m) % 12) + 1)} 12.times {|m| fields << month_name(((Date.today.month - 1 - m) % 12) + 1)}
graph = SVG::Graph::Bar.new( graph = SVG::Graph::Bar.new(
:height => 300, :height => 300,
:width => 800, :width => 800,
@@ -302,7 +259,7 @@ class RepositoriesController < ApplicationController
:graph_title => l(:label_commits_per_month), :graph_title => l(:label_commits_per_month),
:show_graph_title => true :show_graph_title => true
) )
graph.add_data( graph.add_data(
:data => commits_by_month[0..11].reverse, :data => commits_by_month[0..11].reverse,
:title => l(:label_revision_plural) :title => l(:label_revision_plural)
@@ -312,7 +269,7 @@ class RepositoriesController < ApplicationController
:data => changes_by_month[0..11].reverse, :data => changes_by_month[0..11].reverse,
:title => l(:label_change_plural) :title => l(:label_change_plural)
) )
graph.burn graph.burn
end end
@@ -322,18 +279,18 @@ class RepositoriesController < ApplicationController
changes_by_author = repository.changes.count(:all, :group => :committer) changes_by_author = repository.changes.count(:all, :group => :committer)
h = changes_by_author.inject({}) {|o, i| o[i.first] = i.last; o} h = changes_by_author.inject({}) {|o, i| o[i.first] = i.last; o}
fields = commits_by_author.collect {|r| r.first} fields = commits_by_author.collect {|r| r.first}
commits_data = commits_by_author.collect {|r| r.last} commits_data = commits_by_author.collect {|r| r.last}
changes_data = commits_by_author.collect {|r| h[r.first] || 0} changes_data = commits_by_author.collect {|r| h[r.first] || 0}
fields = fields + [""]*(10 - fields.length) if fields.length<10 fields = fields + [""]*(10 - fields.length) if fields.length<10
commits_data = commits_data + [0]*(10 - commits_data.length) if commits_data.length<10 commits_data = commits_data + [0]*(10 - commits_data.length) if commits_data.length<10
changes_data = changes_data + [0]*(10 - changes_data.length) if changes_data.length<10 changes_data = changes_data + [0]*(10 - changes_data.length) if changes_data.length<10
# Remove email adress in usernames # Remove email adress in usernames
fields = fields.collect {|c| c.gsub(%r{<.+@.+>}, '') } fields = fields.collect {|c| c.gsub(%r{<.+@.+>}, '') }
graph = SVG::Graph::BarHorizontal.new( graph = SVG::Graph::BarHorizontal.new(
:height => 400, :height => 400,
:width => 800, :width => 800,
@@ -345,18 +302,22 @@ class RepositoriesController < ApplicationController
:graph_title => l(:label_commits_per_author), :graph_title => l(:label_commits_per_author),
:show_graph_title => true :show_graph_title => true
) )
graph.add_data( graph.add_data(
:data => commits_data, :data => commits_data,
:title => l(:label_revision_plural) :title => l(:label_revision_plural)
) )
graph.add_data( graph.add_data(
:data => changes_data, :data => changes_data,
:title => l(:label_change_plural) :title => l(:label_change_plural)
) )
graph.burn graph.burn
end end
end
end
class Date class Date
def months_ago(date = Date.today) def months_ago(date = Date.today)
(date.year - self.year)*12 + (date.month - self.month) (date.year - self.year)*12 + (date.month - self.month)
+3 -5
View File
@@ -38,10 +38,9 @@ class RolesController < ApplicationController
end end
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to :action => 'index' redirect_to :action => 'index'
else
@permissions = @role.setable_permissions
@roles = Role.find :all, :order => 'builtin, position'
end end
@permissions = @role.setable_permissions
@roles = Role.find :all, :order => 'builtin, position'
end end
def edit def edit
@@ -49,9 +48,8 @@ class RolesController < ApplicationController
if request.post? and @role.update_attributes(params[:role]) if request.post? and @role.update_attributes(params[:role])
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'index' redirect_to :action => 'index'
else
@permissions = @role.setable_permissions
end end
@permissions = @role.setable_permissions
end end
def destroy def destroy
+4 -4
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -24,8 +24,8 @@ class SearchController < ApplicationController
def index def index
@question = params[:q] || "" @question = params[:q] || ""
@question.strip! @question.strip!
@all_words = params[:all_words] ? params[:all_words].present? : true @all_words = params[:all_words] || (params[:submit] ? false : true)
@titles_only = params[:titles_only] ? params[:titles_only].present? : false @titles_only = !params[:titles_only].nil?
projects_to_search = projects_to_search =
case params[:scope] case params[:scope]
+14 -15
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -17,7 +17,7 @@
class SettingsController < ApplicationController class SettingsController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin before_filter :require_admin
def index def index
@@ -36,16 +36,16 @@ class SettingsController < ApplicationController
end end
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'edit', :tab => params[:tab] redirect_to :action => 'edit', :tab => params[:tab]
else return
@options = {}
@options[:user_format] = User::USER_FORMATS.keys.collect {|f| [User.current.name(f), f.to_s] }
@deliveries = ActionMailer::Base.perform_deliveries
@guessed_host_and_path = request.host_with_port.dup
@guessed_host_and_path << ('/'+ Redmine::Utils.relative_url_root.gsub(%r{^\/}, '')) unless Redmine::Utils.relative_url_root.blank?
Redmine::Themes.rescan
end end
@options = {}
@options[:user_format] = User::USER_FORMATS.keys.collect {|f| [User.current.name(f), f.to_s] }
@deliveries = ActionMailer::Base.perform_deliveries
@guessed_host_and_path = request.host_with_port.dup
@guessed_host_and_path << ('/'+ Redmine::Utils.relative_url_root.gsub(%r{^\/}, '')) unless Redmine::Utils.relative_url_root.blank?
Redmine::Themes.rescan
end end
def plugin def plugin
@@ -54,10 +54,9 @@ class SettingsController < ApplicationController
Setting["plugin_#{@plugin.id}"] = params[:settings] Setting["plugin_#{@plugin.id}"] = params[:settings]
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'plugin', :id => @plugin.id redirect_to :action => 'plugin', :id => @plugin.id
else
@partial = @plugin.settings[:partial]
@settings = Setting["plugin_#{@plugin.id}"]
end end
@partial = @plugin.settings[:partial]
@settings = Setting["plugin_#{@plugin.id}"]
rescue Redmine::PluginNotFound rescue Redmine::PluginNotFound
render_404 render_404
end end
+67 -119
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2010 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -18,12 +18,10 @@
class TimelogController < ApplicationController class TimelogController < ApplicationController
menu_item :issues menu_item :issues
before_filter :find_project, :only => [:new, :create] before_filter :find_project, :only => [:new, :create]
before_filter :find_time_entry, :only => [:show, :edit, :update] before_filter :find_time_entry, :only => [:show, :edit, :update, :destroy]
before_filter :find_time_entries, :only => [:bulk_edit, :bulk_update, :destroy]
before_filter :authorize, :except => [:index] before_filter :authorize, :except => [:index]
before_filter :find_optional_project, :only => [:index] before_filter :find_optional_project, :only => [:index]
accept_rss_auth :index accept_key_auth :index, :show, :create, :update, :destroy
accept_api_auth :index, :show, :create, :update, :destroy
helper :sort helper :sort
include SortHelper include SortHelper
@@ -42,56 +40,60 @@ class TimelogController < ApplicationController
'hours' => 'hours' 'hours' => 'hours'
cond = ARCondition.new cond = ARCondition.new
if @issue if @project.nil?
cond << "#{Issue.table_name}.root_id = #{@issue.root_id} AND #{Issue.table_name}.lft >= #{@issue.lft} AND #{Issue.table_name}.rgt <= #{@issue.rgt}" cond << Project.allowed_to_condition(User.current, :view_time_entries)
elsif @project elsif @issue.nil?
cond << @project.project_condition(Setting.display_subprojects_issues?) cond << @project.project_condition(Setting.display_subprojects_issues?)
else
cond << "#{Issue.table_name}.root_id = #{@issue.root_id} AND #{Issue.table_name}.lft >= #{@issue.lft} AND #{Issue.table_name}.rgt <= #{@issue.rgt}"
end end
retrieve_date_range retrieve_date_range
cond << ['spent_on BETWEEN ? AND ?', @from, @to] cond << ['spent_on BETWEEN ? AND ?', @from, @to]
respond_to do |format| TimeEntry.visible_by(User.current) do
format.html { respond_to do |format|
# Paginate results format.html {
@entry_count = TimeEntry.visible.count(:include => [:project, :issue], :conditions => cond.conditions) # Paginate results
@entry_pages = Paginator.new self, @entry_count, per_page_option, params['page'] @entry_count = TimeEntry.count(:include => [:project, :issue], :conditions => cond.conditions)
@entries = TimeEntry.visible.find(:all, @entry_pages = Paginator.new self, @entry_count, per_page_option, params['page']
:include => [:project, :activity, :user, {:issue => :tracker}], @entries = TimeEntry.find(:all,
:conditions => cond.conditions, :include => [:project, :activity, :user, {:issue => :tracker}],
:order => sort_clause, :conditions => cond.conditions,
:limit => @entry_pages.items_per_page, :order => sort_clause,
:offset => @entry_pages.current.offset) :limit => @entry_pages.items_per_page,
@total_hours = TimeEntry.visible.sum(:hours, :include => [:project, :issue], :conditions => cond.conditions).to_f :offset => @entry_pages.current.offset)
@total_hours = TimeEntry.sum(:hours, :include => [:project, :issue], :conditions => cond.conditions).to_f
render :layout => !request.xhr? render :layout => !request.xhr?
} }
format.api { format.api {
@entry_count = TimeEntry.visible.count(:include => [:project, :issue], :conditions => cond.conditions) @entry_count = TimeEntry.count(:include => [:project, :issue], :conditions => cond.conditions)
@offset, @limit = api_offset_and_limit @entry_pages = Paginator.new self, @entry_count, per_page_option, params['page']
@entries = TimeEntry.visible.find(:all, @entries = TimeEntry.find(:all,
:include => [:project, :activity, :user, {:issue => :tracker}], :include => [:project, :activity, :user, {:issue => :tracker}],
:conditions => cond.conditions, :conditions => cond.conditions,
:order => sort_clause, :order => sort_clause,
:limit => @limit, :limit => @entry_pages.items_per_page,
:offset => @offset) :offset => @entry_pages.current.offset)
} }
format.atom { format.atom {
entries = TimeEntry.visible.find(:all, entries = TimeEntry.find(:all,
:include => [:project, :activity, :user, {:issue => :tracker}], :include => [:project, :activity, :user, {:issue => :tracker}],
:conditions => cond.conditions, :conditions => cond.conditions,
:order => "#{TimeEntry.table_name}.created_on DESC", :order => "#{TimeEntry.table_name}.created_on DESC",
:limit => Setting.feeds_limit.to_i) :limit => Setting.feeds_limit.to_i)
render_feed(entries, :title => l(:label_spent_time)) render_feed(entries, :title => l(:label_spent_time))
} }
format.csv { format.csv {
# Export all entries # Export all entries
@entries = TimeEntry.visible.find(:all, @entries = TimeEntry.find(:all,
:include => [:project, :activity, :user, {:issue => [:tracker, :assigned_to, :priority]}], :include => [:project, :activity, :user, {:issue => [:tracker, :assigned_to, :priority]}],
:conditions => cond.conditions, :conditions => cond.conditions,
:order => sort_clause) :order => sort_clause)
send_data(entries_to_csv(@entries), :type => 'text/csv; header=present', :filename => 'timelog.csv') send_data(entries_to_csv(@entries), :type => 'text/csv; header=present', :filename => 'timelog.csv')
} }
end
end end
end end
@@ -162,55 +164,27 @@ class TimelogController < ApplicationController
end end
end end
def bulk_edit
@available_activities = TimeEntryActivity.shared.active
@custom_fields = TimeEntry.first.available_custom_fields
end
def bulk_update
attributes = parse_params_for_bulk_time_entry_attributes(params)
unsaved_time_entry_ids = []
@time_entries.each do |time_entry|
time_entry.reload
time_entry.attributes = attributes
call_hook(:controller_time_entries_bulk_edit_before_save, { :params => params, :time_entry => time_entry })
unless time_entry.save
# Keep unsaved time_entry ids to display them in flash error
unsaved_time_entry_ids << time_entry.id
end
end
set_flash_from_bulk_time_entry_save(@time_entries, unsaved_time_entry_ids)
redirect_back_or_default({:controller => 'timelog', :action => 'index', :project_id => @projects.first})
end
verify :method => :delete, :only => :destroy, :render => {:nothing => true, :status => :method_not_allowed } verify :method => :delete, :only => :destroy, :render => {:nothing => true, :status => :method_not_allowed }
def destroy def destroy
@time_entries.each do |t| if @time_entry.destroy && @time_entry.destroyed?
begin respond_to do |format|
unless t.destroy && t.destroyed? format.html {
respond_to do |format| flash[:notice] = l(:notice_successful_delete)
format.html { redirect_to :back
flash[:error] = l(:notice_unable_delete_time_entry) }
redirect_to :back format.api { head :ok }
} end
format.api { render_validation_errors(t) } else
end respond_to do |format|
return format.html {
end flash[:error] = l(:notice_unable_delete_time_entry)
rescue ::ActionController::RedirectBackError redirect_to :back
redirect_to :action => 'index', :project_id => @projects.first }
return format.api { render_validation_errors(@time_entry) }
end end
end end
rescue ::ActionController::RedirectBackError
respond_to do |format| redirect_to :action => 'index', :project_id => @time_entry.project
format.html {
flash[:notice] = l(:notice_successful_delete)
redirect_back_or_default(:action => 'index', :project_id => @projects.first)
}
format.api { head :ok }
end
end end
private private
@@ -225,26 +199,6 @@ private
render_404 render_404
end end
def find_time_entries
@time_entries = TimeEntry.find_all_by_id(params[:id] || params[:ids])
raise ActiveRecord::RecordNotFound if @time_entries.empty?
@projects = @time_entries.collect(&:project).compact.uniq
@project = @projects.first if @projects.size == 1
rescue ActiveRecord::RecordNotFound
render_404
end
def set_flash_from_bulk_time_entry_save(time_entries, unsaved_time_entry_ids)
if unsaved_time_entry_ids.empty?
flash[:notice] = l(:notice_successful_update) unless time_entries.empty?
else
flash[:error] = l(:notice_failed_to_save_time_entries,
:count => unsaved_time_entry_ids.size,
:total => time_entries.size,
:ids => '#' + unsaved_time_entry_ids.join(', #'))
end
end
def find_project def find_project
if (issue_id = (params[:issue_id] || params[:time_entry] && params[:time_entry][:issue_id])).present? if (issue_id = (params[:issue_id] || params[:time_entry] && params[:time_entry][:issue_id])).present?
@issue = Issue.find(issue_id) @issue = Issue.find(issue_id)
@@ -315,10 +269,4 @@ private
@to ||= (TimeEntry.latest_date_for_project(@project) || Date.today) @to ||= (TimeEntry.latest_date_for_project(@project) || Date.today)
end end
def parse_params_for_bulk_time_entry_attributes(params)
attributes = (params[:time_entry] || {}).reject {|k,v| v.blank?}
attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'}
attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
attributes
end
end end
+9 -24
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2010 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -19,8 +19,8 @@ class UsersController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin, :except => :show before_filter :require_admin, :except => :show
before_filter :find_user, :only => [:show, :edit, :update, :destroy, :edit_membership, :destroy_membership] before_filter :find_user, :only => [:show, :edit, :update, :edit_membership, :destroy_membership]
accept_api_auth :index, :show, :create, :update, :destroy accept_key_auth :index, :show, :create, :update
helper :sort helper :sort
include SortHelper include SortHelper
@@ -38,9 +38,6 @@ class UsersController < ApplicationController
@limit = per_page_option @limit = per_page_option
end end
scope = User
scope = scope.in_group(params[:group_id].to_i) if params[:group_id].present?
@status = params[:status] ? params[:status].to_i : 1 @status = params[:status] ? params[:status].to_i : 1
c = ARCondition.new(@status == 0 ? "status <> 0" : ["status = ?", @status]) c = ARCondition.new(@status == 0 ? "status <> 0" : ["status = ?", @status])
@@ -49,27 +46,24 @@ class UsersController < ApplicationController
c << ["LOWER(login) LIKE ? OR LOWER(firstname) LIKE ? OR LOWER(lastname) LIKE ? OR LOWER(mail) LIKE ?", name, name, name, name] c << ["LOWER(login) LIKE ? OR LOWER(firstname) LIKE ? OR LOWER(lastname) LIKE ? OR LOWER(mail) LIKE ?", name, name, name, name]
end end
@user_count = scope.count(:conditions => c.conditions) @user_count = User.count(:conditions => c.conditions)
@user_pages = Paginator.new self, @user_count, @limit, params['page'] @user_pages = Paginator.new self, @user_count, @limit, params['page']
@offset ||= @user_pages.current.offset @offset ||= @user_pages.current.offset
@users = scope.find :all, @users = User.find :all,
:order => sort_clause, :order => sort_clause,
:conditions => c.conditions, :conditions => c.conditions,
:limit => @limit, :limit => @limit,
:offset => @offset :offset => @offset
respond_to do |format| respond_to do |format|
format.html { format.html { render :layout => !request.xhr? }
@groups = Group.all.sort
render :layout => !request.xhr?
}
format.api format.api
end end
end end
def show def show
# show projects based on current user visibility # show projects based on current user visibility
@memberships = @user.memberships.all(:conditions => Project.visible_condition(User.current)) @memberships = @user.memberships.all(:conditions => Project.visible_by(User.current))
events = Redmine::Activity::Fetcher.new(User.current, :author => @user).events(nil, nil, :limit => 10) events = Redmine::Activity::Fetcher.new(User.current, :author => @user).events(nil, nil, :limit => 10)
@events_by_day = events.group_by(&:event_date) @events_by_day = events.group_by(&:event_date)
@@ -183,15 +177,6 @@ class UsersController < ApplicationController
redirect_to :controller => 'users', :action => 'edit', :id => @user redirect_to :controller => 'users', :action => 'edit', :id => @user
end end
verify :method => :delete, :only => :destroy, :render => {:nothing => true, :status => :method_not_allowed }
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to(users_url) }
format.api { head :ok }
end
end
def edit_membership def edit_membership
@membership = Member.edit_membership(params[:membership_id], params[:membership], @user) @membership = Member.edit_membership(params[:membership_id], params[:membership], @user)
@membership.save if request.post? @membership.save if request.post?
+13 -5
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -76,13 +76,21 @@ private
def set_watcher(user, watching) def set_watcher(user, watching)
@watched.set_watcher(user, watching) @watched.set_watcher(user, watching)
if params[:replace].present?
if params[:replace].is_a? Array
replace_ids = params[:replace]
else
replace_ids = [params[:replace]]
end
else
replace_ids = ['watcher']
end
respond_to do |format| respond_to do |format|
format.html { redirect_to :back } format.html { redirect_to :back }
format.js do format.js do
render(:update) do |page| render(:update) do |page|
c = watcher_css(@watched) replace_ids.each do |replace_id|
page.select(".#{c}").each do |item| page.replace_html replace_id, watcher_link(@watched, user, :replace => replace_ids)
page.replace_html item, watcher_link(@watched, user)
end end
end end
end end
+37 -44
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -34,27 +34,23 @@ require 'diff'
class WikiController < ApplicationController class WikiController < ApplicationController
default_search_scope :wiki_pages default_search_scope :wiki_pages
before_filter :find_wiki, :authorize before_filter :find_wiki, :authorize
before_filter :find_existing_or_new_page, :only => [:show, :edit, :update]
before_filter :find_existing_page, :only => [:rename, :protect, :history, :diff, :annotate, :add_attachment, :destroy] before_filter :find_existing_page, :only => [:rename, :protect, :history, :diff, :annotate, :add_attachment, :destroy]
verify :method => :post, :only => [:protect], :redirect_to => { :action => :show }
helper :attachments helper :attachments
include AttachmentsHelper include AttachmentsHelper
helper :watchers helper :watchers
# List of pages, sorted alphabetically and by parent (hierarchy) # List of pages, sorted alphabetically and by parent (hierarchy)
def index def index
load_pages_for_index load_pages_grouped_by_date_without_content
@pages_by_parent_id = @pages.group_by(&:parent_id)
end
# List of page, by last update
def date_index
load_pages_for_index
@pages_by_date = @pages.group_by {|p| p.updated_on.to_date}
end end
# display a page (in editing mode if it doesn't exist) # display a page (in editing mode if it doesn't exist)
def show def show
page_title = params[:id]
@page = @wiki.find_or_new_page(page_title)
if @page.new_record? if @page.new_record?
if User.current.allowed_to?(:edit_wiki_pages, @project) && editable? if User.current.allowed_to?(:edit_wiki_pages, @project) && editable?
edit edit
@@ -83,12 +79,13 @@ class WikiController < ApplicationController
@editable = editable? @editable = editable?
render :action => 'show' render :action => 'show'
end end
# edit an existing page or a new one # edit an existing page or a new one
def edit def edit
@page = @wiki.find_or_new_page(params[:id])
return render_403 unless editable? return render_403 unless editable?
@page.content = WikiContent.new(:page => @page) if @page.new_record? @page.content = WikiContent.new(:page => @page) if @page.new_record?
@content = @page.content_for_version(params[:version]) @content = @page.content_for_version(params[:version])
@content.text = initial_page_content(@page) if @content.text.blank? @content.text = initial_page_content(@page) if @content.text.blank?
# don't keep previous comment # don't keep previous comment
@@ -101,9 +98,10 @@ class WikiController < ApplicationController
verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed } verify :method => :put, :only => :update, :render => {:nothing => true, :status => :method_not_allowed }
# Creates a new page or updates an existing one # Creates a new page or updates an existing one
def update def update
@page = @wiki.find_or_new_page(params[:id])
return render_403 unless editable? return render_403 unless editable?
@page.content = WikiContent.new(:page => @page) if @page.new_record? @page.content = WikiContent.new(:page => @page) if @page.new_record?
@content = @page.content_for_version(params[:version]) @content = @page.content_for_version(params[:version])
@content.text = initial_page_content(@page) if @content.text.blank? @content.text = initial_page_content(@page) if @content.text.blank?
# don't keep previous comment # don't keep previous comment
@@ -145,8 +143,7 @@ class WikiController < ApplicationController
redirect_to :action => 'show', :project_id => @project, :id => @page.title redirect_to :action => 'show', :project_id => @project, :id => @page.title
end end
end end
verify :method => :post, :only => :protect, :redirect_to => { :action => :show }
def protect def protect
@page.update_attribute :protected, params[:protected] @page.update_attribute :protected, params[:protected]
redirect_to :action => 'show', :project_id => @project, :id => @page.title redirect_to :action => 'show', :project_id => @project, :id => @page.title
@@ -156,8 +153,8 @@ class WikiController < ApplicationController
def history def history
@version_count = @page.content.versions.count @version_count = @page.content.versions.count
@version_pages = Paginator.new self, @version_count, per_page_option, params['p'] @version_pages = Paginator.new self, @version_count, per_page_option, params['p']
# don't load text # don't load text
@versions = @page.content.versions.find :all, @versions = @page.content.versions.find :all,
:select => "id, author_id, comments, updated_on, version", :select => "id, author_id, comments, updated_on, version",
:order => 'version DESC', :order => 'version DESC',
:limit => @version_pages.items_per_page + 1, :limit => @version_pages.items_per_page + 1,
@@ -165,12 +162,12 @@ class WikiController < ApplicationController
render :layout => false if request.xhr? render :layout => false if request.xhr?
end end
def diff def diff
@diff = @page.diff(params[:version], params[:version_from]) @diff = @page.diff(params[:version], params[:version_from])
render_404 unless @diff render_404 unless @diff
end end
def annotate def annotate
@annotate = @page.annotate(params[:version]) @annotate = @page.annotate(params[:version])
render_404 unless @annotate render_404 unless @annotate
@@ -181,7 +178,7 @@ class WikiController < ApplicationController
# Children can be either set as root pages, removed or reassigned to another parent page # Children can be either set as root pages, removed or reassigned to another parent page
def destroy def destroy
return render_403 unless editable? return render_403 unless editable?
@descendants_count = @page.descendants.size @descendants_count = @page.descendants.size
if @descendants_count > 0 if @descendants_count > 0
case params[:todo] case params[:todo]
@@ -217,6 +214,10 @@ class WikiController < ApplicationController
end end
end end
def date_index
load_pages_grouped_by_date_without_content
end
def preview def preview
page = @wiki.find_page(params[:id]) page = @wiki.find_page(params[:id])
# page is nil when previewing a new page # page is nil when previewing a new page
@@ -237,7 +238,7 @@ class WikiController < ApplicationController
end end
private private
def find_wiki def find_wiki
@project = Project.find(params[:project_id]) @project = Project.find(params[:project_id])
@wiki = @project.wiki @wiki = @project.wiki
@@ -245,27 +246,13 @@ private
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
# Finds the requested page or a new page if it doesn't exist
def find_existing_or_new_page
@page = @wiki.find_or_new_page(params[:id])
if @wiki.page_found_with_redirect?
redirect_to params.update(:id => @page.title)
end
end
# Finds the requested page and returns a 404 error if it doesn't exist # Finds the requested page and returns a 404 error if it doesn't exist
def find_existing_page def find_existing_page
@page = @wiki.find_page(params[:id]) @page = @wiki.find_page(params[:id])
if @page.nil? render_404 if @page.nil?
render_404
return
end
if @wiki.page_found_with_redirect?
redirect_to params.update(:id => @page.title)
end
end end
# Returns true if the current user is allowed to edit the page, otherwise false # Returns true if the current user is allowed to edit the page, otherwise false
def editable?(page = @page) def editable?(page = @page)
page.editable_by?(User.current) page.editable_by?(User.current)
@@ -278,7 +265,13 @@ private
helper.instance_method(:initial_page_content).bind(self).call(page) helper.instance_method(:initial_page_content).bind(self).call(page)
end end
def load_pages_for_index # eager load information about last updates, without loading text
@pages = @wiki.pages.with_updated_on.all(:order => 'title', :include => {:wiki => :project}) def load_pages_grouped_by_date_without_content
@pages = @wiki.pages.find :all, :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
:joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
:order => 'title'
@pages_by_date = @pages.group_by {|p| p.updated_on.to_date}
@pages_by_parent_id = @pages.group_by(&:parent_id)
end end
end end
+3 -14
View File
@@ -32,17 +32,14 @@ class WorkflowsController < ApplicationController
if request.post? if request.post?
Workflow.destroy_all( ["role_id=? and tracker_id=?", @role.id, @tracker.id]) Workflow.destroy_all( ["role_id=? and tracker_id=?", @role.id, @tracker.id])
(params[:issue_status] || []).each { |status_id, transitions| (params[:issue_status] || []).each { |old, news|
transitions.each { |new_status_id, options| news.each { |new|
author = options.is_a?(Array) && options.include?('author') && !options.include?('always') @role.workflows.build(:tracker_id => @tracker.id, :old_status_id => old, :new_status_id => new)
assignee = options.is_a?(Array) && options.include?('assignee') && !options.include?('always')
@role.workflows.build(:tracker_id => @tracker.id, :old_status_id => status_id, :new_status_id => new_status_id, :author => author, :assignee => assignee)
} }
} }
if @role.save if @role.save
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'edit', :role_id => @role, :tracker_id => @tracker redirect_to :action => 'edit', :role_id => @role, :tracker_id => @tracker
return
end end
end end
@@ -51,14 +48,6 @@ class WorkflowsController < ApplicationController
@statuses = @tracker.issue_statuses @statuses = @tracker.issue_statuses
end end
@statuses ||= IssueStatus.find(:all, :order => 'position') @statuses ||= IssueStatus.find(:all, :order => 'position')
if @tracker && @role && @statuses.any?
workflows = Workflow.all(:conditions => {:role_id => @role.id, :tracker_id => @tracker.id})
@workflows = {}
@workflows['always'] = workflows.select {|w| !w.author && !w.assignee}
@workflows['author'] = workflows.select {|w| w.author}
@workflows['assignee'] = workflows.select {|w| w.assignee}
end
end end
def copy def copy
+93 -123
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2010 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -63,7 +63,7 @@ module ApplicationHelper
# Displays a link to +issue+ with its subject. # Displays a link to +issue+ with its subject.
# Examples: # Examples:
# #
# link_to_issue(issue) # => Defect #6: This is the subject # link_to_issue(issue) # => Defect #6: This is the subject
# link_to_issue(issue, :truncate => 6) # => Defect #6: This i... # link_to_issue(issue, :truncate => 6) # => Defect #6: This i...
# link_to_issue(issue, :subject => false) # => Defect #6 # link_to_issue(issue, :subject => false) # => Defect #6
@@ -80,7 +80,7 @@ module ApplicationHelper
subject = truncate(subject, :length => options[:truncate]) subject = truncate(subject, :length => options[:truncate])
end end
end end
s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue}, s = link_to "#{issue.tracker} ##{issue.id}", {:controller => "issues", :action => "show", :id => issue},
:class => issue.css_classes, :class => issue.css_classes,
:title => title :title => title
s << ": #{h subject}" if subject s << ": #{h subject}" if subject
@@ -110,23 +110,9 @@ module ApplicationHelper
:title => l(:label_revision_id, format_revision(revision))) :title => l(:label_revision_id, format_revision(revision)))
end end
# Generates a link to a message
def link_to_message(message, options={}, html_options = nil)
link_to(
h(truncate(message.subject, :length => 60)),
{ :controller => 'messages', :action => 'show',
:board_id => message.board_id,
:id => message.root,
:r => (message.parent_id && message.id),
:anchor => (message.parent_id ? "message-#{message.id}" : nil)
}.merge(options),
html_options
)
end
# Generates a link to a project if active # Generates a link to a project if active
# Examples: # Examples:
# #
# link_to_project(project) # => link to the specified project overview # link_to_project(project) # => link to the specified project overview
# link_to_project(project, :action=>'settings') # => link to project settings # link_to_project(project, :action=>'settings') # => link to project settings
# link_to_project(project, {:only_path => false}, :class => "project") # => 3rd arg adds html options # link_to_project(project, {:only_path => false}, :class => "project") # => 3rd arg adds html options
@@ -160,15 +146,15 @@ module ApplicationHelper
html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;" html_options[:onclick] = "promptToRemote('#{text}', '#{param}', '#{url_for(url)}'); return false;"
link_to name, {}, html_options link_to name, {}, html_options
end end
def format_activity_title(text) def format_activity_title(text)
h(truncate_single_line(text, :length => 100)) h(truncate_single_line(text, :length => 100))
end end
def format_activity_day(date) def format_activity_day(date)
date == Date.today ? l(:label_today).titleize : format_date(date) date == Date.today ? l(:label_today).titleize : format_date(date)
end end
def format_activity_description(text) def format_activity_description(text)
h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />") h(truncate(text.to_s, :length => 120).gsub(%r{[\r\n]*<(pre|code)>.*$}m, '...')).gsub(/[\r\n]+/, "<br />")
end end
@@ -180,29 +166,29 @@ module ApplicationHelper
h("#{version.project} - #{version}") h("#{version.project} - #{version}")
end end
end end
def due_date_distance_in_words(date) def due_date_distance_in_words(date)
if date if date
l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date)) l((date < Date.today ? :label_roadmap_overdue : :label_roadmap_due_in), distance_of_date_in_words(Date.today, date))
end end
end end
def render_page_hierarchy(pages, node=nil, options={}) def render_page_hierarchy(pages, node=nil)
content = '' content = ''
if pages[node] if pages[node]
content << "<ul class=\"pages-hierarchy\">\n" content << "<ul class=\"pages-hierarchy\">\n"
pages[node].each do |page| pages[node].each do |page|
content << "<li>" content << "<li>"
content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title}, content << link_to(h(page.pretty_title), {:controller => 'wiki', :action => 'show', :project_id => page.project, :id => page.title},
:title => (options[:timestamp] && page.updated_on ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil)) :title => (page.respond_to?(:updated_on) ? l(:label_updated_time, distance_of_time_in_words(Time.now, page.updated_on)) : nil))
content << "\n" + render_page_hierarchy(pages, page.id, options) if pages[page.id] content << "\n" + render_page_hierarchy(pages, page.id) if pages[page.id]
content << "</li>\n" content << "</li>\n"
end end
content << "</ul>\n" content << "</ul>\n"
end end
content content
end end
# Renders flash messages # Renders flash messages
def render_flash_messages def render_flash_messages
s = '' s = ''
@@ -211,7 +197,7 @@ module ApplicationHelper
end end
s s
end end
# Renders tabs and their content # Renders tabs and their content
def render_tabs(tabs) def render_tabs(tabs)
if tabs.any? if tabs.any?
@@ -220,11 +206,11 @@ module ApplicationHelper
content_tag 'p', l(:label_no_data), :class => "nodata" content_tag 'p', l(:label_no_data), :class => "nodata"
end end
end end
# Renders the project quick-jump box # Renders the project quick-jump box
def render_project_jump_box def render_project_jump_box
return unless User.current.logged? # Retrieve them now to avoid a COUNT query
projects = User.current.memberships.collect(&:project).compact.uniq projects = User.current.projects.all
if projects.any? if projects.any?
s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' + s = '<select onchange="if (this.value != \'\') { window.location = this.value; }">' +
"<option value=''>#{ l(:label_jump_to_a_project) }</option>" + "<option value=''>#{ l(:label_jump_to_a_project) }</option>" +
@@ -236,7 +222,7 @@ module ApplicationHelper
s s
end end
end end
def project_tree_options_for_select(projects, options = {}) def project_tree_options_for_select(projects, options = {})
s = '' s = ''
project_tree(projects) do |project, level| project_tree(projects) do |project, level|
@@ -252,14 +238,14 @@ module ApplicationHelper
end end
s s
end end
# Yields the given block for each project with its level in the tree # Yields the given block for each project with its level in the tree
# #
# Wrapper for Project#project_tree # Wrapper for Project#project_tree
def project_tree(projects, &block) def project_tree(projects, &block)
Project.project_tree(projects, &block) Project.project_tree(projects, &block)
end end
def project_nested_ul(projects, &block) def project_nested_ul(projects, &block)
s = '' s = ''
if projects.any? if projects.any?
@@ -270,7 +256,7 @@ module ApplicationHelper
else else
ancestors.pop ancestors.pop
s << "</li>" s << "</li>"
while (ancestors.any? && !project.is_descendant_of?(ancestors.last)) while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
ancestors.pop ancestors.pop
s << "</ul></li>\n" s << "</ul></li>\n"
end end
@@ -283,20 +269,20 @@ module ApplicationHelper
end end
s s
end end
def principals_check_box_tags(name, principals) def principals_check_box_tags(name, principals)
s = '' s = ''
principals.sort.each do |principal| principals.sort.each do |principal|
s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n" s << "<label>#{ check_box_tag name, principal.id, false } #{h principal}</label>\n"
end end
s s
end end
# Truncates and returns the string as a single line # Truncates and returns the string as a single line
def truncate_single_line(string, *args) def truncate_single_line(string, *args)
truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ') truncate(string.to_s, *args).gsub(%r{[\r\n]+}m, ' ')
end end
# Truncates at line break after 250 characters or options[:length] # Truncates at line break after 250 characters or options[:length]
def truncate_lines(string, options={}) def truncate_lines(string, options={})
length = options[:length] || 250 length = options[:length] || 250
@@ -314,7 +300,7 @@ module ApplicationHelper
def authoring(created, author, options={}) def authoring(created, author, options={})
l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created)) l(options[:label] || :label_added_time_by, :author => link_to_user(author), :age => time_tag(created))
end end
def time_tag(time) def time_tag(time)
text = distance_of_time_in_words(Time.now, time) text = distance_of_time_in_words(Time.now, time)
if @project if @project
@@ -336,18 +322,20 @@ module ApplicationHelper
page_param = options.delete(:page_param) || :page page_param = options.delete(:page_param) || :page
per_page_links = options.delete(:per_page_links) per_page_links = options.delete(:per_page_links)
url_param = params.dup url_param = params.dup
# don't reuse query params if filters are present
url_param.merge!(:fields => nil, :values => nil, :operators => nil) if url_param.delete(:set_filter)
html = '' html = ''
if paginator.current.previous if paginator.current.previous
html << link_to_content_update('&#171; ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' ' html << link_to_remote_content_update('&#171; ' + l(:label_previous), url_param.merge(page_param => paginator.current.previous)) + ' '
end end
html << (pagination_links_each(paginator, options) do |n| html << (pagination_links_each(paginator, options) do |n|
link_to_content_update(n.to_s, url_param.merge(page_param => n)) link_to_remote_content_update(n.to_s, url_param.merge(page_param => n))
end || '') end || '')
if paginator.current.next if paginator.current.next
html << ' ' + link_to_content_update((l(:label_next) + ' &#187;'), url_param.merge(page_param => paginator.current.next)) html << ' ' + link_to_remote_content_update((l(:label_next) + ' &#187;'), url_param.merge(page_param => paginator.current.next))
end end
unless count.nil? unless count.nil?
@@ -359,14 +347,20 @@ module ApplicationHelper
html html
end end
def per_page_links(selected=nil) def per_page_links(selected=nil)
url_param = params.dup
url_param.clear if url_param.has_key?(:set_filter)
links = Setting.per_page_options_array.collect do |n| links = Setting.per_page_options_array.collect do |n|
n == selected ? n : link_to_content_update(n, params.merge(:per_page => n)) n == selected ? n : link_to_remote(n, {:update => "content",
:url => params.dup.merge(:per_page => n),
:method => :get},
{:href => url_for(url_param.merge(:per_page => n))})
end end
links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil links.size > 1 ? l(:label_display_per_page, links.join(', ')) : nil
end end
def reorder_links(name, url) def reorder_links(name, url)
link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) + link_to(image_tag('2uparrow.png', :alt => l(:label_sort_highest)), url.merge({"#{name}[move_to]" => 'highest'}), :method => :post, :title => l(:label_sort_highest)) +
link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) + link_to(image_tag('1uparrow.png', :alt => l(:label_sort_higher)), url.merge({"#{name}[move_to]" => 'higher'}), :method => :post, :title => l(:label_sort_higher)) +
@@ -378,19 +372,19 @@ module ApplicationHelper
elements = args.flatten elements = args.flatten
elements.any? ? content_tag('p', args.join(' &#187; ') + ' &#187; ', :class => 'breadcrumb') : nil elements.any? ? content_tag('p', args.join(' &#187; ') + ' &#187; ', :class => 'breadcrumb') : nil
end end
def other_formats_links(&block) def other_formats_links(&block)
concat('<p class="other-formats">' + l(:label_export_to)) concat('<p class="other-formats">' + l(:label_export_to))
yield Redmine::Views::OtherFormatsBuilder.new(self) yield Redmine::Views::OtherFormatsBuilder.new(self)
concat('</p>') concat('</p>')
end end
def page_header_title def page_header_title
if @project.nil? || @project.new_record? if @project.nil? || @project.new_record?
h(Setting.app_title) h(Setting.app_title)
else else
b = [] b = []
ancestors = (@project.root? ? [] : @project.ancestors.visible.all) ancestors = (@project.root? ? [] : @project.ancestors.visible)
if ancestors.any? if ancestors.any?
root = ancestors.shift root = ancestors.shift
b << link_to_project(root, {:jump => current_menu_item}, :class => 'root') b << link_to_project(root, {:jump => current_menu_item}, :class => 'root')
@@ -457,21 +451,21 @@ module ApplicationHelper
only_path = options.delete(:only_path) == false ? false : true only_path = options.delete(:only_path) == false ? false : true
text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) { |macro, args| exec_macro(macro, obj, args) } text = Redmine::WikiFormatting.to_html(Setting.text_formatting, text, :object => obj, :attribute => attr) { |macro, args| exec_macro(macro, obj, args) }
@parsed_headings = [] @parsed_headings = []
text = parse_non_pre_blocks(text) do |text| text = parse_non_pre_blocks(text) do |text|
[:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links, :parse_headings].each do |method_name| [:parse_inline_attachments, :parse_wiki_links, :parse_redmine_links, :parse_headings].each do |method_name|
send method_name, text, project, obj, attr, only_path, options send method_name, text, project, obj, attr, only_path, options
end end
end end
if @parsed_headings.any? if @parsed_headings.any?
replace_toc(text, @parsed_headings) replace_toc(text, @parsed_headings)
end end
text text
end end
def parse_non_pre_blocks(text) def parse_non_pre_blocks(text)
s = StringScanner.new(text) s = StringScanner.new(text)
tags = [] tags = []
@@ -500,13 +494,13 @@ module ApplicationHelper
end end
parsed parsed
end end
def parse_inline_attachments(text, project, obj, attr, only_path, options) def parse_inline_attachments(text, project, obj, attr, only_path, options)
# when using an image link, try to use an attachment, if possible # when using an image link, try to use an attachment, if possible
if options[:attachments] || (obj && obj.respond_to?(:attachments)) if options[:attachments] || (obj && obj.respond_to?(:attachments))
attachments = nil attachments = nil
text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m| text.gsub!(/src="([^\/"]+\.(bmp|gif|jpg|jpeg|png))"(\s+alt="([^"]*)")?/i) do |m|
filename, ext, alt, alttext = $1.downcase, $2, $3, $4 filename, ext, alt, alttext = $1.downcase, $2, $3, $4
attachments ||= (options[:attachments] || obj.attachments).sort_by(&:created_on).reverse attachments ||= (options[:attachments] || obj.attachments).sort_by(&:created_on).reverse
# search for the picture in attachments # search for the picture in attachments
if found = attachments.detect { |att| att.filename.downcase == filename } if found = attachments.detect { |att| att.filename.downcase == filename }
@@ -550,20 +544,15 @@ module ApplicationHelper
if page =~ /^(.+?)\#(.+)$/ if page =~ /^(.+?)\#(.+)$/
page, anchor = $1, $2 page, anchor = $1, $2
end end
anchor = sanitize_anchor_name(anchor) if anchor.present?
# check if page exists # check if page exists
wiki_page = link_project.wiki.find_page(page) wiki_page = link_project.wiki.find_page(page)
url = if anchor.present? && wiki_page.present? && (obj.is_a?(WikiContent) || obj.is_a?(WikiContent::Version)) && obj.page == wiki_page url = case options[:wiki_links]
"##{anchor}" when :local; "#{title}.html"
else
case options[:wiki_links]
when :local; "#{page.present? ? Wiki.titleize(page) : ''}.html" + (anchor.present? ? "##{anchor}" : '')
when :anchor; "##{title}" # used for single-file wiki export when :anchor; "##{title}" # used for single-file wiki export
else else
wiki_page_id = page.present? ? Wiki.titleize(page) : nil wiki_page_id = page.present? ? Wiki.titleize(page) : nil
url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project, :id => wiki_page_id, :anchor => anchor) url_for(:only_path => only_path, :controller => 'wiki', :action => 'show', :project_id => link_project, :id => wiki_page_id, :anchor => anchor)
end end
end
link_to((title || page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new'))) link_to((title || page), url, :class => ('wiki-page' + (wiki_page ? '' : ' new')))
else else
# project or wiki doesn't exist # project or wiki doesn't exist
@@ -574,7 +563,7 @@ module ApplicationHelper
end end
end end
end end
# Redmine links # Redmine links
# #
# Examples: # Examples:
@@ -599,26 +588,16 @@ module ApplicationHelper
# source:some/file#L120 -> Link to line 120 of the file # source:some/file#L120 -> Link to line 120 of the file
# source:some/file@52#L120 -> Link to line 120 of the file's revision 52 # source:some/file@52#L120 -> Link to line 120 of the file's revision 52
# export:some/file -> Force the download of the file # export:some/file -> Force the download of the file
# Forum messages: # Forum messages:
# message#1218 -> Link to message with id 1218 # message#1218 -> Link to message with id 1218
#
# Links can refer other objects from other projects, using project identifier:
# identifier:r52
# identifier:document:"Some document"
# identifier:version:1.0.0
# identifier:source:some/file
def parse_redmine_links(text, project, obj, attr, only_path, options) def parse_redmine_links(text, project, obj, attr, only_path, options)
text.gsub!(%r{([\s\(,\-\[\>]|^)(!)?(([a-z0-9\-]+):)?(attachment|document|version|commit|source|export|message|project)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|\]|<|$)}) do |m| text.gsub!(%r{([\s\(,\-\[\>]|^)(!)?(attachment|document|version|commit|source|export|message|project)?((#|r)(\d+)|(:)([^"\s<>][^\s<>]*?|"[^"]+?"))(?=(?=[[:punct:]]\W)|,|\s|\]|<|$)}) do |m|
leading, esc, project_prefix, project_identifier, prefix, sep, identifier = $1, $2, $3, $4, $5, $7 || $9, $8 || $10 leading, esc, prefix, sep, identifier = $1, $2, $3, $5 || $7, $6 || $8
link = nil link = nil
if project_identifier
project = Project.visible.find_by_identifier(project_identifier)
end
if esc.nil? if esc.nil?
if prefix.nil? && sep == 'r' if prefix.nil? && sep == 'r'
# project.changesets.visible raises an SQL error because of a double join on repositories if project && (changeset = project.changesets.find_by_revision(identifier))
if project && project.repository && (changeset = Changeset.visible.find_by_repository_id_and_revision(project.repository.id, identifier)) link = link_to("r#{identifier}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
link = link_to("#{project_prefix}r#{identifier}", {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
:class => 'changeset', :class => 'changeset',
:title => truncate_single_line(changeset.comments, :length => 100)) :title => truncate_single_line(changeset.comments, :length => 100))
end end
@@ -632,18 +611,24 @@ module ApplicationHelper
:title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})") :title => "#{truncate(issue.subject, :length => 100)} (#{issue.status.name})")
end end
when 'document' when 'document'
if document = Document.visible.find_by_id(oid) if document = Document.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document}, link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
:class => 'document' :class => 'document'
end end
when 'version' when 'version'
if version = Version.visible.find_by_id(oid) if version = Version.find_by_id(oid, :include => [:project], :conditions => Project.visible_by(User.current))
link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version}, link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
:class => 'version' :class => 'version'
end end
when 'message' when 'message'
if message = Message.visible.find_by_id(oid, :include => :parent) if message = Message.find_by_id(oid, :include => [:parent, {:board => :project}], :conditions => Project.visible_by(User.current))
link = link_to_message(message, {:only_path => only_path}, :class => 'message') link = link_to h(truncate(message.subject, :length => 60)), {:only_path => only_path,
:controller => 'messages',
:action => 'show',
:board_id => message.board,
:id => message.root,
:anchor => (message.parent ? "message-#{message.id}" : nil)},
:class => 'message'
end end
when 'project' when 'project'
if p = Project.visible.find_by_id(oid) if p = Project.visible.find_by_id(oid)
@@ -655,26 +640,26 @@ module ApplicationHelper
name = identifier.gsub(%r{^"(.*)"$}, "\\1") name = identifier.gsub(%r{^"(.*)"$}, "\\1")
case prefix case prefix
when 'document' when 'document'
if project && document = project.documents.visible.find_by_title(name) if project && document = project.documents.find_by_title(name)
link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document}, link = link_to h(document.title), {:only_path => only_path, :controller => 'documents', :action => 'show', :id => document},
:class => 'document' :class => 'document'
end end
when 'version' when 'version'
if project && version = project.versions.visible.find_by_name(name) if project && version = project.versions.find_by_name(name)
link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version}, link = link_to h(version.name), {:only_path => only_path, :controller => 'versions', :action => 'show', :id => version},
:class => 'version' :class => 'version'
end end
when 'commit' when 'commit'
if project && project.repository && (changeset = Changeset.visible.find(:first, :conditions => ["repository_id = ? AND scmid LIKE ?", project.repository.id, "#{name}%"])) if project && (changeset = project.changesets.find(:first, :conditions => ["scmid LIKE ?", "#{name}%"]))
link = link_to h("#{project_prefix}#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.identifier}, link = link_to h("#{name}"), {:only_path => only_path, :controller => 'repositories', :action => 'revision', :id => project, :rev => changeset.revision},
:class => 'changeset', :class => 'changeset',
:title => truncate_single_line(changeset.comments, :length => 100) :title => truncate_single_line(changeset.comments, :length => 100)
end end
when 'source', 'export' when 'source', 'export'
if project && project.repository && User.current.allowed_to?(:browse_repository, project) if project && project.repository
name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$} name =~ %r{^[/\\]*(.*?)(@([0-9a-f]+))?(#(L\d+))?$}
path, rev, anchor = $1, $3, $5 path, rev, anchor = $1, $3, $5
link = link_to h("#{project_prefix}#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project, link = link_to h("#{prefix}:#{name}"), {:controller => 'repositories', :action => 'entry', :id => project,
:path => to_path_param(path), :path => to_path_param(path),
:rev => rev, :rev => rev,
:anchor => anchor, :anchor => anchor,
@@ -694,28 +679,28 @@ module ApplicationHelper
end end
end end
end end
leading + (link || "#{project_prefix}#{prefix}#{sep}#{identifier}") leading + (link || "#{prefix}#{sep}#{identifier}")
end end
end end
HEADING_RE = /<h(1|2|3|4)( [^>]+)?>(.+?)<\/h(1|2|3|4)>/i unless const_defined?(:HEADING_RE) HEADING_RE = /<h(1|2|3|4)( [^>]+)?>(.+?)<\/h(1|2|3|4)>/i unless const_defined?(:HEADING_RE)
# Headings and TOC # Headings and TOC
# Adds ids and links to headings unless options[:headings] is set to false # Adds ids and links to headings unless options[:headings] is set to false
def parse_headings(text, project, obj, attr, only_path, options) def parse_headings(text, project, obj, attr, only_path, options)
return if options[:headings] == false return if options[:headings] == false
text.gsub!(HEADING_RE) do text.gsub!(HEADING_RE) do
level, attrs, content = $1.to_i, $2, $3 level, attrs, content = $1.to_i, $2, $3
item = strip_tags(content).strip item = strip_tags(content).strip
anchor = sanitize_anchor_name(item) anchor = item.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
@parsed_headings << [level, anchor, item] @parsed_headings << [level, anchor, item]
"<a name=\"#{anchor}\"></a>\n<h#{level} #{attrs}>#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>" "<h#{level} #{attrs} id=\"#{anchor}\">#{content}<a href=\"##{anchor}\" class=\"wiki-anchor\">&para;</a></h#{level}>"
end end
end end
TOC_RE = /<p>\{\{([<>]?)toc\}\}<\/p>/i unless const_defined?(:TOC_RE) TOC_RE = /<p>\{\{([<>]?)toc\}\}<\/p>/i unless const_defined?(:TOC_RE)
# Renders the TOC with given headings # Renders the TOC with given headings
def replace_toc(text, headings) def replace_toc(text, headings)
text.gsub!(TOC_RE) do text.gsub!(TOC_RE) do
@@ -798,13 +783,13 @@ module ApplicationHelper
), :class => 'progress', :style => "width: #{width};") + ), :class => 'progress', :style => "width: #{width};") +
content_tag('p', legend, :class => 'pourcent') content_tag('p', legend, :class => 'pourcent')
end end
def checked_image(checked=true) def checked_image(checked=true)
if checked if checked
image_tag 'toggle_check.png' image_tag 'toggle_check.png'
end end
end end
def context_menu(url) def context_menu(url)
unless @context_menu_included unless @context_menu_included
content_for :header_tags do content_for :header_tags do
@@ -852,15 +837,13 @@ module ApplicationHelper
'Calendar._FD = 1;' # Monday 'Calendar._FD = 1;' # Monday
when 7 when 7
'Calendar._FD = 0;' # Sunday 'Calendar._FD = 0;' # Sunday
when 6
'Calendar._FD = 6;' # Saturday
else else
'' # use language '' # use language
end end
javascript_include_tag('calendar/calendar') + javascript_include_tag('calendar/calendar') +
javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") + javascript_include_tag("calendar/lang/calendar-#{current_language.to_s.downcase}.js") +
javascript_tag(start_of_week) + javascript_tag(start_of_week) +
javascript_include_tag('calendar/calendar-setup') + javascript_include_tag('calendar/calendar-setup') +
stylesheet_link_tag('calendar') stylesheet_link_tag('calendar')
end end
@@ -894,27 +877,10 @@ module ApplicationHelper
end end
end end
def sanitize_anchor_name(anchor)
anchor.gsub(%r{[^\w\s\-]}, '').gsub(%r{\s+(\-+\s*)?}, '-')
end
# Returns the javascript tags that are included in the html layout head
def javascript_heads
tags = javascript_include_tag(:defaults)
unless User.current.pref.warn_on_leaving_unsaved == '0'
tags << "\n" + javascript_tag("Event.observe(window, 'load', function(){ new WarnLeavingUnsaved('#{escape_javascript( l(:text_warn_on_leaving_unsaved) )}'); });")
end
tags
end
def favicon def favicon
"<link rel='shortcut icon' href='#{image_path('/favicon.ico')}' />" "<link rel='shortcut icon' href='#{image_path('/favicon.ico')}' />"
end end
def robot_exclusion_tag
'<meta name="robots" content="noindex,follow,noarchive" />'
end
# Returns true if arg is expected in the API response # Returns true if arg is expected in the API response
def include_in_api_response?(arg) def include_in_api_response?(arg)
unless @included_in_api_response unless @included_in_api_response
@@ -936,7 +902,7 @@ module ApplicationHelper
options options
end end
end end
private private
def wiki_helper def wiki_helper
@@ -944,8 +910,12 @@ module ApplicationHelper
extend helper extend helper
return self return self
end end
def link_to_content_update(text, url_params = {}, html_options = {}) def link_to_remote_content_update(text, url_params)
link_to(text, url_params, html_options) link_to_remote(text,
{:url => url_params, :method => :get, :update => 'content', :complete => 'window.scrollTo(0,0)'},
{:href => url_for(:params => url_params)}
)
end end
end end
+7 -19
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -21,26 +21,14 @@ module AttachmentsHelper
# :author -- author names are not displayed if set to false # :author -- author names are not displayed if set to false
def link_to_attachments(container, options = {}) def link_to_attachments(container, options = {})
options.assert_valid_keys(:author) options.assert_valid_keys(:author)
if container.attachments.any? if container.attachments.any?
options = {:deletable => container.attachments_deletable?, :author => true}.merge(options) options = {:deletable => container.attachments_deletable?, :author => true}.merge(options)
render :partial => 'attachments/links', :locals => {:attachments => container.attachments, :options => options} render :partial => 'attachments/links', :locals => {:attachments => container.attachments, :options => options}
end end
end end
def to_utf8(str) def to_utf8(str)
if str.respond_to?(:force_encoding) str
str.force_encoding('UTF-8')
return str if str.valid_encoding?
else
return str if /\A[\r\n\t\x20-\x7e]*\Z/n.match(str) # for us-ascii
end
begin
Iconv.conv('UTF-8//IGNORE', 'UTF-8', str + ' ')[0..-3]
rescue Iconv::InvalidEncoding
# "UTF-8//IGNORE" is not supported on some OS
str
end
end end
end end
+9 -1
View File
@@ -32,6 +32,14 @@ module CalendarsHelper
end end
def link_to_month(link_name, year, month, options={}) def link_to_month(link_name, year, month, options={})
link_to_content_update(link_name, params.merge(:year => year, :month => month)) project_id = options[:project].present? ? options[:project].to_param : nil
link_target = calendar_path(:year => year, :month => month, :project_id => project_id)
link_to_remote(link_name,
{:update => "content", :url => link_target, :method => :put},
{:href => link_target})
end end
end end
+5 -5
View File
@@ -49,7 +49,7 @@ module CustomFieldsHelper
blank_option = custom_field.is_required? ? blank_option = custom_field.is_required? ?
(custom_field.default_value.blank? ? "<option value=\"\">--- #{l(:actionview_instancetag_blank_option)} ---</option>" : '') : (custom_field.default_value.blank? ? "<option value=\"\">--- #{l(:actionview_instancetag_blank_option)} ---</option>" : '') :
'<option></option>' '<option></option>'
select_tag(field_name, blank_option + options_for_select(custom_field.possible_values_options(custom_value.customized), custom_value.value), :id => field_id) select_tag(field_name, blank_option + options_for_select(custom_field.possible_values, custom_value.value), :id => field_id)
else else
text_field_tag(field_name, custom_value.value, :id => field_id) text_field_tag(field_name, custom_value.value, :id => field_id)
end end
@@ -68,7 +68,7 @@ module CustomFieldsHelper
custom_field_label_tag(name, custom_value) + custom_field_tag(name, custom_value) custom_field_label_tag(name, custom_value) + custom_field_tag(name, custom_value)
end end
def custom_field_tag_for_bulk_edit(name, custom_field, projects=nil) def custom_field_tag_for_bulk_edit(name, custom_field)
field_name = "#{name}[custom_field_values][#{custom_field.id}]" field_name = "#{name}[custom_field_values][#{custom_field.id}]"
field_id = "#{name}_custom_field_values_#{custom_field.id}" field_id = "#{name}_custom_field_values_#{custom_field.id}"
field_format = Redmine::CustomFieldFormat.find_by_name(custom_field.field_format) field_format = Redmine::CustomFieldFormat.find_by_name(custom_field.field_format)
@@ -83,7 +83,7 @@ module CustomFieldsHelper
[l(:general_text_yes), '1'], [l(:general_text_yes), '1'],
[l(:general_text_no), '0']]), :id => field_id) [l(:general_text_no), '0']]), :id => field_id)
when "list" when "list"
select_tag(field_name, options_for_select([[l(:label_no_change_option), '']] + custom_field.possible_values_options(projects)), :id => field_id) select_tag(field_name, options_for_select([[l(:label_no_change_option), '']] + custom_field.possible_values), :id => field_id)
else else
text_field_tag(field_name, '', :id => field_id) text_field_tag(field_name, '', :id => field_id)
end end
@@ -101,8 +101,8 @@ module CustomFieldsHelper
end end
# Return an array of custom field formats which can be used in select_tag # Return an array of custom field formats which can be used in select_tag
def custom_field_formats_for_select(custom_field) def custom_field_formats_for_select
Redmine::CustomFieldFormat.as_select(custom_field.class.customized_class.name) Redmine::CustomFieldFormat.as_select
end end
# Renders the custom_values in api views # Renders the custom_values in api views
+16 -8
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -21,21 +21,29 @@ module GanttHelper
case in_or_out case in_or_out
when :in when :in
if gantt.zoom < 4 if gantt.zoom < 4
link_to_content_update l(:text_zoom_in), link_to_remote(l(:text_zoom_in),
params.merge(gantt.params.merge(:zoom => (gantt.zoom+1))), {:url => gantt.params.merge(:zoom => (gantt.zoom+1)), :method => :get, :update => 'content'},
:class => 'icon icon-zoom-in' {:href => url_for(gantt.params.merge(:zoom => (gantt.zoom+1))),
:class => 'icon icon-zoom-in'})
else else
content_tag('span', l(:text_zoom_in), :class => 'icon icon-zoom-in') content_tag('span', l(:text_zoom_in), :class => 'icon icon-zoom-in')
end end
when :out when :out
if gantt.zoom > 1 if gantt.zoom > 1
link_to_content_update l(:text_zoom_out), link_to_remote(l(:text_zoom_out),
params.merge(gantt.params.merge(:zoom => (gantt.zoom-1))), {:url => gantt.params.merge(:zoom => (gantt.zoom-1)), :method => :get, :update => 'content'},
:class => 'icon icon-zoom-out' {:href => url_for(gantt.params.merge(:zoom => (gantt.zoom-1))),
:class => 'icon icon-zoom-out'})
else else
content_tag('span', l(:text_zoom_out), :class => 'icon icon-zoom-out') content_tag('span', l(:text_zoom_out), :class => 'icon icon-zoom-out')
end end
end end
end end
def number_of_issues_on_versions(gantt)
versions = gantt.events.collect {|event| (event.is_a? Version) ? event : nil}.compact
versions.sum {|v| v.fixed_issues.for_gantt.with_query(@query).count}
end
end end
+24 -84
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -54,30 +54,20 @@ module IssuesHelper
"<strong>#{@cached_label_assigned_to}</strong>: #{issue.assigned_to}<br />" + "<strong>#{@cached_label_assigned_to}</strong>: #{issue.assigned_to}<br />" +
"<strong>#{@cached_label_priority}</strong>: #{issue.priority.name}" "<strong>#{@cached_label_priority}</strong>: #{issue.priority.name}"
end end
def issue_heading(issue)
h("#{issue.tracker} ##{issue.id}")
end
def render_issue_subject_with_tree(issue) def render_issue_subject_with_tree(issue)
s = '' s = ''
ancestors = issue.root? ? [] : issue.ancestors.visible.all issue.ancestors.each do |ancestor|
ancestors.each do |ancestor|
s << '<div>' + content_tag('p', link_to_issue(ancestor)) s << '<div>' + content_tag('p', link_to_issue(ancestor))
end end
s << '<div>' s << '<div>' + content_tag('h3', h(issue.subject))
subject = h(issue.subject) s << '</div>' * (issue.ancestors.size + 1)
if issue.is_private?
subject = content_tag('span', l(:field_is_private), :class => 'private') + ' ' + subject
end
s << content_tag('h3', subject)
s << '</div>' * (ancestors.size + 1)
s s
end end
def render_descendants_tree(issue) def render_descendants_tree(issue)
s = '<form><table class="list issues">' s = '<form><table class="list issues">'
issue_list(issue.descendants.visible.sort_by(&:lft)) do |child, level| issue_list(issue.descendants.sort_by(&:lft)) do |child, level|
s << content_tag('tr', s << content_tag('tr',
content_tag('td', check_box_tag("ids[]", child.id, false, :id => nil), :class => 'checkbox') + content_tag('td', check_box_tag("ids[]", child.id, false, :id => nil), :class => 'checkbox') +
content_tag('td', link_to_issue(child, :truncate => 60), :class => 'subject') + content_tag('td', link_to_issue(child, :truncate => 60), :class => 'subject') +
@@ -89,7 +79,7 @@ module IssuesHelper
s << '</form></table>' s << '</form></table>'
s s
end end
def render_custom_fields_rows(issue) def render_custom_fields_rows(issue)
return if issue.custom_field_values.empty? return if issue.custom_field_values.empty?
ordered_values = [] ordered_values = []
@@ -108,58 +98,21 @@ module IssuesHelper
s << "</tr>\n" s << "</tr>\n"
s s
end end
def issues_destroy_confirmation_message(issues)
issues = [issues] unless issues.is_a?(Array)
message = l(:text_issues_destroy_confirmation)
descendant_count = issues.inject(0) {|memo, i| memo += (i.right - i.left - 1)/2}
if descendant_count > 0
issues.each do |issue|
next if issue.root?
issues.each do |other_issue|
descendant_count -= 1 if issue.is_descendant_of?(other_issue)
end
end
if descendant_count > 0
message << "\n" + l(:text_issues_destroy_descendants_confirmation, :count => descendant_count)
end
end
message
end
def sidebar_queries def sidebar_queries
unless @sidebar_queries unless @sidebar_queries
# User can see public queries and his own queries # User can see public queries and his own queries
visible = ARCondition.new(["is_public = ? OR user_id = ?", true, (User.current.logged? ? User.current.id : 0)]) visible = ARCondition.new(["is_public = ? OR user_id = ?", true, (User.current.logged? ? User.current.id : 0)])
# Project specific queries and global queries # Project specific queries and global queries
visible << (@project.nil? ? ["project_id IS NULL"] : ["project_id IS NULL OR project_id = ?", @project.id]) visible << (@project.nil? ? ["project_id IS NULL"] : ["project_id IS NULL OR project_id = ?", @project.id])
@sidebar_queries = Query.find(:all, @sidebar_queries = Query.find(:all,
:select => 'id, name, is_public', :select => 'id, name',
:order => "name ASC", :order => "name ASC",
:conditions => visible.conditions) :conditions => visible.conditions)
end end
@sidebar_queries @sidebar_queries
end end
def query_links(title, queries)
# links to #index on issues/show
url_params = controller_name == 'issues' ? {:controller => 'issues', :action => 'index', :project_id => @project} : params
content_tag('h3', title) +
queries.collect {|query|
link_to(h(query.name), url_params.merge(:query_id => query))
}.join('<br />')
end
def render_sidebar_queries
out = ''
queries = sidebar_queries.select {|q| !q.is_public?}
out << query_links(l(:label_my_queries), queries) if queries.any?
queries = sidebar_queries.select {|q| q.is_public?}
out << query_links(l(:label_query_plural), queries) if queries.any?
out
end
def show_detail(detail, no_html=false) def show_detail(detail, no_html=false)
case detail.property case detail.property
when 'attr' when 'attr'
@@ -182,10 +135,6 @@ module IssuesHelper
label = l(:field_parent_issue) label = l(:field_parent_issue)
value = "##{detail.value}" unless detail.value.blank? value = "##{detail.value}" unless detail.value.blank?
old_value = "##{detail.old_value}" unless detail.old_value.blank? old_value = "##{detail.old_value}" unless detail.old_value.blank?
when detail.prop_key == 'is_private'
value = l(detail.value == "0" ? :general_text_No : :general_text_Yes) unless detail.value.blank?
old_value = l(detail.old_value == "0" ? :general_text_No : :general_text_Yes) unless detail.old_value.blank?
end end
when 'cf' when 'cf'
custom_field = CustomField.find_by_id(detail.prop_key) custom_field = CustomField.find_by_id(detail.prop_key)
@@ -202,7 +151,7 @@ module IssuesHelper
label ||= detail.prop_key label ||= detail.prop_key
value ||= detail.value value ||= detail.value
old_value ||= detail.old_value old_value ||= detail.old_value
unless no_html unless no_html
label = content_tag('strong', label) label = content_tag('strong', label)
old_value = content_tag("i", h(old_value)) if detail.old_value old_value = content_tag("i", h(old_value)) if detail.old_value
@@ -214,17 +163,8 @@ module IssuesHelper
value = content_tag("i", h(value)) if value value = content_tag("i", h(value)) if value
end end
end end
if detail.property == 'attr' && detail.prop_key == 'description' if !detail.value.blank?
s = l(:text_journal_changed_no_detail, :label => label)
unless no_html
diff_link = link_to 'diff',
{:controller => 'journals', :action => 'diff', :id => detail.journal_id, :detail_id => detail.id},
:title => l(:label_view_diff)
s << " (#{ diff_link })"
end
s
elsif !detail.value.blank?
case detail.property case detail.property
when 'attr', 'cf' when 'attr', 'cf'
if !detail.old_value.blank? if !detail.old_value.blank?
@@ -248,7 +188,7 @@ module IssuesHelper
return record.name if record return record.name if record
end end
end end
# Renders issue children recursively # Renders issue children recursively
def render_api_issue_children(issue, api) def render_api_issue_children(issue, api)
return if issue.leaf? return if issue.leaf?
@@ -262,14 +202,14 @@ module IssuesHelper
end end
end end
end end
def issues_to_csv(issues, project = nil) def issues_to_csv(issues, project = nil)
ic = Iconv.new(l(:general_csv_encoding), 'UTF-8') ic = Iconv.new(l(:general_csv_encoding), 'UTF-8')
decimal_separator = l(:general_csv_decimal_separator) decimal_separator = l(:general_csv_decimal_separator)
export = FCSV.generate(:col_sep => l(:general_csv_separator)) do |csv| export = FCSV.generate(:col_sep => l(:general_csv_separator)) do |csv|
# csv header fields # csv header fields
headers = [ "#", headers = [ "#",
l(:field_status), l(:field_status),
l(:field_project), l(:field_project),
l(:field_tracker), l(:field_tracker),
l(:field_priority), l(:field_priority),
@@ -296,9 +236,9 @@ module IssuesHelper
# csv lines # csv lines
issues.each do |issue| issues.each do |issue|
fields = [issue.id, fields = [issue.id,
issue.status.name, issue.status.name,
issue.project.name, issue.project.name,
issue.tracker.name, issue.tracker.name,
issue.priority.name, issue.priority.name,
issue.subject, issue.subject,
issue.assigned_to, issue.assigned_to,
@@ -310,7 +250,7 @@ module IssuesHelper
issue.done_ratio, issue.done_ratio,
issue.estimated_hours.to_s.gsub('.', decimal_separator), issue.estimated_hours.to_s.gsub('.', decimal_separator),
issue.parent_id, issue.parent_id,
format_time(issue.created_on), format_time(issue.created_on),
format_time(issue.updated_on) format_time(issue.updated_on)
] ]
custom_fields.each {|f| fields << show_value(issue.custom_value_for(f)) } custom_fields.each {|f| fields << show_value(issue.custom_value_for(f)) }
+10
View File
@@ -16,4 +16,14 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
module MessagesHelper module MessagesHelper
def link_to_message(message)
return '' unless message
link_to h(truncate(message.subject, :length => 60)), :controller => 'messages',
:action => 'show',
:board_id => message.board_id,
:id => message.root,
:r => (message.parent_id && message.id),
:anchor => (message.parent_id ? "message-#{message.id}" : nil)
end
end end
+11 -11
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -20,7 +20,7 @@ module ProjectsHelper
return '' unless version && version.is_a?(Version) return '' unless version && version.is_a?(Version)
link_to_if version.visible?, format_version_name(version), { :controller => 'versions', :action => 'show', :id => version }, options link_to_if version.visible?, format_version_name(version), { :controller => 'versions', :action => 'show', :id => version }, options
end end
def project_settings_tabs def project_settings_tabs
tabs = [{:name => 'info', :action => :edit_project, :partial => 'projects/edit', :label => :label_information_plural}, tabs = [{:name => 'info', :action => :edit_project, :partial => 'projects/edit', :label => :label_information_plural},
{:name => 'modules', :action => :select_project_modules, :partial => 'projects/settings/modules', :label => :label_module_plural}, {:name => 'modules', :action => :select_project_modules, :partial => 'projects/settings/modules', :label => :label_module_plural},
@@ -32,9 +32,9 @@ module ProjectsHelper
{:name => 'boards', :action => :manage_boards, :partial => 'projects/settings/boards', :label => :label_board_plural}, {:name => 'boards', :action => :manage_boards, :partial => 'projects/settings/boards', :label => :label_board_plural},
{:name => 'activities', :action => :manage_project_activities, :partial => 'projects/settings/activities', :label => :enumeration_activities} {:name => 'activities', :action => :manage_project_activities, :partial => 'projects/settings/activities', :label => :enumeration_activities}
] ]
tabs.select {|tab| User.current.allowed_to?(tab[:action], @project)} tabs.select {|tab| User.current.allowed_to?(tab[:action], @project)}
end end
def parent_project_select_tag(project) def parent_project_select_tag(project)
selected = project.parent selected = project.parent
# retrieve the requested parent project # retrieve the requested parent project
@@ -42,13 +42,13 @@ module ProjectsHelper
if parent_id if parent_id
selected = (parent_id.blank? ? nil : Project.find(parent_id)) selected = (parent_id.blank? ? nil : Project.find(parent_id))
end end
options = '' options = ''
options << "<option value=''></option>" if project.allowed_parents.include?(nil) options << "<option value=''></option>" if project.allowed_parents.include?(nil)
options << project_tree_options_for_select(project.allowed_parents.compact, :selected => selected) options << project_tree_options_for_select(project.allowed_parents.compact, :selected => selected)
content_tag('select', options, :name => 'project[parent_id]', :id => 'project_parent_id') content_tag('select', options, :name => 'project[parent_id]', :id => 'project_parent_id')
end end
# Renders a tree of projects as a nested set of unordered lists # Renders a tree of projects as a nested set of unordered lists
# The given collection may be a subset of the whole project tree # The given collection may be a subset of the whole project tree
# (eg. some intermediate nodes are private and can not be seen) # (eg. some intermediate nodes are private and can not be seen)
@@ -65,7 +65,7 @@ module ProjectsHelper
else else
ancestors.pop ancestors.pop
s << "</li>" s << "</li>"
while (ancestors.any? && !project.is_descendant_of?(ancestors.last)) while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
ancestors.pop ancestors.pop
s << "</ul></li>\n" s << "</ul></li>\n"
end end
@@ -93,7 +93,7 @@ module ProjectsHelper
if selected && !versions.include?(selected) if selected && !versions.include?(selected)
grouped[selected.project.name] << [selected.name, selected.id] grouped[selected.project.name] << [selected.name, selected.id]
end end
if grouped.keys.size > 1 if grouped.keys.size > 1
grouped_options_for_select(grouped, selected && selected.id) grouped_options_for_select(grouped, selected && selected.id)
else else
+5 -6
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -70,7 +70,6 @@ module QueriesHelper
cond = "project_id IS NULL" cond = "project_id IS NULL"
cond << " OR project_id = #{@project.id}" if @project cond << " OR project_id = #{@project.id}" if @project
@query = Query.find(params[:query_id], :conditions => cond) @query = Query.find(params[:query_id], :conditions => cond)
raise ::Unauthorized unless @query.visible?
@query.project = @project @query.project = @project
session[:query] = {:id => @query.id, :project_id => @query.project_id} session[:query] = {:id => @query.id, :project_id => @query.project_id}
sort_clear sort_clear
@@ -79,16 +78,16 @@ module QueriesHelper
# Give it a name, required to be valid # Give it a name, required to be valid
@query = Query.new(:name => "_") @query = Query.new(:name => "_")
@query.project = @project @query.project = @project
if params[:fields] || params[:f] if params[:fields]
@query.filters = {} @query.filters = {}
@query.add_filters(params[:fields] || params[:f], params[:operators] || params[:op], params[:values] || params[:v]) @query.add_filters(params[:fields], params[:operators], params[:values])
else else
@query.available_filters.keys.each do |field| @query.available_filters.keys.each do |field|
@query.add_short_filter(field, params[field]) if params[field] @query.add_short_filter(field, params[field]) if params[field]
end end
end end
@query.group_by = params[:group_by] @query.group_by = params[:group_by]
@query.column_names = params[:c] || (params[:query] && params[:query][:column_names]) @query.column_names = params[:query] && params[:query][:column_names]
session[:query] = {:project_id => @query.project_id, :filters => @query.filters, :group_by => @query.group_by, :column_names => @query.column_names} session[:query] = {:project_id => @query.project_id, :filters => @query.filters, :group_by => @query.group_by, :column_names => @query.column_names}
else else
@query = Query.find_by_id(session[:query][:id]) if session[:query][:id] @query = Query.find_by_id(session[:query][:id]) if session[:query][:id]
+7 -7
View File
@@ -1,22 +1,22 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
module ReportsHelper module ReportsHelper
def aggregate(data, criteria) def aggregate(data, criteria)
a = 0 a = 0
data.each { |row| data.each { |row|
@@ -28,9 +28,9 @@ module ReportsHelper
} unless data.nil? } unless data.nil?
a a
end end
def aggregate_link(data, criteria, *args) def aggregate_link(data, criteria, *args)
a = aggregate data, criteria a = aggregate data, criteria
a > 0 ? link_to(a, *args) : '-' a > 0 ? link_to(a, *args) : '-'
end end
end end
+40 -132
View File
@@ -1,22 +1,21 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require 'iconv' require 'iconv'
require 'redmine/codeset_util'
module RepositoriesHelper module RepositoriesHelper
def format_revision(revision) def format_revision(revision)
@@ -26,13 +25,13 @@ module RepositoriesHelper
revision.to_s revision.to_s
end end
end end
def truncate_at_line_break(text, length = 255) def truncate_at_line_break(text, length = 255)
if text if text
text.gsub(%r{^(.{#{length}}[^\n]*)\n.+$}m, '\\1...') text.gsub(%r{^(.{#{length}}[^\n]*)\n.+$}m, '\\1...')
end end
end end
def render_properties(properties) def render_properties(properties)
unless properties.nil? || properties.empty? unless properties.nil? || properties.empty?
content = '' content = ''
@@ -42,15 +41,14 @@ module RepositoriesHelper
content_tag('ul', content, :class => 'properties') content_tag('ul', content, :class => 'properties')
end end
end end
def render_changeset_changes def render_changeset_changes
changes = @changeset.changes.find(:all, :limit => 1000, :order => 'path').collect do |change| changes = @changeset.changes.find(:all, :limit => 1000, :order => 'path').collect do |change|
case change.action case change.action
when 'A' when 'A'
# Detects moved/copied files # Detects moved/copied files
if !change.from_path.blank? if !change.from_path.blank?
change.action = change.action = @changeset.changes.detect {|c| c.action == 'D' && c.path == change.from_path} ? 'R' : 'C'
@changeset.changes.detect {|c| c.action == 'D' && c.path == change.from_path} ? 'R' : 'C'
end end
change change
when 'D' when 'D'
@@ -58,8 +56,8 @@ module RepositoriesHelper
else else
change change
end end
end.compact end.compact
tree = { } tree = { }
changes.each do |change| changes.each do |change|
p = tree p = tree
@@ -74,11 +72,13 @@ module RepositoriesHelper
end end
p[:c] = change p[:c] = change
end end
render_changes_tree(tree[:s]) render_changes_tree(tree[:s])
end end
def render_changes_tree(tree) def render_changes_tree(tree)
return '' if tree.nil? return '' if tree.nil?
output = '' output = ''
output << '<ul>' output << '<ul>'
tree.keys.sort.each do |file| tree.keys.sort.each do |file|
@@ -115,26 +115,9 @@ module RepositoriesHelper
output << '</ul>' output << '</ul>'
output output
end end
def to_utf8(str) def to_utf8(str)
return str if str.nil?
str = to_utf8_internal(str)
if str.respond_to?(:force_encoding)
str.force_encoding('UTF-8')
end
str
end
def to_utf8_internal(str)
return str if str.nil?
if str.respond_to?(:force_encoding)
str.force_encoding('ASCII-8BIT')
end
return str if str.empty?
return str if /\A[\r\n\t\x20-\x7e]*\Z/n.match(str) # for us-ascii return str if /\A[\r\n\t\x20-\x7e]*\Z/n.match(str) # for us-ascii
if str.respond_to?(:force_encoding)
str.force_encoding('UTF-8')
end
@encodings ||= Setting.repositories_encodings.split(',').collect(&:strip) @encodings ||= Setting.repositories_encodings.split(',').collect(&:strip)
@encodings.each do |encoding| @encodings.each do |encoding|
begin begin
@@ -143,142 +126,67 @@ module RepositoriesHelper
# do nothing here and try the next encoding # do nothing here and try the next encoding
end end
end end
str = Redmine::CodesetUtil.replace_invalid_utf8(str) str
end end
private :to_utf8_internal
def repository_field_tags(form, repository)
def repository_field_tags(form, repository)
method = repository.class.name.demodulize.underscore + "_field_tags" method = repository.class.name.demodulize.underscore + "_field_tags"
if repository.is_a?(Repository) && send(method, form, repository) if repository.is_a?(Repository) && respond_to?(method) && method != 'repository_field_tags'
respond_to?(method) && method != 'repository_field_tags'
send(method, form, repository)
end
end end
def scm_select_tag(repository) def scm_select_tag(repository)
scm_options = [["--- #{l(:actionview_instancetag_blank_option)} ---", '']] scm_options = [["--- #{l(:actionview_instancetag_blank_option)} ---", '']]
Redmine::Scm::Base.all.each do |scm| Redmine::Scm::Base.all.each do |scm|
if Setting.enabled_scm.include?(scm) || scm_options << ["Repository::#{scm}".constantize.scm_name, scm] if Setting.enabled_scm.include?(scm) || (repository && repository.class.name.demodulize == scm)
(repository && repository.class.name.demodulize == scm)
scm_options << ["Repository::#{scm}".constantize.scm_name, scm]
end
end end
select_tag('repository_scm',
select_tag('repository_scm',
options_for_select(scm_options, repository.class.name.demodulize), options_for_select(scm_options, repository.class.name.demodulize),
:disabled => (repository && !repository.new_record?), :disabled => (repository && !repository.new_record?),
:onchange => remote_function( :onchange => remote_function(:url => { :controller => 'repositories', :action => 'edit', :id => @project }, :method => :get, :with => "Form.serialize(this.form)")
:url => { )
:controller => 'repositories',
:action => 'edit',
:id => @project
},
:method => :get,
:with => "Form.serialize(this.form)")
)
end end
def with_leading_slash(path) def with_leading_slash(path)
path.to_s.starts_with?('/') ? path : "/#{path}" path.to_s.starts_with?('/') ? path : "/#{path}"
end end
def without_leading_slash(path) def without_leading_slash(path)
path.gsub(%r{^/+}, '') path.gsub(%r{^/+}, '')
end end
def subversion_field_tags(form, repository) def subversion_field_tags(form, repository)
content_tag('p', form.text_field(:url, :size => 60, :required => true, content_tag('p', form.text_field(:url, :size => 60, :required => true, :disabled => (repository && !repository.root_url.blank?)) +
:disabled => (repository && !repository.root_url.blank?)) +
'<br />(file:///, http://, https://, svn://, svn+[tunnelscheme]://)') + '<br />(file:///, http://, https://, svn://, svn+[tunnelscheme]://)') +
content_tag('p', form.text_field(:login, :size => 30)) + content_tag('p', form.text_field(:login, :size => 30)) +
content_tag('p', form.password_field( content_tag('p', form.password_field(:password, :size => 30, :name => 'ignore',
:password, :size => 30, :name => 'ignore', :value => ((repository.new_record? || repository.password.blank?) ? '' : ('x'*15)),
:value => ((repository.new_record? || repository.password.blank?) ? '' : ('x'*15)), :onfocus => "this.value=''; this.name='repository[password]';",
:onfocus => "this.value=''; this.name='repository[password]';", :onchange => "this.name='repository[password]';"))
:onchange => "this.name='repository[password]';"))
end end
def darcs_field_tags(form, repository) def darcs_field_tags(form, repository)
content_tag('p', form.text_field( content_tag('p', form.text_field(:url, :label => 'Root directory', :size => 60, :required => true, :disabled => (repository && !repository.new_record?)))
:url, :label => l(:field_path_to_repository),
:size => 60, :required => true,
:disabled => (repository && !repository.new_record?))) +
content_tag('p', form.select(
:log_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_commit_logs_encoding), :required => true))
end end
def mercurial_field_tags(form, repository) def mercurial_field_tags(form, repository)
content_tag('p', form.text_field( content_tag('p', form.text_field(:url, :label => 'Root directory', :size => 60, :required => true, :disabled => (repository && !repository.root_url.blank?)))
:url, :label => l(:field_path_to_repository),
:size => 60, :required => true,
:disabled => (repository && !repository.root_url.blank?)
) +
'<br />' + l(:text_mercurial_repository_note)) +
content_tag('p', form.select(
:path_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_scm_path_encoding)
) +
'<br />' + l(:text_scm_path_encoding_note))
end end
def git_field_tags(form, repository) def git_field_tags(form, repository)
content_tag('p', form.text_field( content_tag('p', form.text_field(:url, :label => 'Path to .git directory', :size => 60, :required => true, :disabled => (repository && !repository.root_url.blank?)))
:url, :label => l(:field_path_to_repository),
:size => 60, :required => true,
:disabled => (repository && !repository.root_url.blank?)
) +
'<br />' + l(:text_git_repository_note)) +
content_tag('p', form.select(
:path_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_scm_path_encoding)
) +
'<br />' + l(:text_scm_path_encoding_note)) +
content_tag('p', form.check_box(
:extra_report_last_commit,
:label => l(:label_git_report_last_commit)
))
end end
def cvs_field_tags(form, repository) def cvs_field_tags(form, repository)
content_tag('p', form.text_field( content_tag('p', form.text_field(:root_url, :label => 'CVSROOT', :size => 60, :required => true, :disabled => !repository.new_record?)) +
:root_url, content_tag('p', form.text_field(:url, :label => 'Module', :size => 30, :required => true, :disabled => !repository.new_record?))
:label => l(:field_cvsroot),
:size => 60, :required => true,
:disabled => !repository.new_record?)) +
content_tag('p', form.text_field(
:url,
:label => l(:field_cvs_module),
:size => 30, :required => true,
:disabled => !repository.new_record?)) +
content_tag('p', form.select(
:log_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_commit_logs_encoding), :required => true)) +
content_tag('p', form.select(
:path_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_scm_path_encoding)
) +
'<br />' + l(:text_scm_path_encoding_note))
end end
def bazaar_field_tags(form, repository) def bazaar_field_tags(form, repository)
content_tag('p', form.text_field( content_tag('p', form.text_field(:url, :label => 'Root directory', :size => 60, :required => true, :disabled => (repository && !repository.new_record?)))
:url, :label => l(:field_path_to_repository),
:size => 60, :required => true,
:disabled => (repository && !repository.new_record?))) +
content_tag('p', form.select(
:log_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_commit_logs_encoding), :required => true))
end end
def filesystem_field_tags(form, repository) def filesystem_field_tags(form, repository)
content_tag('p', form.text_field( content_tag('p', form.text_field(:url, :label => 'Root directory', :size => 60, :required => true, :disabled => (repository && !repository.root_url.blank?)))
:url, :label => l(:field_root_directory),
:size => 60, :required => true,
:disabled => (repository && !repository.root_url.blank?))) +
content_tag('p', form.select(
:path_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_scm_path_encoding)
) +
'<br />' + l(:text_scm_path_encoding_note))
end end
end end
+3 -3
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -57,7 +57,7 @@ module SearchHelper
c = results_by_type[t] c = results_by_type[t]
next if c == 0 next if c == 0
text = "#{type_label(t)} (#{c})" text = "#{type_label(t)} (#{c})"
links << link_to(text, :q => params[:q], :titles_only => params[:titles_only], :all_words => params[:all_words], :scope => params[:scope], t => 1) links << link_to(text, :q => params[:q], :titles_only => params[:title_only], :all_words => params[:all_words], :scope => params[:scope], t => 1)
end end
('<ul>' + links.map {|link| content_tag('li', link)}.join(' ') + '</ul>') unless links.empty? ('<ul>' + links.map {|link| content_tag('li', link)}.join(' ') + '</ul>') unless links.empty?
end end
+16 -23
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2009 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -27,53 +27,46 @@ module SettingsHelper
{:name => 'repositories', :partial => 'settings/repositories', :label => :label_repository_plural} {:name => 'repositories', :partial => 'settings/repositories', :label => :label_repository_plural}
] ]
end end
def setting_select(setting, choices, options={}) def setting_select(setting, choices, options={})
if blank_text = options.delete(:blank) if blank_text = options.delete(:blank)
choices = [[blank_text.is_a?(Symbol) ? l(blank_text) : blank_text, '']] + choices choices = [[blank_text.is_a?(Symbol) ? l(blank_text) : blank_text, '']] + choices
end end
setting_label(setting, options) + setting_label(setting, options) +
select_tag("settings[#{setting}]", select_tag("settings[#{setting}]", options_for_select(choices, Setting.send(setting).to_s), options)
options_for_select(choices, Setting.send(setting).to_s),
options)
end end
def setting_multiselect(setting, choices, options={}) def setting_multiselect(setting, choices, options={})
setting_values = Setting.send(setting) setting_values = Setting.send(setting)
setting_values = [] unless setting_values.is_a?(Array) setting_values = [] unless setting_values.is_a?(Array)
setting_label(setting, options) + setting_label(setting, options) +
hidden_field_tag("settings[#{setting}][]", '') + hidden_field_tag("settings[#{setting}][]", '') +
choices.collect do |choice| choices.collect do |choice|
text, value = (choice.is_a?(Array) ? choice : [choice, choice]) text, value = (choice.is_a?(Array) ? choice : [choice, choice])
content_tag( content_tag('label',
'label', check_box_tag("settings[#{setting}][]", value, Setting.send(setting).include?(value)) + text.to_s,
check_box_tag(
"settings[#{setting}][]",
value,
Setting.send(setting).include?(value)
) + text.to_s,
:class => 'block' :class => 'block'
) )
end.join end.join
end end
def setting_text_field(setting, options={}) def setting_text_field(setting, options={})
setting_label(setting, options) + setting_label(setting, options) +
text_field_tag("settings[#{setting}]", Setting.send(setting), options) text_field_tag("settings[#{setting}]", Setting.send(setting), options)
end end
def setting_text_area(setting, options={}) def setting_text_area(setting, options={})
setting_label(setting, options) + setting_label(setting, options) +
text_area_tag("settings[#{setting}]", Setting.send(setting), options) text_area_tag("settings[#{setting}]", Setting.send(setting), options)
end end
def setting_check_box(setting, options={}) def setting_check_box(setting, options={})
setting_label(setting, options) + setting_label(setting, options) +
hidden_field_tag("settings[#{setting}]", 0) + hidden_field_tag("settings[#{setting}]", 0) +
check_box_tag("settings[#{setting}]", 1, Setting.send("#{setting}?"), options) check_box_tag("settings[#{setting}]", 1, Setting.send("#{setting}?"), options)
end end
def setting_label(setting, options={}) def setting_label(setting, options={})
label = options.delete(:label) label = options.delete(:label)
label != false ? content_tag("label", l(label || "setting_#{setting}")) : '' label != false ? content_tag("label", l(label || "setting_#{setting}")) : ''
+6 -2
View File
@@ -200,12 +200,16 @@ module SortHelper
caption = column.to_s.humanize unless caption caption = column.to_s.humanize unless caption
sort_options = { :sort => @sort_criteria.add(column.to_s, order).to_param } sort_options = { :sort => @sort_criteria.add(column.to_s, order).to_param }
url_options = params.merge(sort_options) # don't reuse params if filters are present
url_options = params.has_key?(:set_filter) ? sort_options : params.merge(sort_options)
# Add project_id to url_options # Add project_id to url_options
url_options = url_options.merge(:project_id => params[:project_id]) if params.has_key?(:project_id) url_options = url_options.merge(:project_id => params[:project_id]) if params.has_key?(:project_id)
link_to_content_update(caption, url_options, :class => css) link_to_remote(caption,
{:update => "content", :url => url_options, :method => :get},
{:href => url_for(url_options),
:class => css})
end end
# Returns a table header <th> tag with a sort link for the named column # Returns a table header <th> tag with a sort link for the named column
+5 -4
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -17,10 +17,11 @@
module VersionsHelper module VersionsHelper
STATUS_BY_CRITERIAS = %w(category tracker status priority author assigned_to) STATUS_BY_CRITERIAS = %w(category tracker priority author assigned_to)
def render_issue_status_by(version, criteria) def render_issue_status_by(version, criteria)
criteria = 'category' unless STATUS_BY_CRITERIAS.include?(criteria) criteria ||= 'category'
raise 'Unknown criteria' unless STATUS_BY_CRITERIAS.include?(criteria)
h = Hash.new {|k,v| k[v] = [0, 0]} h = Hash.new {|k,v| k[v] = [0, 0]}
begin begin
+17 -12
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -16,18 +16,28 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
module WatchersHelper module WatchersHelper
def watcher_tag(object, user, options={}) # Valid options
content_tag("span", watcher_link(object, user), :class => watcher_css(object)) # * :id - the element id
# * :replace - a string or array of element ids that will be
# replaced
def watcher_tag(object, user, options={:replace => 'watcher'})
id = options[:id]
id ||= options[:replace] if options[:replace].is_a? String
content_tag("span", watcher_link(object, user, options), :id => id)
end end
def watcher_link(object, user) # Valid options
# * :replace - a string or array of element ids that will be
# replaced
def watcher_link(object, user, options={:replace => 'watcher'})
return '' unless user && user.logged? && object.respond_to?('watched_by?') return '' unless user && user.logged? && object.respond_to?('watched_by?')
watched = object.watched_by?(user) watched = object.watched_by?(user)
url = {:controller => 'watchers', url = {:controller => 'watchers',
:action => (watched ? 'unwatch' : 'watch'), :action => (watched ? 'unwatch' : 'watch'),
:object_type => object.class.to_s.underscore, :object_type => object.class.to_s.underscore,
:object_id => object.id} :object_id => object.id,
:replace => options[:replace]}
link_to_remote((watched ? l(:button_unwatch) : l(:button_watch)), link_to_remote((watched ? l(:button_unwatch) : l(:button_watch)),
{:url => url}, {:url => url},
:href => url_for(url), :href => url_for(url),
@@ -35,11 +45,6 @@ module WatchersHelper
end end
# Returns the css class used to identify watch links for a given +object+
def watcher_css(object)
"#{object.class.to_s.underscore}-#{object.id}-watcher"
end
# Returns a comma separated list of users watching the given object # Returns a comma separated list of users watching the given object
def watchers_list(object) def watchers_list(object)
remove_allowed = User.current.allowed_to?("delete_#{object.class.name.underscore}_watchers".to_sym, object.project) remove_allowed = User.current.allowed_to?("delete_#{object.class.name.underscore}_watchers".to_sym, object.project)
+46 -12
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -18,18 +18,52 @@
module WikiHelper module WikiHelper
def wiki_page_options_for_select(pages, selected = nil, parent = nil, level = 0) def wiki_page_options_for_select(pages, selected = nil, parent = nil, level = 0)
pages = pages.group_by(&:parent) unless pages.is_a?(Hash)
s = '' s = ''
if pages.has_key?(parent) pages.select {|p| p.parent == parent}.each do |page|
pages[parent].each do |page| attrs = "value='#{page.id}'"
attrs = "value='#{page.id}'" attrs << " selected='selected'" if selected == page
attrs << " selected='selected'" if selected == page indent = (level > 0) ? ('&nbsp;' * level * 2 + '&#187; ') : nil
indent = (level > 0) ? ('&nbsp;' * level * 2 + '&#187; ') : nil
s << "<option #{attrs}>#{indent}#{h page.pretty_title}</option>\n" +
s << "<option #{attrs}>#{indent}#{h page.pretty_title}</option>\n" + wiki_page_options_for_select(pages, selected, page, level + 1)
wiki_page_options_for_select(pages, selected, page, level + 1)
end
end end
s s
end end
def html_diff(wdiff)
words = wdiff.words.collect{|word| h(word)}
words_add = 0
words_del = 0
dels = 0
del_off = 0
wdiff.diff.diffs.each do |diff|
add_at = nil
add_to = nil
del_at = nil
deleted = ""
diff.each do |change|
pos = change[1]
if change[0] == "+"
add_at = pos + dels unless add_at
add_to = pos + dels
words_add += 1
else
del_at = pos unless del_at
deleted << ' ' + h(change[2])
words_del += 1
end
end
if add_at
words[add_at] = '<span class="diff_in">' + words[add_at]
words[add_to] = words[add_to] + '</span>'
end
if del_at
words.insert del_at - del_off + dels + words_add, '<span class="diff_out">' + deleted + '</span>'
dels += 1
del_off += words_del
words_del = 0
end
end
simple_format_without_paragraph(words.join(' '))
end
end end
+23 -23
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -20,7 +20,7 @@ require "digest/md5"
class Attachment < ActiveRecord::Base class Attachment < ActiveRecord::Base
belongs_to :container, :polymorphic => true belongs_to :container, :polymorphic => true
belongs_to :author, :class_name => "User", :foreign_key => "author_id" belongs_to :author, :class_name => "User", :foreign_key => "author_id"
validates_presence_of :container, :filename, :author validates_presence_of :container, :filename, :author
validates_length_of :filename, :maximum => 255 validates_length_of :filename, :maximum => 255
validates_length_of :disk_filename, :maximum => 255 validates_length_of :disk_filename, :maximum => 255
@@ -31,20 +31,20 @@ class Attachment < ActiveRecord::Base
acts_as_activity_provider :type => 'files', acts_as_activity_provider :type => 'files',
:permission => :view_files, :permission => :view_files,
:author_key => :author_id, :author_key => :author_id,
:find_options => {:select => "#{Attachment.table_name}.*", :find_options => {:select => "#{Attachment.table_name}.*",
:joins => "LEFT JOIN #{Version.table_name} ON #{Attachment.table_name}.container_type='Version' AND #{Version.table_name}.id = #{Attachment.table_name}.container_id " + :joins => "LEFT JOIN #{Version.table_name} ON #{Attachment.table_name}.container_type='Version' AND #{Version.table_name}.id = #{Attachment.table_name}.container_id " +
"LEFT JOIN #{Project.table_name} ON #{Version.table_name}.project_id = #{Project.table_name}.id OR ( #{Attachment.table_name}.container_type='Project' AND #{Attachment.table_name}.container_id = #{Project.table_name}.id )"} "LEFT JOIN #{Project.table_name} ON #{Version.table_name}.project_id = #{Project.table_name}.id OR ( #{Attachment.table_name}.container_type='Project' AND #{Attachment.table_name}.container_id = #{Project.table_name}.id )"}
acts_as_activity_provider :type => 'documents', acts_as_activity_provider :type => 'documents',
:permission => :view_documents, :permission => :view_documents,
:author_key => :author_id, :author_key => :author_id,
:find_options => {:select => "#{Attachment.table_name}.*", :find_options => {:select => "#{Attachment.table_name}.*",
:joins => "LEFT JOIN #{Document.table_name} ON #{Attachment.table_name}.container_type='Document' AND #{Document.table_name}.id = #{Attachment.table_name}.container_id " + :joins => "LEFT JOIN #{Document.table_name} ON #{Attachment.table_name}.container_type='Document' AND #{Document.table_name}.id = #{Attachment.table_name}.container_id " +
"LEFT JOIN #{Project.table_name} ON #{Document.table_name}.project_id = #{Project.table_name}.id"} "LEFT JOIN #{Project.table_name} ON #{Document.table_name}.project_id = #{Project.table_name}.id"}
cattr_accessor :storage_path cattr_accessor :storage_path
@@storage_path = Redmine::Configuration['attachments_storage_path'] || "#{RAILS_ROOT}/files" @@storage_path = "#{RAILS_ROOT}/files"
def validate def validate
if self.filesize > Setting.attachment_max_size.to_i.kilobytes if self.filesize > Setting.attachment_max_size.to_i.kilobytes
errors.add(:base, :too_long, :count => Setting.attachment_max_size.to_i.kilobytes) errors.add(:base, :too_long, :count => Setting.attachment_max_size.to_i.kilobytes)
@@ -76,7 +76,7 @@ class Attachment < ActiveRecord::Base
if @temp_file && (@temp_file.size > 0) if @temp_file && (@temp_file.size > 0)
logger.debug("saving '#{self.diskfile}'") logger.debug("saving '#{self.diskfile}'")
md5 = Digest::MD5.new md5 = Digest::MD5.new
File.open(diskfile, "wb") do |f| File.open(diskfile, "wb") do |f|
buffer = "" buffer = ""
while (buffer = @temp_file.read(8192)) while (buffer = @temp_file.read(8192))
f.write(buffer) f.write(buffer)
@@ -100,7 +100,7 @@ class Attachment < ActiveRecord::Base
def diskfile def diskfile
"#{@@storage_path}/#{self.disk_filename}" "#{@@storage_path}/#{self.disk_filename}"
end end
def increment_download def increment_download
increment!(:downloads) increment!(:downloads)
end end
@@ -108,27 +108,27 @@ class Attachment < ActiveRecord::Base
def project def project
container.project container.project
end end
def visible?(user=User.current) def visible?(user=User.current)
container.attachments_visible?(user) container.attachments_visible?(user)
end end
def deletable?(user=User.current) def deletable?(user=User.current)
container.attachments_deletable?(user) container.attachments_deletable?(user)
end end
def image? def image?
self.filename =~ /\.(jpe?g|gif|png)$/i self.filename =~ /\.(jpe?g|gif|png)$/i
end end
def is_text? def is_text?
Redmine::MimeType.is_type?('text', filename) Redmine::MimeType.is_type?('text', filename)
end end
def is_diff? def is_diff?
self.filename =~ /\.(patch|diff)$/i self.filename =~ /\.(patch|diff)$/i
end end
# Returns true if the file is readable # Returns true if the file is readable
def readable? def readable?
File.readable?(diskfile) File.readable?(diskfile)
@@ -145,7 +145,7 @@ class Attachment < ActiveRecord::Base
attachments.each_value do |attachment| attachments.each_value do |attachment|
file = attachment['file'] file = attachment['file']
next unless file && file.size > 0 next unless file && file.size > 0
a = Attachment.create(:container => obj, a = Attachment.create(:container => obj,
:file => file, :file => file,
:description => attachment['description'].to_s.strip, :description => attachment['description'].to_s.strip,
:author => User.current) :author => User.current)
@@ -160,18 +160,18 @@ class Attachment < ActiveRecord::Base
end end
{:files => attached, :unsaved => obj.unsaved_attachments} {:files => attached, :unsaved => obj.unsaved_attachments}
end end
private private
def sanitize_filename(value) def sanitize_filename(value)
# get only the filename, not the whole path # get only the filename, not the whole path
just_filename = value.gsub(/^.*(\\|\/)/, '') just_filename = value.gsub(/^.*(\\|\/)/, '')
# NOTE: File.basename doesn't work right with Windows paths on Unix # NOTE: File.basename doesn't work right with Windows paths on Unix
# INCORRECT: just_filename = File.basename(value.gsub('\\\\', '/')) # INCORRECT: just_filename = File.basename(value.gsub('\\\\', '/'))
# Finally, replace all non alphanumeric, hyphens or periods with underscore # Finally, replace all non alphanumeric, hyphens or periods with underscore
@filename = just_filename.gsub(/[^\w\.\-]/,'_') @filename = just_filename.gsub(/[^\w\.\-]/,'_')
end end
# Returns an ASCII or hashed filename # Returns an ASCII or hashed filename
def self.disk_filename(filename) def self.disk_filename(filename)
timestamp = DateTime.now.strftime("%y%m%d%H%M%S") timestamp = DateTime.now.strftime("%y%m%d%H%M%S")
-10
View File
@@ -16,8 +16,6 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class AuthSource < ActiveRecord::Base class AuthSource < ActiveRecord::Base
include Redmine::Ciphering
has_many :users has_many :users
validates_presence_of :name validates_presence_of :name
@@ -33,14 +31,6 @@ class AuthSource < ActiveRecord::Base
def auth_method_name def auth_method_name
"Abstract" "Abstract"
end end
def account_password
read_ciphered_attribute(:account_password)
end
def account_password=(arg)
write_ciphered_attribute(:account_password, arg)
end
def allow_password_changes? def allow_password_changes?
self.class.allow_password_changes? self.class.allow_password_changes?
+2 -2
View File
@@ -20,8 +20,8 @@ require 'iconv'
class AuthSourceLdap < AuthSource class AuthSourceLdap < AuthSource
validates_presence_of :host, :port, :attr_login validates_presence_of :host, :port, :attr_login
validates_length_of :name, :host, :maximum => 60, :allow_nil => true validates_length_of :name, :host, :account_password, :maximum => 60, :allow_nil => true
validates_length_of :account, :account_password, :base_dn, :maximum => 255, :allow_nil => true validates_length_of :account, :base_dn, :maximum => 255, :allow_nil => true
validates_length_of :attr_login, :attr_firstname, :attr_lastname, :attr_mail, :maximum => 30, :allow_nil => true validates_length_of :attr_login, :attr_firstname, :attr_lastname, :attr_mail, :maximum => 30, :allow_nil => true
validates_numericality_of :port, :only_integer => true validates_numericality_of :port, :only_integer => true
+7 -12
View File
@@ -1,35 +1,30 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class Change < ActiveRecord::Base class Change < ActiveRecord::Base
belongs_to :changeset belongs_to :changeset
validates_presence_of :changeset_id, :action, :path validates_presence_of :changeset_id, :action, :path
before_save :init_path before_save :init_path
def relative_path def relative_path
changeset.repository.relative_path(path) changeset.repository.relative_path(path)
end end
def before_validation
self.path = Redmine::CodesetUtil.replace_invalid_utf8(self.path)
self.from_path = Redmine::CodesetUtil.replace_invalid_utf8(self.from_path)
end
def init_path def init_path
self.path ||= "" self.path ||= ""
end end
+67 -91
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2010 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -27,23 +27,23 @@ class Changeset < ActiveRecord::Base
:description => :long_comments, :description => :long_comments,
:datetime => :committed_on, :datetime => :committed_on,
:url => Proc.new {|o| {:controller => 'repositories', :action => 'revision', :id => o.repository.project, :rev => o.identifier}} :url => Proc.new {|o| {:controller => 'repositories', :action => 'revision', :id => o.repository.project, :rev => o.identifier}}
acts_as_searchable :columns => 'comments', acts_as_searchable :columns => 'comments',
:include => {:repository => :project}, :include => {:repository => :project},
:project_key => "#{Repository.table_name}.project_id", :project_key => "#{Repository.table_name}.project_id",
:date_column => 'committed_on' :date_column => 'committed_on'
acts_as_activity_provider :timestamp => "#{table_name}.committed_on", acts_as_activity_provider :timestamp => "#{table_name}.committed_on",
:author_key => :user_id, :author_key => :user_id,
:find_options => {:include => [:user, {:repository => :project}]} :find_options => {:include => [:user, {:repository => :project}]}
validates_presence_of :repository_id, :revision, :committed_on, :commit_date validates_presence_of :repository_id, :revision, :committed_on, :commit_date
validates_uniqueness_of :revision, :scope => :repository_id validates_uniqueness_of :revision, :scope => :repository_id
validates_uniqueness_of :scmid, :scope => :repository_id, :allow_nil => true validates_uniqueness_of :scmid, :scope => :repository_id, :allow_nil => true
named_scope :visible, lambda {|*args| { :include => {:repository => :project}, named_scope :visible, lambda {|*args| { :include => {:repository => :project},
:conditions => Project.allowed_to_condition(args.shift || User.current, :view_changesets, *args) } } :conditions => Project.allowed_to_condition(args.first || User.current, :view_changesets) } }
def revision=(r) def revision=(r)
write_attribute :revision, (r.nil? ? nil : r.to_s) write_attribute :revision, (r.nil? ? nil : r.to_s)
end end
@@ -56,6 +56,10 @@ class Changeset < ActiveRecord::Base
revision.to_s revision.to_s
end end
end end
def comments=(comment)
write_attribute(:comments, Changeset.normalize_comments(comment))
end
def committed_on=(date) def committed_on=(date)
self.commit_date = date self.commit_date = date
@@ -70,26 +74,27 @@ class Changeset < ActiveRecord::Base
identifier identifier
end end
end end
def committer=(arg)
write_attribute(:committer, self.class.to_utf8(arg.to_s))
end
def project def project
repository.project repository.project
end end
def author def author
user || committer.to_s.split('<').first user || committer.to_s.split('<').first
end end
def before_create def before_create
self.committer = self.class.to_utf8(self.committer, repository.repo_log_encoding) self.user = repository.find_committer_user(committer)
self.comments = self.class.normalize_comments(
self.comments, repository.repo_log_encoding)
self.user = repository.find_committer_user(self.committer)
end end
def after_create def after_create
scan_comment_for_issue_ids scan_comment_for_issue_ids
end end
TIMELOG_RE = / TIMELOG_RE = /
( (
((\d+)(h|hours?))((\d+)(m|min)?)? ((\d+)(h|hours?))((\d+)(m|min)?)?
@@ -101,7 +106,7 @@ class Changeset < ActiveRecord::Base
(\d+([\.,]\d+)?)h? (\d+([\.,]\d+)?)h?
) )
/x /x
def scan_comment_for_issue_ids def scan_comment_for_issue_ids
return if comments.blank? return if comments.blank?
# keywords used to reference issues # keywords used to reference issues
@@ -109,15 +114,15 @@ class Changeset < ActiveRecord::Base
ref_keywords_any = ref_keywords.delete('*') ref_keywords_any = ref_keywords.delete('*')
# keywords used to fix issues # keywords used to fix issues
fix_keywords = Setting.commit_fix_keywords.downcase.split(",").collect(&:strip) fix_keywords = Setting.commit_fix_keywords.downcase.split(",").collect(&:strip)
kw_regexp = (ref_keywords + fix_keywords).collect{|kw| Regexp.escape(kw)}.join("|") kw_regexp = (ref_keywords + fix_keywords).collect{|kw| Regexp.escape(kw)}.join("|")
referenced_issues = [] referenced_issues = []
comments.scan(/([\s\(\[,-]|^)((#{kw_regexp})[\s:]+)?(#\d+(\s+@#{TIMELOG_RE})?([\s,;&]+#\d+(\s+@#{TIMELOG_RE})?)*)(?=[[:punct:]]|\s|<|$)/i) do |match| comments.scan(/([\s\(\[,-]|^)((#{kw_regexp})[\s:]+)?(#\d+(\s+@#{TIMELOG_RE})?([\s,;&]+#\d+(\s+@#{TIMELOG_RE})?)*)(?=[[:punct:]]|\s|<|$)/i) do |match|
action, refs = match[2], match[3] action, refs = match[2], match[3]
next unless action.present? || ref_keywords_any next unless action.present? || ref_keywords_any
refs.scan(/#(\d+)(\s+@#{TIMELOG_RE})?/).each do |m| refs.scan(/#(\d+)(\s+@#{TIMELOG_RE})?/).each do |m|
issue, hours = find_referenced_issue_by_id(m[0].to_i), m[2] issue, hours = find_referenced_issue_by_id(m[0].to_i), m[2]
if issue if issue
@@ -127,15 +132,15 @@ class Changeset < ActiveRecord::Base
end end
end end
end end
referenced_issues.uniq! referenced_issues.uniq!
self.issues = referenced_issues unless referenced_issues.empty? self.issues = referenced_issues unless referenced_issues.empty?
end end
def short_comments def short_comments
@short_comments || split_comments.first @short_comments || split_comments.first
end end
def long_comments def long_comments
@long_comments || split_comments.last @long_comments || split_comments.last
end end
@@ -147,32 +152,31 @@ class Changeset < ActiveRecord::Base
"r#{revision}" "r#{revision}"
end end
end end
# Returns the previous changeset # Returns the previous changeset
def previous def previous
@previous ||= Changeset.find(:first, @previous ||= Changeset.find(:first, :conditions => ['id < ? AND repository_id = ?', self.id, self.repository_id], :order => 'id DESC')
:conditions => ['id < ? AND repository_id = ?',
self.id, self.repository_id],
:order => 'id DESC')
end end
# Returns the next changeset # Returns the next changeset
def next def next
@next ||= Changeset.find(:first, @next ||= Changeset.find(:first, :conditions => ['id > ? AND repository_id = ?', self.id, self.repository_id], :order => 'id ASC')
:conditions => ['id > ? AND repository_id = ?', end
self.id, self.repository_id],
:order => 'id ASC') # Strips and reencodes a commit log before insertion into the database
def self.normalize_comments(str)
to_utf8(str.to_s.strip)
end end
# Creates a new Change from it's common parameters # Creates a new Change from it's common parameters
def create_change(change) def create_change(change)
Change.create(:changeset => self, Change.create(:changeset => self,
:action => change[:action], :action => change[:action],
:path => change[:path], :path => change[:path],
:from_path => change[:from_path], :from_path => change[:from_path],
:from_revision => change[:from_revision]) :from_revision => change[:from_revision])
end end
private private
# Finds an issue that can be referenced by the commit message # Finds an issue that can be referenced by the commit message
@@ -181,27 +185,25 @@ class Changeset < ActiveRecord::Base
return nil if id.blank? return nil if id.blank?
issue = Issue.find_by_id(id.to_i, :include => :project) issue = Issue.find_by_id(id.to_i, :include => :project)
if issue if issue
unless issue.project && unless issue.project && (project == issue.project || project.is_ancestor_of?(issue.project) || project.is_descendant_of?(issue.project))
(project == issue.project || project.is_ancestor_of?(issue.project) ||
project.is_descendant_of?(issue.project))
issue = nil issue = nil
end end
end end
issue issue
end end
def fix_issue(issue) def fix_issue(issue)
status = IssueStatus.find_by_id(Setting.commit_fix_status_id.to_i) status = IssueStatus.find_by_id(Setting.commit_fix_status_id.to_i)
if status.nil? if status.nil?
logger.warn("No status matches commit_fix_status_id setting (#{Setting.commit_fix_status_id})") if logger logger.warn("No status macthes commit_fix_status_id setting (#{Setting.commit_fix_status_id})") if logger
return issue return issue
end end
# the issue may have been updated by the closure of another one (eg. duplicate) # the issue may have been updated by the closure of another one (eg. duplicate)
issue.reload issue.reload
# don't change the status is the issue is closed # don't change the status is the issue is closed
return if issue.status && issue.status.is_closed? return if issue.status && issue.status.is_closed?
journal = issue.init_journal(user || User.anonymous, ll(Setting.default_language, :text_status_changed_by_changeset, text_tag)) journal = issue.init_journal(user || User.anonymous, ll(Setting.default_language, :text_status_changed_by_changeset, text_tag))
issue.status = status issue.status = status
unless Setting.commit_fix_done_ratio.blank? unless Setting.commit_fix_done_ratio.blank?
@@ -214,30 +216,29 @@ class Changeset < ActiveRecord::Base
end end
issue issue
end end
def log_time(issue, hours) def log_time(issue, hours)
time_entry = TimeEntry.new( time_entry = TimeEntry.new(
:user => user, :user => user,
:hours => hours, :hours => hours,
:issue => issue, :issue => issue,
:spent_on => commit_date, :spent_on => commit_date,
:comments => l(:text_time_logged_by_changeset, :value => text_tag, :comments => l(:text_time_logged_by_changeset, :value => text_tag, :locale => Setting.default_language)
:locale => Setting.default_language)
) )
time_entry.activity = log_time_activity unless log_time_activity.nil? time_entry.activity = log_time_activity unless log_time_activity.nil?
unless time_entry.save unless time_entry.save
logger.warn("TimeEntry could not be created by changeset #{id}: #{time_entry.errors.full_messages}") if logger logger.warn("TimeEntry could not be created by changeset #{id}: #{time_entry.errors.full_messages}") if logger
end end
time_entry time_entry
end end
def log_time_activity def log_time_activity
if Setting.commit_logtime_activity_id.to_i > 0 if Setting.commit_logtime_activity_id.to_i > 0
TimeEntryActivity.find_by_id(Setting.commit_logtime_activity_id.to_i) TimeEntryActivity.find_by_id(Setting.commit_logtime_activity_id.to_i)
end end
end end
def split_comments def split_comments
comments =~ /\A(.+?)\r?\n(.*)$/m comments =~ /\A(.+?)\r?\n(.*)$/m
@short_comments = $1 || comments @short_comments = $1 || comments
@@ -245,47 +246,22 @@ class Changeset < ActiveRecord::Base
return @short_comments, @long_comments return @short_comments, @long_comments
end end
public def self.to_utf8(str)
return str if /\A[\r\n\t\x20-\x7e]*\Z/n.match(str) # for us-ascii
# Strips and reencodes a commit log before insertion into the database encoding = Setting.commit_logs_encoding.to_s.strip
def self.normalize_comments(str, encoding) unless encoding.blank? || encoding == 'UTF-8'
Changeset.to_utf8(str.to_s.strip, encoding)
end
def self.to_utf8(str, encoding)
return str if str.nil?
str.force_encoding("ASCII-8BIT") if str.respond_to?(:force_encoding)
if str.empty?
str.force_encoding("UTF-8") if str.respond_to?(:force_encoding)
return str
end
enc = encoding.blank? ? "UTF-8" : encoding
if str.respond_to?(:force_encoding)
if enc.upcase != "UTF-8"
str.force_encoding(enc)
str = str.encode("UTF-8", :invalid => :replace,
:undef => :replace, :replace => '?')
else
str.force_encoding("UTF-8")
if ! str.valid_encoding?
str = str.encode("US-ASCII", :invalid => :replace,
:undef => :replace, :replace => '?').encode("UTF-8")
end
end
else
ic = Iconv.new('UTF-8', enc)
txtar = ""
begin begin
txtar += ic.iconv(str) str = Iconv.conv('UTF-8', encoding, str)
rescue Iconv::IllegalSequence rescue Iconv::Failure
txtar += $!.success # do nothing here
str = '?' + $!.failed[1,$!.failed.length]
retry
rescue
txtar += $!.success
end end
str = txtar
end end
str # removes invalid UTF8 sequences
begin
Iconv.conv('UTF-8//IGNORE', 'UTF-8', str + ' ')[0..-3]
rescue Iconv::InvalidEncoding
# "UTF-8//IGNORE" is not supported on some OS
str
end
end end
end end
-24
View File
@@ -1,24 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class CommentObserver < ActiveRecord::Observer
def after_create(comment)
if comment.commented.is_a?(News) && Setting.notified_events.include?('news_comment_added')
Mailer.deliver_news_comment_added(comment)
end
end
end
+3 -41
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -23,6 +23,7 @@ class CustomField < ActiveRecord::Base
validates_presence_of :name, :field_format validates_presence_of :name, :field_format
validates_uniqueness_of :name, :scope => :type validates_uniqueness_of :name, :scope => :type
validates_length_of :name, :maximum => 30 validates_length_of :name, :maximum => 30
validates_format_of :name, :with => /^[\w\s\.\'\-]*$/i
validates_inclusion_of :field_format, :in => Redmine::CustomFieldFormat.available_formats validates_inclusion_of :field_format, :in => Redmine::CustomFieldFormat.available_formats
def initialize(attributes = nil) def initialize(attributes = nil)
@@ -42,49 +43,12 @@ class CustomField < ActiveRecord::Base
errors.add(:possible_values, :invalid) unless self.possible_values.is_a? Array errors.add(:possible_values, :invalid) unless self.possible_values.is_a? Array
end end
if regexp.present?
begin
Regexp.new(regexp)
rescue
errors.add(:regexp, :invalid)
end
end
# validate default value # validate default value
v = CustomValue.new(:custom_field => self.clone, :value => default_value, :customized => nil) v = CustomValue.new(:custom_field => self.clone, :value => default_value, :customized => nil)
v.custom_field.is_required = false v.custom_field.is_required = false
errors.add(:default_value, :invalid) unless v.valid? errors.add(:default_value, :invalid) unless v.valid?
end end
def possible_values_options(obj=nil)
case field_format
when 'user', 'version'
if obj.respond_to?(:project) && obj.project
case field_format
when 'user'
obj.project.users.sort.collect {|u| [u.to_s, u.id.to_s]}
when 'version'
obj.project.shared_versions.sort.collect {|u| [u.to_s, u.id.to_s]}
end
elsif obj.is_a?(Array)
obj.collect {|o| possible_values_options(o)}.inject {|memo, v| memo & v}
else
[]
end
else
read_attribute :possible_values
end
end
def possible_values(obj=nil)
case field_format
when 'user', 'version'
possible_values_options(obj).collect(&:last)
else
read_attribute :possible_values
end
end
# Makes possible_values accept a multiline string # Makes possible_values accept a multiline string
def possible_values=(arg) def possible_values=(arg)
if arg.is_a?(Array) if arg.is_a?(Array)
@@ -108,8 +72,6 @@ class CustomField < ActiveRecord::Base
casted = value.to_i casted = value.to_i
when 'float' when 'float'
casted = value.to_f casted = value.to_f
when 'user', 'version'
casted = (value.blank? ? nil : field_format.classify.constantize.find_by_id(value.to_i))
end end
end end
casted casted
+8 -11
View File
@@ -1,16 +1,16 @@
# RedMine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -25,23 +25,20 @@ class Document < ActiveRecord::Base
:author => Proc.new {|o| (a = o.attachments.find(:first, :order => "#{Attachment.table_name}.created_on ASC")) ? a.author : nil }, :author => Proc.new {|o| (a = o.attachments.find(:first, :order => "#{Attachment.table_name}.created_on ASC")) ? a.author : nil },
:url => Proc.new {|o| {:controller => 'documents', :action => 'show', :id => o.id}} :url => Proc.new {|o| {:controller => 'documents', :action => 'show', :id => o.id}}
acts_as_activity_provider :find_options => {:include => :project} acts_as_activity_provider :find_options => {:include => :project}
validates_presence_of :project, :title, :category validates_presence_of :project, :title, :category
validates_length_of :title, :maximum => 60 validates_length_of :title, :maximum => 60
named_scope :visible, lambda {|*args| { :include => :project,
:conditions => Project.allowed_to_condition(args.shift || User.current, :view_documents, *args) } }
def visible?(user=User.current) def visible?(user=User.current)
!user.nil? && user.allowed_to?(:view_documents, project) !user.nil? && user.allowed_to?(:view_documents, project)
end end
def after_initialize def after_initialize
if new_record? if new_record?
self.category ||= DocumentCategory.default self.category ||= DocumentCategory.default
end end
end end
def updated_on def updated_on
unless @updated_on unless @updated_on
a = attachments.find(:first, :order => 'created_on DESC') a = attachments.find(:first, :order => 'created_on DESC')
+4 -4
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+5 -4
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -20,3 +20,4 @@ class DocumentCategoryCustomField < CustomField
:enumeration_doc_categories :enumeration_doc_categories
end end
end end
+4 -4
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+7 -7
View File
@@ -1,30 +1,30 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2009 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class EnabledModule < ActiveRecord::Base class EnabledModule < ActiveRecord::Base
belongs_to :project belongs_to :project
validates_presence_of :name validates_presence_of :name
validates_uniqueness_of :name, :scope => :project_id validates_uniqueness_of :name, :scope => :project_id
after_create :module_enabled after_create :module_enabled
private private
# after_create callback used to do things when a module is enabled # after_create callback used to do things when a module is enabled
def module_enabled def module_enabled
case name case name
-1
View File
@@ -32,7 +32,6 @@ class Enumeration < ActiveRecord::Base
named_scope :shared, :conditions => { :project_id => nil } named_scope :shared, :conditions => { :project_id => nil }
named_scope :active, :conditions => { :active => true } named_scope :active, :conditions => { :active => true }
named_scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
def self.default def self.default
# Creates a fake default scope so Enumeration.default will check # Creates a fake default scope so Enumeration.default will check
+105 -163
View File
@@ -1,23 +1,23 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class Issue < ActiveRecord::Base class Issue < ActiveRecord::Base
include Redmine::SafeAttributes include Redmine::SafeAttributes
belongs_to :project belongs_to :project
belongs_to :tracker belongs_to :tracker
belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id' belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
@@ -30,10 +30,10 @@ class Issue < ActiveRecord::Base
has_many :journals, :as => :journalized, :dependent => :destroy has_many :journals, :as => :journalized, :dependent => :destroy
has_many :time_entries, :dependent => :delete_all has_many :time_entries, :dependent => :delete_all
has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC" has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
acts_as_nested_set :scope => 'root_id', :dependent => :destroy acts_as_nested_set :scope => 'root_id', :dependent => :destroy
acts_as_attachable :after_remove => :attachment_removed acts_as_attachable :after_remove => :attachment_removed
acts_as_customizable acts_as_customizable
@@ -45,7 +45,7 @@ class Issue < ActiveRecord::Base
acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"}, acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
:url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}}, :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
:type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') } :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]}, acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
:author_key => :author_id :author_key => :author_id
@@ -60,14 +60,19 @@ class Issue < ActiveRecord::Base
validates_numericality_of :estimated_hours, :allow_nil => true validates_numericality_of :estimated_hours, :allow_nil => true
named_scope :visible, lambda {|*args| { :include => :project, named_scope :visible, lambda {|*args| { :include => :project,
:conditions => Issue.visible_condition(args.shift || User.current, *args) } } :conditions => Project.allowed_to_condition(args.first || User.current, :view_issues) } }
named_scope :open, :conditions => ["#{IssueStatus.table_name}.is_closed = ?", false], :include => :status named_scope :open, :conditions => ["#{IssueStatus.table_name}.is_closed = ?", false], :include => :status
named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC" named_scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
named_scope :with_limit, lambda { |limit| { :limit => limit} } named_scope :with_limit, lambda { |limit| { :limit => limit} }
named_scope :on_active_project, :include => [:status, :project, :tracker], named_scope :on_active_project, :include => [:status, :project, :tracker],
:conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"] :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
named_scope :for_gantt, lambda {
{
:include => [:tracker, :status, :assigned_to, :priority, :project, :fixed_version]
}
}
named_scope :without_version, lambda { named_scope :without_version, lambda {
{ {
@@ -85,39 +90,12 @@ class Issue < ActiveRecord::Base
before_save :close_duplicates, :update_done_ratio_from_issue_status before_save :close_duplicates, :update_done_ratio_from_issue_status
after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
after_destroy :update_parent_attributes after_destroy :update_parent_attributes
# Returns a SQL conditions string used to find all issues visible by the specified user
def self.visible_condition(user, options={})
Project.allowed_to_condition(user, :view_issues, options) do |role, user|
case role.issues_visibility
when 'all'
nil
when 'default'
"(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id = #{user.id})"
when 'own'
"(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id = #{user.id})"
else
'1=0'
end
end
end
# Returns true if usr or current user is allowed to view the issue # Returns true if usr or current user is allowed to view the issue
def visible?(usr=nil) def visible?(usr=nil)
(usr || User.current).allowed_to?(:view_issues, self.project) do |role, user| (usr || User.current).allowed_to?(:view_issues, self.project)
case role.issues_visibility
when 'all'
true
when 'default'
!self.is_private? || self.author == user || self.assigned_to == user
when 'own'
self.author == user || self.assigned_to == user
else
false
end
end
end end
def after_initialize def after_initialize
if new_record? if new_record?
# set default values for new records only # set default values for new records only
@@ -125,12 +103,12 @@ class Issue < ActiveRecord::Base
self.priority ||= IssuePriority.default self.priority ||= IssuePriority.default
end end
end end
# Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
def available_custom_fields def available_custom_fields
(project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : [] (project && tracker) ? project.all_issue_custom_fields.select {|c| tracker.custom_fields.include? c } : []
end end
def copy_from(arg) def copy_from(arg)
issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg) issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on") self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
@@ -138,7 +116,7 @@ class Issue < ActiveRecord::Base
self.status = issue.status self.status = issue.status
self self
end end
# Moves/copies an issue to a new project and tracker # Moves/copies an issue to a new project and tracker
# Returns the moved/copied issue on success, false on failure # Returns the moved/copied issue on success, false on failure
def move_to_project(*args) def move_to_project(*args)
@@ -146,11 +124,11 @@ class Issue < ActiveRecord::Base
move_to_project_without_transaction(*args) || raise(ActiveRecord::Rollback) move_to_project_without_transaction(*args) || raise(ActiveRecord::Rollback)
end || false end || false
end end
def move_to_project_without_transaction(new_project, new_tracker = nil, options = {}) def move_to_project_without_transaction(new_project, new_tracker = nil, options = {})
options ||= {} options ||= {}
issue = options[:copy] ? self.class.new.copy_from(self) : self issue = options[:copy] ? self.class.new.copy_from(self) : self
if new_project && issue.project_id != new_project.id if new_project && issue.project_id != new_project.id
# delete issue relations # delete issue relations
unless Setting.cross_project_issue_relations? unless Setting.cross_project_issue_relations?
@@ -175,7 +153,6 @@ class Issue < ActiveRecord::Base
issue.reset_custom_values! issue.reset_custom_values!
end end
if options[:copy] if options[:copy]
issue.author = User.current
issue.custom_field_values = self.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h} issue.custom_field_values = self.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
issue.status = if options[:attributes] && options[:attributes][:status_id] issue.status = if options[:attributes] && options[:attributes][:status_id]
IssueStatus.find_by_id(options[:attributes][:status_id]) IssueStatus.find_by_id(options[:attributes][:status_id])
@@ -188,16 +165,10 @@ class Issue < ActiveRecord::Base
issue.attributes = options[:attributes] issue.attributes = options[:attributes]
end end
if issue.save if issue.save
if options[:copy] unless options[:copy]
if current_journal && current_journal.notes.present?
issue.init_journal(current_journal.user, current_journal.notes)
issue.current_journal.notify = false
issue.save
end
else
# Manually update project_id on related time entries # Manually update project_id on related time entries
TimeEntry.update_all("project_id = #{new_project.id}", {:issue_id => id}) TimeEntry.update_all("project_id = #{new_project.id}", {:issue_id => id})
issue.children.each do |child| issue.children.each do |child|
unless child.move_to_project_without_transaction(new_project) unless child.move_to_project_without_transaction(new_project)
# Move failed and transaction was rollback'd # Move failed and transaction was rollback'd
@@ -215,7 +186,7 @@ class Issue < ActiveRecord::Base
self.status = nil self.status = nil
write_attribute(:status_id, sid) write_attribute(:status_id, sid)
end end
def priority_id=(pid) def priority_id=(pid)
self.priority = nil self.priority = nil
write_attribute(:priority_id, pid) write_attribute(:priority_id, pid)
@@ -228,13 +199,6 @@ class Issue < ActiveRecord::Base
result result
end end
def description=(arg)
if arg.is_a?(String)
arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
end
write_attribute(:description, arg)
end
# Overrides attributes= so that tracker_id gets assigned first # Overrides attributes= so that tracker_id gets assigned first
def attributes_with_tracker_first=(new_attributes, *args) def attributes_with_tracker_first=(new_attributes, *args)
return if new_attributes.nil? return if new_attributes.nil?
@@ -246,11 +210,11 @@ class Issue < ActiveRecord::Base
end end
# Do not redefine alias chain on reload (see #4838) # Do not redefine alias chain on reload (see #4838)
alias_method_chain(:attributes=, :tracker_first) unless method_defined?(:attributes_without_tracker_first=) alias_method_chain(:attributes=, :tracker_first) unless method_defined?(:attributes_without_tracker_first=)
def estimated_hours=(h) def estimated_hours=(h)
write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h) write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
end end
safe_attributes 'tracker_id', safe_attributes 'tracker_id',
'status_id', 'status_id',
'parent_issue_id', 'parent_issue_id',
@@ -268,19 +232,13 @@ class Issue < ActiveRecord::Base
'custom_fields', 'custom_fields',
'lock_version', 'lock_version',
:if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) } :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
safe_attributes 'status_id', safe_attributes 'status_id',
'assigned_to_id', 'assigned_to_id',
'fixed_version_id', 'fixed_version_id',
'done_ratio', 'done_ratio',
:if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? } :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
safe_attributes 'is_private',
:if => lambda {|issue, user|
user.allowed_to?(:set_issues_private, issue.project) ||
(issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
}
# Safely sets attributes # Safely sets attributes
# Should be called from controllers instead of #attributes= # Should be called from controllers instead of #attributes=
# attr_accessible is too rough because we still want things like # attr_accessible is too rough because we still want things like
@@ -288,26 +246,26 @@ class Issue < ActiveRecord::Base
# TODO: move workflow/permission checks from controllers to here # TODO: move workflow/permission checks from controllers to here
def safe_attributes=(attrs, user=User.current) def safe_attributes=(attrs, user=User.current)
return unless attrs.is_a?(Hash) return unless attrs.is_a?(Hash)
# User can change issue attributes only if he has :edit permission or if a workflow transition is allowed # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
attrs = delete_unsafe_attributes(attrs, user) attrs = delete_unsafe_attributes(attrs, user)
return if attrs.empty? return if attrs.empty?
# Tracker must be set before since new_statuses_allowed_to depends on it. # Tracker must be set before since new_statuses_allowed_to depends on it.
if t = attrs.delete('tracker_id') if t = attrs.delete('tracker_id')
self.tracker_id = t self.tracker_id = t
end end
if attrs['status_id'] if attrs['status_id']
unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i) unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
attrs.delete('status_id') attrs.delete('status_id')
end end
end end
unless leaf? unless leaf?
attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)} attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
end end
if attrs.has_key?('parent_issue_id') if attrs.has_key?('parent_issue_id')
if !user.allowed_to?(:manage_subtasks, project) if !user.allowed_to?(:manage_subtasks, project)
attrs.delete('parent_issue_id') attrs.delete('parent_issue_id')
@@ -315,10 +273,10 @@ class Issue < ActiveRecord::Base
attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i) attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
end end
end end
self.attributes = attrs self.attributes = attrs
end end
def done_ratio def done_ratio
if Issue.use_status_for_done_ratio? && status && status.default_done_ratio if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
status.default_done_ratio status.default_done_ratio
@@ -334,20 +292,20 @@ class Issue < ActiveRecord::Base
def self.use_field_for_done_ratio? def self.use_field_for_done_ratio?
Setting.issue_done_ratio == 'issue_field' Setting.issue_done_ratio == 'issue_field'
end end
def validate def validate
if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty? if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
errors.add :due_date, :not_a_date errors.add :due_date, :not_a_date
end end
if self.due_date and self.start_date and self.due_date < self.start_date if self.due_date and self.start_date and self.due_date < self.start_date
errors.add :due_date, :greater_than_start_date errors.add :due_date, :greater_than_start_date
end end
if start_date && soonest_start && start_date < soonest_start if start_date && soonest_start && start_date < soonest_start
errors.add :start_date, :invalid errors.add :start_date, :invalid
end end
if fixed_version if fixed_version
if !assignable_versions.include?(fixed_version) if !assignable_versions.include?(fixed_version)
errors.add :fixed_version_id, :inclusion errors.add :fixed_version_id, :inclusion
@@ -355,14 +313,14 @@ class Issue < ActiveRecord::Base
errors.add_to_base I18n.t(:error_can_not_reopen_issue_on_closed_version) errors.add_to_base I18n.t(:error_can_not_reopen_issue_on_closed_version)
end end
end end
# Checks that the issue can not be added/moved to a disabled tracker # Checks that the issue can not be added/moved to a disabled tracker
if project && (tracker_id_changed? || project_id_changed?) if project && (tracker_id_changed? || project_id_changed?)
unless project.trackers.include?(tracker) unless project.trackers.include?(tracker)
errors.add :tracker_id, :inclusion errors.add :tracker_id, :inclusion
end end
end end
# Checks parent issue assignment # Checks parent issue assignment
if @parent_issue if @parent_issue
if @parent_issue.project_id != project_id if @parent_issue.project_id != project_id
@@ -379,7 +337,7 @@ class Issue < ActiveRecord::Base
end end
end end
end end
# Set the done_ratio using the status if that setting is set. This will keep the done_ratios # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
# even if the user turns off the setting later # even if the user turns off the setting later
def update_done_ratio_from_issue_status def update_done_ratio_from_issue_status
@@ -387,7 +345,7 @@ class Issue < ActiveRecord::Base
self.done_ratio = status.default_done_ratio self.done_ratio = status.default_done_ratio
end end
end end
def init_journal(user, notes = "") def init_journal(user, notes = "")
@current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes) @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
@issue_before_change = self.clone @issue_before_change = self.clone
@@ -398,12 +356,12 @@ class Issue < ActiveRecord::Base
updated_on_will_change! updated_on_will_change!
@current_journal @current_journal
end end
# Return true if the issue is closed, otherwise false # Return true if the issue is closed, otherwise false
def closed? def closed?
self.status.is_closed? self.status.is_closed?
end end
# Return true if the issue is being reopened # Return true if the issue is being reopened
def reopened? def reopened?
if !new_record? && status_id_changed? if !new_record? && status_id_changed?
@@ -427,7 +385,7 @@ class Issue < ActiveRecord::Base
end end
false false
end end
# Returns true if the issue is overdue # Returns true if the issue is overdue
def overdue? def overdue?
!due_date.nil? && (due_date < Date.today) && !status.is_closed? !due_date.nil? && (due_date < Date.today) && !status.is_closed?
@@ -444,39 +402,33 @@ class Issue < ActiveRecord::Base
def children? def children?
!leaf? !leaf?
end end
# Users the issue can be assigned to # Users the issue can be assigned to
def assignable_users def assignable_users
users = project.assignable_users users = project.assignable_users
users << author if author users << author if author
users << assigned_to if assigned_to
users.uniq.sort users.uniq.sort
end end
# Versions that the issue can be assigned to # Versions that the issue can be assigned to
def assignable_versions def assignable_versions
@assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
end end
# Returns true if this issue is blocked by another issue that is still open # Returns true if this issue is blocked by another issue that is still open
def blocked? def blocked?
!relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil? !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
end end
# Returns an array of status that user is able to apply # Returns an array of status that user is able to apply
def new_statuses_allowed_to(user, include_default=false) def new_statuses_allowed_to(user, include_default=false)
statuses = status.find_new_statuses_allowed_to( statuses = status.find_new_statuses_allowed_to(user.roles_for_project(project), tracker)
user.roles_for_project(project),
tracker,
author == user,
assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
)
statuses << status unless statuses.empty? statuses << status unless statuses.empty?
statuses << IssueStatus.default if include_default statuses << IssueStatus.default if include_default
statuses = statuses.uniq.sort statuses = statuses.uniq.sort
blocked? ? statuses.reject {|s| s.is_closed?} : statuses blocked? ? statuses.reject {|s| s.is_closed?} : statuses
end end
# Returns the mail adresses of users that should be notified # Returns the mail adresses of users that should be notified
def recipients def recipients
notified = project.notified_users notified = project.notified_users
@@ -489,7 +441,7 @@ class Issue < ActiveRecord::Base
notified.reject! {|user| !visible?(user)} notified.reject! {|user| !visible?(user)}
notified.collect(&:mail) notified.collect(&:mail)
end end
# Returns the total number of hours spent on this issue and its descendants # Returns the total number of hours spent on this issue and its descendants
# #
# Example: # Example:
@@ -498,50 +450,47 @@ class Issue < ActiveRecord::Base
def spent_hours def spent_hours
@spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours", :include => :time_entries).to_f || 0.0 @spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours", :include => :time_entries).to_f || 0.0
end end
def relations def relations
(relations_from + relations_to).sort (relations_from + relations_to).sort
end end
def all_dependent_issues(except=[]) def all_dependent_issues
except << self
dependencies = [] dependencies = []
relations_from.each do |relation| relations_from.each do |relation|
if relation.issue_to && !except.include?(relation.issue_to) dependencies << relation.issue_to
dependencies << relation.issue_to dependencies += relation.issue_to.all_dependent_issues
dependencies += relation.issue_to.all_dependent_issues(except)
end
end end
dependencies dependencies
end end
# Returns an array of issues that duplicate this one # Returns an array of issues that duplicate this one
def duplicates def duplicates
relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from} relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
end end
# Returns the due date or the target due date if any # Returns the due date or the target due date if any
# Used on gantt chart # Used on gantt chart
def due_before def due_before
due_date || (fixed_version ? fixed_version.effective_date : nil) due_date || (fixed_version ? fixed_version.effective_date : nil)
end end
# Returns the time scheduled for this issue. # Returns the time scheduled for this issue.
# #
# Example: # Example:
# Start Date: 2/26/09, End Date: 3/04/09 # Start Date: 2/26/09, End Date: 3/04/09
# duration => 6 # duration => 6
def duration def duration
(start_date && due_date) ? due_date - start_date : 0 (start_date && due_date) ? due_date - start_date : 0
end end
def soonest_start def soonest_start
@soonest_start ||= ( @soonest_start ||= (
relations_to.collect{|relation| relation.successor_soonest_start} + relations_to.collect{|relation| relation.successor_soonest_start} +
ancestors.collect(&:soonest_start) ancestors.collect(&:soonest_start)
).compact.max ).compact.max
end end
def reschedule_after(date) def reschedule_after(date)
return if date.nil? return if date.nil?
if leaf? if leaf?
@@ -555,7 +504,7 @@ class Issue < ActiveRecord::Base
end end
end end
end end
def <=>(issue) def <=>(issue)
if issue.nil? if issue.nil?
-1 -1
@@ -565,19 +514,16 @@ class Issue < ActiveRecord::Base
(lft || 0) <=> (issue.lft || 0) (lft || 0) <=> (issue.lft || 0)
end end
end end
def to_s def to_s
"#{tracker} ##{id}: #{subject}" "#{tracker} ##{id}: #{subject}"
end end
# Returns a string of css classes that apply to the issue # Returns a string of css classes that apply to the issue
def css_classes def css_classes
s = "issue status-#{status.position} priority-#{priority.position}" s = "issue status-#{status.position} priority-#{priority.position}"
s << ' closed' if closed? s << ' closed' if closed?
s << ' overdue' if overdue? s << ' overdue' if overdue?
s << ' child' if child?
s << ' parent' unless leaf?
s << ' private' if is_private?
s << ' created-by-me' if User.current.logged? && author_id == User.current.id s << ' created-by-me' if User.current.logged? && author_id == User.current.id
s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
s s
@@ -587,7 +533,7 @@ class Issue < ActiveRecord::Base
# Returns false if save fails # Returns false if save fails
def save_issue_with_child_records(params, existing_time_entry=nil) def save_issue_with_child_records(params, existing_time_entry=nil)
Issue.transaction do Issue.transaction do
if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project) if params[:time_entry] && params[:time_entry][:hours].present? && User.current.allowed_to?(:log_time, project)
@time_entry = existing_time_entry || TimeEntry.new @time_entry = existing_time_entry || TimeEntry.new
@time_entry.project = project @time_entry.project = project
@time_entry.issue = self @time_entry.issue = self
@@ -596,10 +542,10 @@ class Issue < ActiveRecord::Base
@time_entry.attributes = params[:time_entry] @time_entry.attributes = params[:time_entry]
self.time_entries << @time_entry self.time_entries << @time_entry
end end
if valid? if valid?
attachments = Attachment.attach_files(self, params[:attachments]) attachments = Attachment.attach_files(self, params[:attachments])
attachments[:files].each {|a| @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => a.id, :value => a.filename)} attachments[:files].each {|a| @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => a.id, :value => a.filename)}
# TODO: Rename hook # TODO: Rename hook
Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal}) Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
@@ -624,7 +570,7 @@ class Issue < ActiveRecord::Base
# Update issues assigned to the version # Update issues assigned to the version
update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id]) update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
end end
# Unassigns issues from versions that are no longer shared # Unassigns issues from versions that are no longer shared
# after +project+ was moved # after +project+ was moved
def self.update_versions_from_hierarchy_change(project) def self.update_versions_from_hierarchy_change(project)
@@ -642,7 +588,7 @@ class Issue < ActiveRecord::Base
nil nil
end end
end end
def parent_issue_id def parent_issue_id
if instance_variable_defined? :@parent_issue if instance_variable_defined? :@parent_issue
@parent_issue.nil? ? nil : @parent_issue.id @parent_issue.nil? ? nil : @parent_issue.id
@@ -691,19 +637,17 @@ class Issue < ActiveRecord::Base
def self.by_subproject(project) def self.by_subproject(project)
ActiveRecord::Base.connection.select_all("select s.id as status_id, ActiveRecord::Base.connection.select_all("select s.id as status_id,
s.is_closed as closed, s.is_closed as closed,
#{Issue.table_name}.project_id as project_id, i.project_id as project_id,
count(#{Issue.table_name}.id) as total count(i.id) as total
from from
#{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s #{Issue.table_name} i, #{IssueStatus.table_name} s
where where
#{Issue.table_name}.status_id=s.id i.status_id=s.id
and #{Issue.table_name}.project_id = #{Project.table_name}.id and i.project_id IN (#{project.descendants.active.collect{|p| p.id}.join(',')})
and #{visible_condition(User.current, :project => project, :with_subprojects => true)} group by s.id, s.is_closed, i.project_id") if project.descendants.active.any?
and #{Issue.table_name}.project_id <> #{project.id}
group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
end end
# End ReportsController extraction # End ReportsController extraction
# Returns an array of projects that current user can move issues to # Returns an array of projects that current user can move issues to
def self.allowed_target_projects_on_move def self.allowed_target_projects_on_move
projects = [] projects = []
@@ -719,9 +663,9 @@ class Issue < ActiveRecord::Base
end end
projects projects
end end
private private
def update_nested_set_attributes def update_nested_set_attributes
if root_id.nil? if root_id.nil?
# issue was just created # issue was just created
@@ -768,7 +712,7 @@ class Issue < ActiveRecord::Base
end end
remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue) remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
end end
def update_parent_attributes def update_parent_attributes
recalculate_attributes_for(parent_id) if parent_id recalculate_attributes_for(parent_id) if parent_id
end end
@@ -779,14 +723,14 @@ class Issue < ActiveRecord::Base
if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :include => :priority) if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :include => :priority)
p.priority = IssuePriority.find_by_position(priority_position) p.priority = IssuePriority.find_by_position(priority_position)
end end
# start/due dates = lowest/highest dates of children # start/due dates = lowest/highest dates of children
p.start_date = p.children.minimum(:start_date) p.start_date = p.children.minimum(:start_date)
p.due_date = p.children.maximum(:due_date) p.due_date = p.children.maximum(:due_date)
if p.start_date && p.due_date && p.due_date < p.start_date if p.start_date && p.due_date && p.due_date < p.start_date
p.start_date, p.due_date = p.due_date, p.start_date p.start_date, p.due_date = p.due_date, p.start_date
end end
# done ratio = weighted average ratio of leaves # done ratio = weighted average ratio of leaves
unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
leaves_count = p.leaves.count leaves_count = p.leaves.count
@@ -800,16 +744,16 @@ class Issue < ActiveRecord::Base
p.done_ratio = progress.round p.done_ratio = progress.round
end end
end end
# estimate = sum of leaves estimates # estimate = sum of leaves estimates
p.estimated_hours = p.leaves.sum(:estimated_hours).to_f p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
p.estimated_hours = nil if p.estimated_hours == 0.0 p.estimated_hours = nil if p.estimated_hours == 0.0
# ancestors will be recursively updated # ancestors will be recursively updated
p.save(false) p.save(false)
end end
end end
# Update issues so their versions are not pointing to a # Update issues so their versions are not pointing to a
# fixed_version that is not shared with the issue's project # fixed_version that is not shared with the issue's project
def self.update_versions(conditions=nil) def self.update_versions(conditions=nil)
@@ -829,7 +773,7 @@ class Issue < ActiveRecord::Base
end end
end end
end end
# Callback on attachment deletion # Callback on attachment deletion
def attachment_removed(obj) def attachment_removed(obj)
journal = init_journal(User.current) journal = init_journal(User.current)
@@ -838,7 +782,7 @@ class Issue < ActiveRecord::Base
:old_value => obj.filename) :old_value => obj.filename)
journal.save journal.save
end end
# Default assignment based on category # Default assignment based on category
def default_assign def default_assign
if assigned_to.nil? && category && category.assigned_to if assigned_to.nil? && category && category.assigned_to
@@ -871,30 +815,27 @@ class Issue < ActiveRecord::Base
end end
end end
end end
# Saves the changes in a Journal # Saves the changes in a Journal
# Called after_save # Called after_save
def create_journal def create_journal
if @current_journal if @current_journal
# attributes changes # attributes changes
(Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c| (Issue.column_names - %w(id description root_id lft rgt lock_version created_on updated_on)).each {|c|
before = @issue_before_change.send(c)
after = send(c)
next if before == after || (before.blank? && after.blank?)
@current_journal.details << JournalDetail.new(:property => 'attr', @current_journal.details << JournalDetail.new(:property => 'attr',
:prop_key => c, :prop_key => c,
:old_value => @issue_before_change.send(c), :old_value => @issue_before_change.send(c),
:value => send(c)) :value => send(c)) unless send(c)==@issue_before_change.send(c)
} }
# custom fields changes # custom fields changes
custom_values.each {|c| custom_values.each {|c|
next if (@custom_values_before_change[c.custom_field_id]==c.value || next if (@custom_values_before_change[c.custom_field_id]==c.value ||
(@custom_values_before_change[c.custom_field_id].blank? && c.value.blank?)) (@custom_values_before_change[c.custom_field_id].blank? && c.value.blank?))
@current_journal.details << JournalDetail.new(:property => 'cf', @current_journal.details << JournalDetail.new(:property => 'cf',
:prop_key => c.custom_field_id, :prop_key => c.custom_field_id,
:old_value => @custom_values_before_change[c.custom_field_id], :old_value => @custom_values_before_change[c.custom_field_id],
:value => c.value) :value => c.value)
} }
@current_journal.save @current_journal.save
# reset current journal # reset current journal
init_journal @current_journal.user, @current_journal.notes init_journal @current_journal.user, @current_journal.notes
@@ -913,19 +854,20 @@ class Issue < ActiveRecord::Base
select_field = options.delete(:field) select_field = options.delete(:field)
joins = options.delete(:joins) joins = options.delete(:joins)
where = "#{Issue.table_name}.#{select_field}=j.id" where = "i.#{select_field}=j.id"
ActiveRecord::Base.connection.select_all("select s.id as status_id, ActiveRecord::Base.connection.select_all("select s.id as status_id,
s.is_closed as closed, s.is_closed as closed,
j.id as #{select_field}, j.id as #{select_field},
count(#{Issue.table_name}.id) as total count(i.id) as total
from from
#{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j #{Issue.table_name} i, #{IssueStatus.table_name} s, #{joins} j
where where
#{Issue.table_name}.status_id=s.id i.status_id=s.id
and #{where} and #{where}
and #{Issue.table_name}.project_id=#{Project.table_name}.id and i.project_id=#{project.id}
and #{visible_condition(User.current, :project => project)}
group by s.id, s.is_closed, j.id") group by s.id, s.is_closed, j.id")
end end
end end
+2 -4
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -24,8 +24,6 @@ class IssueCategory < ActiveRecord::Base
validates_uniqueness_of :name, :scope => [:project_id] validates_uniqueness_of :name, :scope => [:project_id]
validates_length_of :name, :maximum => 30 validates_length_of :name, :maximum => 30
named_scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
alias :destroy_without_reassign :destroy alias :destroy_without_reassign :destroy
# Destroy the category # Destroy the category
+1 -6
View File
@@ -47,12 +47,7 @@ class IssueRelation < ActiveRecord::Base
if issue_from && issue_to if issue_from && issue_to
errors.add :issue_to_id, :invalid if issue_from_id == issue_to_id errors.add :issue_to_id, :invalid if issue_from_id == issue_to_id
errors.add :issue_to_id, :not_same_project unless issue_from.project_id == issue_to.project_id || Setting.cross_project_issue_relations? errors.add :issue_to_id, :not_same_project unless issue_from.project_id == issue_to.project_id || Setting.cross_project_issue_relations?
#detect circular dependencies depending wether the relation should be reversed errors.add_to_base :circular_dependency if issue_to.all_dependent_issues.include? issue_from
if TYPES.has_key?(relation_type) && TYPES[relation_type][:reverse]
errors.add_to_base :circular_dependency if issue_from.all_dependent_issues.include? issue_to
else
errors.add_to_base :circular_dependency if issue_to.all_dependent_issues.include? issue_from
end
errors.add_to_base :cant_link_an_issue_with_a_descendant if issue_from.is_descendant_of?(issue_to) || issue_from.is_ancestor_of?(issue_to) errors.add_to_base :cant_link_an_issue_with_a_descendant if issue_from.is_descendant_of?(issue_to) || issue_from.is_ancestor_of?(issue_to)
end end
end end
+16 -20
View File
@@ -25,9 +25,8 @@ class IssueStatus < ActiveRecord::Base
validates_presence_of :name validates_presence_of :name
validates_uniqueness_of :name validates_uniqueness_of :name
validates_length_of :name, :maximum => 30 validates_length_of :name, :maximum => 30
validates_format_of :name, :with => /^[\w\s\'\-]*$/i
validates_inclusion_of :default_done_ratio, :in => 0..100, :allow_nil => true validates_inclusion_of :default_done_ratio, :in => 0..100, :allow_nil => true
named_scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
def after_save def after_save
IssueStatus.update_all("is_default=#{connection.quoted_false}", ['id <> ?', id]) if self.is_default? IssueStatus.update_all("is_default=#{connection.quoted_false}", ['id <> ?', id]) if self.is_default?
@@ -52,15 +51,10 @@ class IssueStatus < ActiveRecord::Base
# Returns an array of all statuses the given role can switch to # Returns an array of all statuses the given role can switch to
# Uses association cache when called more than one time # Uses association cache when called more than one time
def new_statuses_allowed_to(roles, tracker, author=false, assignee=false) def new_statuses_allowed_to(roles, tracker)
if roles && tracker if roles && tracker
role_ids = roles.collect(&:id) role_ids = roles.collect(&:id)
transitions = workflows.select do |w| new_statuses = workflows.select {|w| role_ids.include?(w.role_id) && w.tracker_id == tracker.id}.collect{|w| w.new_status}.compact.sort
role_ids.include?(w.role_id) &&
w.tracker_id == tracker.id &&
((!w.author && !w.assignee) || (author && w.author) || (assignee && w.assignee))
end
transitions.collect{|w| w.new_status}.compact.sort
else else
[] []
end end
@@ -68,22 +62,24 @@ class IssueStatus < ActiveRecord::Base
# Same thing as above but uses a database query # Same thing as above but uses a database query
# More efficient than the previous method if called just once # More efficient than the previous method if called just once
def find_new_statuses_allowed_to(roles, tracker, author=false, assignee=false) def find_new_statuses_allowed_to(roles, tracker)
if roles.present? && tracker if roles && tracker
conditions = "(author = :false AND assignee = :false)"
conditions << " OR author = :true" if author
conditions << " OR assignee = :true" if assignee
workflows.find(:all, workflows.find(:all,
:include => :new_status, :include => :new_status,
:conditions => ["role_id IN (:role_ids) AND tracker_id = :tracker_id AND (#{conditions})", :conditions => { :role_id => roles.collect(&:id),
{:role_ids => roles.collect(&:id), :tracker_id => tracker.id, :true => true, :false => false} :tracker_id => tracker.id}).collect{ |w| w.new_status }.compact.sort
]
).collect{|w| w.new_status}.compact.sort
else else
[] []
end end
end end
def new_status_allowed_to?(status, roles, tracker)
if status && roles && tracker
!workflows.find(:first, :conditions => {:new_status_id => status.id, :role_id => roles.collect(&:id), :tracker_id => tracker.id}).nil?
else
false
end
end
def <=>(status) def <=>(status)
position <=> status.position position <=> status.position
+3 -15
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -32,16 +32,12 @@ class Journal < ActiveRecord::Base
:url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.issue.id, :anchor => "change-#{o.id}"}} :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.issue.id, :anchor => "change-#{o.id}"}}
acts_as_activity_provider :type => 'issues', acts_as_activity_provider :type => 'issues',
:permission => :view_issues,
:author_key => :user_id, :author_key => :user_id,
:find_options => {:include => [{:issue => :project}, :details, :user], :find_options => {:include => [{:issue => :project}, :details, :user],
:conditions => "#{Journal.table_name}.journalized_type = 'Issue' AND" + :conditions => "#{Journal.table_name}.journalized_type = 'Issue' AND" +
" (#{JournalDetail.table_name}.prop_key = 'status_id' OR #{Journal.table_name}.notes <> '')"} " (#{JournalDetail.table_name}.prop_key = 'status_id' OR #{Journal.table_name}.notes <> '')"}
named_scope :visible, lambda {|*args| {
:include => {:issue => :project},
:conditions => Issue.visible_condition(args.shift || User.current, *args)
}}
def save(*args) def save(*args)
# Do not save an empty journal # Do not save an empty journal
(details.empty? && notes.blank?) ? false : super (details.empty? && notes.blank?) ? false : super
@@ -77,12 +73,4 @@ class Journal < ActiveRecord::Base
s << ' has-details' unless details.blank? s << ' has-details' unless details.blank?
s s
end end
def notify?
@notify != false
end
def notify=(arg)
@notify = arg
end
end end
+5 -18
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -17,22 +17,9 @@
class JournalDetail < ActiveRecord::Base class JournalDetail < ActiveRecord::Base
belongs_to :journal belongs_to :journal
before_save :normalize_values
private def before_save
self.value = value[0..254] if value && value.is_a?(String)
def normalize_values self.old_value = old_value[0..254] if old_value && old_value.is_a?(String)
self.value = normalize(value)
self.old_value = normalize(old_value)
end
def normalize(v)
if v == true
"1"
elsif v == false
"0"
else
v
end
end end
end end
+6 -8
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -17,12 +17,10 @@
class JournalObserver < ActiveRecord::Observer class JournalObserver < ActiveRecord::Observer
def after_create(journal) def after_create(journal)
if journal.notify? && if Setting.notified_events.include?('issue_updated') ||
(Setting.notified_events.include?('issue_updated') || (Setting.notified_events.include?('issue_note_added') && journal.notes.present?) ||
(Setting.notified_events.include?('issue_note_added') && journal.notes.present?) || (Setting.notified_events.include?('issue_status_updated') && journal.new_status.present?) ||
(Setting.notified_events.include?('issue_status_updated') && journal.new_status.present?) || (Setting.notified_events.include?('issue_priority_updated') && journal.new_value_for('priority_id').present?)
(Setting.notified_events.include?('issue_priority_updated') && journal.new_value_for('priority_id').present?)
)
Mailer.deliver_issue_edit(journal) Mailer.deliver_issue_edit(journal)
end end
end end
+45 -45
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -21,25 +21,25 @@ class MailHandler < ActionMailer::Base
class UnauthorizedAction < StandardError; end class UnauthorizedAction < StandardError; end
class MissingInformation < StandardError; end class MissingInformation < StandardError; end
attr_reader :email, :user attr_reader :email, :user
def self.receive(email, options={}) def self.receive(email, options={})
@@handler_options = options.dup @@handler_options = options.dup
@@handler_options[:issue] ||= {} @@handler_options[:issue] ||= {}
@@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String) @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String)
@@handler_options[:allow_override] ||= [] @@handler_options[:allow_override] ||= []
# Project needs to be overridable if not specified # Project needs to be overridable if not specified
@@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project) @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
# Status overridable by default # Status overridable by default
@@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status) @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
@@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false) @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1' ? true : false)
super email super email
end end
# Processes incoming emails # Processes incoming emails
# Returns the created object (eg. an issue, a message) or false # Returns the created object (eg. an issue, a message) or false
def receive(email) def receive(email)
@@ -78,13 +78,13 @@ class MailHandler < ActionMailer::Base
User.current = @user User.current = @user
dispatch dispatch
end end
private private
MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@} MESSAGE_ID_RE = %r{^<redmine\.([a-z0-9_]+)\-(\d+)\.\d+@}
ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]} ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]} MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
def dispatch def dispatch
headers = [email.in_reply_to, email.references].flatten.compact headers = [email.in_reply_to, email.references].flatten.compact
if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE} if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
@@ -117,7 +117,7 @@ class MailHandler < ActionMailer::Base
def dispatch_to_default def dispatch_to_default
receive_issue receive_issue
end end
# Creates a new issue # Creates a new issue
def receive_issue def receive_issue
project = target_project project = target_project
@@ -134,7 +134,7 @@ class MailHandler < ActionMailer::Base
issue.subject = '(no subject)' issue.subject = '(no subject)'
end end
issue.description = cleaned_up_text_body issue.description = cleaned_up_text_body
# add To and Cc as watchers before saving so the watchers can reply to Redmine # add To and Cc as watchers before saving so the watchers can reply to Redmine
add_watchers(issue) add_watchers(issue)
issue.save! issue.save!
@@ -142,7 +142,7 @@ class MailHandler < ActionMailer::Base
logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
issue issue
end end
# Adds a note to an existing issue # Adds a note to an existing issue
def receive_issue_reply(issue_id) def receive_issue_reply(issue_id)
issue = Issue.find_by_id(issue_id) issue = Issue.find_by_id(issue_id)
@@ -151,10 +151,10 @@ class MailHandler < ActionMailer::Base
unless @@handler_options[:no_permission_check] unless @@handler_options[:no_permission_check]
raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project) raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
end end
# ignore CLI-supplied defaults for new issues # ignore CLI-supplied defaults for new issues
@@handler_options[:issue].clear @@handler_options[:issue].clear
journal = issue.init_journal(user) journal = issue.init_journal(user)
issue.safe_attributes = issue_attributes_from_keywords(issue) issue.safe_attributes = issue_attributes_from_keywords(issue)
issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)} issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
@@ -164,7 +164,7 @@ class MailHandler < ActionMailer::Base
logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
journal journal
end end
# Reply will be added to the issue # Reply will be added to the issue
def receive_journal_reply(journal_id) def receive_journal_reply(journal_id)
journal = Journal.find_by_id(journal_id) journal = Journal.find_by_id(journal_id)
@@ -172,17 +172,17 @@ class MailHandler < ActionMailer::Base
receive_issue_reply(journal.journalized_id) receive_issue_reply(journal.journalized_id)
end end
end end
# Receives a reply to a forum message # Receives a reply to a forum message
def receive_message_reply(message_id) def receive_message_reply(message_id)
message = Message.find_by_id(message_id) message = Message.find_by_id(message_id)
if message if message
message = message.root message = message.root
unless @@handler_options[:no_permission_check] unless @@handler_options[:no_permission_check]
raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project) raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
end end
if !message.locked? if !message.locked?
reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip, reply = Message.new(:subject => email.subject.gsub(%r{^.*msg\d+\]}, '').strip,
:content => cleaned_up_text_body) :content => cleaned_up_text_body)
@@ -196,9 +196,9 @@ class MailHandler < ActionMailer::Base
end end
end end
end end
def add_attachments(obj) def add_attachments(obj)
if email.attachments && email.attachments.any? if email.has_attachments?
email.attachments.each do |attachment| email.attachments.each do |attachment|
Attachment.create(:container => obj, Attachment.create(:container => obj,
:file => attachment, :file => attachment,
@@ -207,7 +207,7 @@ class MailHandler < ActionMailer::Base
end end
end end
end end
# Adds To and Cc as watchers of the given object if the sender has the # Adds To and Cc as watchers of the given object if the sender has the
# appropriate permission # appropriate permission
def add_watchers(obj) def add_watchers(obj)
@@ -219,7 +219,7 @@ class MailHandler < ActionMailer::Base
end end
end end
end end
def get_keyword(attr, options={}) def get_keyword(attr, options={})
@keywords ||= {} @keywords ||= {}
if @keywords.has_key?(attr) if @keywords.has_key?(attr)
@@ -234,14 +234,14 @@ class MailHandler < ActionMailer::Base
end end
end end
end end
# Destructively extracts the value for +attr+ in +text+ # Destructively extracts the value for +attr+ in +text+
# Returns nil if no matching keyword found # Returns nil if no matching keyword found
def extract_keyword!(text, attr, format=nil) def extract_keyword!(text, attr, format=nil)
keys = [attr.to_s.humanize] keys = [attr.to_s.humanize]
if attr.is_a?(Symbol) if attr.is_a?(Symbol)
keys << l("field_#{attr}", :default => '', :locale => user.language) if user && user.language.present? keys << l("field_#{attr}", :default => '', :locale => user.language) if user
keys << l("field_#{attr}", :default => '', :locale => Setting.default_language) if Setting.default_language.present? keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
end end
keys.reject! {|k| k.blank?} keys.reject! {|k| k.blank?}
keys.collect! {|k| Regexp.escape(k)} keys.collect! {|k| Regexp.escape(k)}
@@ -258,34 +258,34 @@ class MailHandler < ActionMailer::Base
raise MissingInformation.new('Unable to determine target project') if target.nil? raise MissingInformation.new('Unable to determine target project') if target.nil?
target target
end end
# Returns a Hash of issue attributes extracted from keywords in the email body # Returns a Hash of issue attributes extracted from keywords in the email body
def issue_attributes_from_keywords(issue) def issue_attributes_from_keywords(issue)
assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_user_from_keyword(k) assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_user_from_keyword(k)
assigned_to = nil if assigned_to && !issue.assignable_users.include?(assigned_to) assigned_to = nil if assigned_to && !issue.assignable_users.include?(assigned_to)
attrs = { attrs = {
'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id), 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.find_by_name(k).try(:id),
'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id), 'status_id' => (k = get_keyword(:status)) && IssueStatus.find_by_name(k).try(:id),
'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id), 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.find_by_name(k).try(:id),
'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id), 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.find_by_name(k).try(:id),
'assigned_to_id' => assigned_to.try(:id), 'assigned_to_id' => assigned_to.try(:id),
'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && issue.project.shared_versions.named(k).first.try(:id), 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) && issue.project.shared_versions.find_by_name(k).try(:id),
'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'), 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'), 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
'estimated_hours' => get_keyword(:estimated_hours, :override => true), 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0') 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
}.delete_if {|k, v| v.blank? } }.delete_if {|k, v| v.blank? }
if issue.new_record? && attrs['tracker_id'].nil? if issue.new_record? && attrs['tracker_id'].nil?
attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id) attrs['tracker_id'] = issue.project.trackers.find(:first).try(:id)
end end
attrs attrs
end end
# Returns a Hash of issue custom field values extracted from keywords in the email body # Returns a Hash of issue custom field values extracted from keywords in the email body
def custom_field_values_from_keywords(customized) def custom_field_values_from_keywords(customized)
customized.custom_field_values.inject({}) do |h, v| customized.custom_field_values.inject({}) do |h, v|
if value = get_keyword(v.custom_field.name, :override => true) if value = get_keyword(v.custom_field.name, :override => true)
h[v.custom_field.id.to_s] = value h[v.custom_field.id.to_s] = value
@@ -293,7 +293,7 @@ class MailHandler < ActionMailer::Base
h h
end end
end end
# Returns the text/plain part of the email # Returns the text/plain part of the email
# If not found (eg. HTML-only email), returns the body with tags removed # If not found (eg. HTML-only email), returns the body with tags removed
def plain_text_body def plain_text_body
@@ -314,7 +314,7 @@ class MailHandler < ActionMailer::Base
@plain_text_body.strip! @plain_text_body.strip!
@plain_text_body @plain_text_body
end end
def cleaned_up_text_body def cleaned_up_text_body
cleanup_body(plain_text_body) cleanup_body(plain_text_body)
end end
@@ -322,19 +322,19 @@ class MailHandler < ActionMailer::Base
def self.full_sanitizer def self.full_sanitizer
@full_sanitizer ||= HTML::FullSanitizer.new @full_sanitizer ||= HTML::FullSanitizer.new
end end
# Creates a user account for the +email+ sender # Creates a user account for the +email+ sender
def self.create_user_from_email(email) def self.create_user_from_email(email)
addr = email.from_addrs.to_a.first addr = email.from_addrs.to_a.first
if addr && !addr.spec.blank? if addr && !addr.spec.blank?
user = User.new user = User.new
user.mail = addr.spec user.mail = addr.spec
names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split names = addr.name.blank? ? addr.spec.gsub(/@.*$/, '').split('.') : addr.name.split
user.firstname = names.shift user.firstname = names.shift
user.lastname = names.join(' ') user.lastname = names.join(' ')
user.lastname = '-' if user.lastname.blank? user.lastname = '-' if user.lastname.blank?
user.login = user.mail user.login = user.mail
user.password = ActiveSupport::SecureRandom.hex(5) user.password = ActiveSupport::SecureRandom.hex(5)
user.language = Setting.default_language user.language = Setting.default_language
@@ -343,7 +343,7 @@ class MailHandler < ActionMailer::Base
end end
private private
# Removes the email body of text after the truncation configurations. # Removes the email body of text after the truncation configurations.
def cleanup_body(body) def cleanup_body(body)
delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)} delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
+23 -41
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -31,7 +31,7 @@ class Mailer < ActionMailer::Base
h = h.to_s.gsub(%r{\/.*$}, '') unless Redmine::Utils.relative_url_root.blank? h = h.to_s.gsub(%r{\/.*$}, '') unless Redmine::Utils.relative_url_root.blank?
{ :host => h, :protocol => Setting.protocol } { :host => h, :protocol => Setting.protocol }
end end
# Builds a tmail object used to email recipients of the added issue. # Builds a tmail object used to email recipients of the added issue.
# #
# Example: # Example:
@@ -133,7 +133,7 @@ class Mailer < ActionMailer::Base
:added_to_url => added_to_url :added_to_url => added_to_url
render_multipart('attachments_added', body) render_multipart('attachments_added', body)
end end
# Builds a tmail object used to email recipients of a news' project when a news item is added. # Builds a tmail object used to email recipients of a news' project when a news item is added.
# #
# Example: # Example:
@@ -149,25 +149,7 @@ class Mailer < ActionMailer::Base
render_multipart('news_added', body) render_multipart('news_added', body)
end end
# Builds a tmail object used to email recipients of a news' project when a news comment is added. # Builds a tmail object used to email the recipients of the specified message that was posted.
#
# Example:
# news_comment_added(comment) => tmail object
# Mailer.news_comment_added(comment) => sends an email to the news' project recipients
def news_comment_added(comment)
news = comment.commented
redmine_headers 'Project' => news.project.identifier
message_id comment
recipients news.recipients
cc news.watcher_recipients
subject "Re: [#{news.project.name}] #{l(:label_news)}: #{news.title}"
body :news => news,
:comment => comment,
:news_url => url_for(:controller => 'news', :action => 'show', :id => news)
render_multipart('news_comment_added', body)
end
# Builds a tmail object used to email the recipients of the specified message that was posted.
# #
# Example: # Example:
# message_posted(message) => tmail object # message_posted(message) => tmail object
@@ -184,8 +166,8 @@ class Mailer < ActionMailer::Base
:message_url => url_for(message.event_url) :message_url => url_for(message.event_url)
render_multipart('message_posted', body) render_multipart('message_posted', body)
end end
# Builds a tmail object used to email the recipients of a project of the specified wiki content was added. # Builds a tmail object used to email the recipients of a project of the specified wiki content was added.
# #
# Example: # Example:
# wiki_content_added(wiki_content) => tmail object # wiki_content_added(wiki_content) => tmail object
@@ -201,8 +183,8 @@ class Mailer < ActionMailer::Base
:wiki_content_url => url_for(:controller => 'wiki', :action => 'show', :project_id => wiki_content.project, :id => wiki_content.page.title) :wiki_content_url => url_for(:controller => 'wiki', :action => 'show', :project_id => wiki_content.project, :id => wiki_content.page.title)
render_multipart('wiki_content_added', body) render_multipart('wiki_content_added', body)
end end
# Builds a tmail object used to email the recipients of a project of the specified wiki content was updated. # Builds a tmail object used to email the recipients of a project of the specified wiki content was updated.
# #
# Example: # Example:
# wiki_content_updated(wiki_content) => tmail object # wiki_content_updated(wiki_content) => tmail object
@@ -296,7 +278,7 @@ class Mailer < ActionMailer::Base
return false if (recipients.nil? || recipients.empty?) && return false if (recipients.nil? || recipients.empty?) &&
(cc.nil? || cc.empty?) && (cc.nil? || cc.empty?) &&
(bcc.nil? || bcc.empty?) (bcc.nil? || bcc.empty?)
# Set Message-Id and References # Set Message-Id and References
if @message_id_object if @message_id_object
mail.message_id = self.class.message_id_for(@message_id_object) mail.message_id = self.class.message_id_for(@message_id_object)
@@ -304,7 +286,7 @@ class Mailer < ActionMailer::Base
if @references_objects if @references_objects
mail.references = @references_objects.collect {|o| self.class.message_id_for(o)} mail.references = @references_objects.collect {|o| self.class.message_id_for(o)}
end end
# Log errors when raise_delivery_errors is set to false, Rails does not # Log errors when raise_delivery_errors is set to false, Rails does not
raise_errors = self.class.raise_delivery_errors raise_errors = self.class.raise_delivery_errors
self.class.raise_delivery_errors = true self.class.raise_delivery_errors = true
@@ -314,7 +296,7 @@ class Mailer < ActionMailer::Base
if raise_errors if raise_errors
raise e raise e
elsif mylogger elsif mylogger
mylogger.error "The following error occured while sending email notification: \"#{e.message}\". Check your configuration in config/configuration.yml." mylogger.error "The following error occured while sending email notification: \"#{e.message}\". Check your configuration in config/email.yml."
end end
ensure ensure
self.class.raise_delivery_errors = raise_errors self.class.raise_delivery_errors = raise_errors
@@ -347,7 +329,7 @@ class Mailer < ActionMailer::Base
deliver_reminder(assignee, issues, days) if assignee && assignee.active? deliver_reminder(assignee, issues, days) if assignee && assignee.active?
end end
end end
# Activates/desactivates email deliveries during +block+ # Activates/desactivates email deliveries during +block+
def self.with_deliveries(enabled = true, &block) def self.with_deliveries(enabled = true, &block)
was_enabled = ActionMailer::Base.perform_deliveries was_enabled = ActionMailer::Base.perform_deliveries
@@ -363,7 +345,7 @@ class Mailer < ActionMailer::Base
@initial_language = current_language @initial_language = current_language
set_language_if_valid Setting.default_language set_language_if_valid Setting.default_language
from Setting.mail_from from Setting.mail_from
# Common headers # Common headers
headers 'X-Mailer' => 'Redmine', headers 'X-Mailer' => 'Redmine',
'X-Redmine-Host' => Setting.host_name, 'X-Redmine-Host' => Setting.host_name,
@@ -386,11 +368,11 @@ class Mailer < ActionMailer::Base
recipients.delete(@author.mail) if recipients recipients.delete(@author.mail) if recipients
cc.delete(@author.mail) if cc cc.delete(@author.mail) if cc
end end
notified_users = [recipients, cc].flatten.compact.uniq notified_users = [recipients, cc].flatten.compact.uniq
# Rails would log recipients only, not cc and bcc # Rails would log recipients only, not cc and bcc
mylogger.info "Sending email notification to: #{notified_users.join(', ')}" if mylogger mylogger.info "Sending email notification to: #{notified_users.join(', ')}" if mylogger
# Blind carbon copy recipients # Blind carbon copy recipients
if Setting.bcc_recipients? if Setting.bcc_recipients?
bcc(notified_users) bcc(notified_users)
@@ -406,7 +388,7 @@ class Mailer < ActionMailer::Base
# #
# https://rails.lighthouseapp.com/projects/8994/tickets/2338-actionmailer-mailer-views-and-content-type # https://rails.lighthouseapp.com/projects/8994/tickets/2338-actionmailer-mailer-views-and-content-type
# https://rails.lighthouseapp.com/projects/8994/tickets/1799-actionmailer-doesnt-set-template_format-when-rendering-layouts # https://rails.lighthouseapp.com/projects/8994/tickets/1799-actionmailer-doesnt-set-template_format-when-rendering-layouts
def render_multipart(method_name, body) def render_multipart(method_name, body)
if Setting.plain_text_mail? if Setting.plain_text_mail?
content_type "text/plain" content_type "text/plain"
@@ -422,29 +404,29 @@ class Mailer < ActionMailer::Base
def self.controller_path def self.controller_path
'' ''
end unless respond_to?('controller_path') end unless respond_to?('controller_path')
# Returns a predictable Message-Id for the given object # Returns a predictable Message-Id for the given object
def self.message_id_for(object) def self.message_id_for(object)
# id + timestamp should reduce the odds of a collision # id + timestamp should reduce the odds of a collision
# as far as we don't send multiple emails for the same object # as far as we don't send multiple emails for the same object
timestamp = object.send(object.respond_to?(:created_on) ? :created_on : :updated_on) timestamp = object.send(object.respond_to?(:created_on) ? :created_on : :updated_on)
hash = "redmine.#{object.class.name.demodulize.underscore}-#{object.id}.#{timestamp.strftime("%Y%m%d%H%M%S")}" hash = "redmine.#{object.class.name.demodulize.underscore}-#{object.id}.#{timestamp.strftime("%Y%m%d%H%M%S")}"
host = Setting.mail_from.to_s.gsub(%r{^.*@}, '') host = Setting.mail_from.to_s.gsub(%r{^.*@}, '')
host = "#{::Socket.gethostname}.redmine" if host.empty? host = "#{::Socket.gethostname}.redmine" if host.empty?
"<#{hash}@#{host}>" "<#{hash}@#{host}>"
end end
private private
def message_id(object) def message_id(object)
@message_id_object = object @message_id_object = object
end end
def references(object) def references(object)
@references_objects ||= [] @references_objects ||= []
@references_objects << object @references_objects << object
end end
def mylogger def mylogger
RAILS_DEFAULT_LOGGER RAILS_DEFAULT_LOGGER
end end
+18 -21
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -21,10 +21,10 @@ class Message < ActiveRecord::Base
acts_as_tree :counter_cache => :replies_count, :order => "#{Message.table_name}.created_on ASC" acts_as_tree :counter_cache => :replies_count, :order => "#{Message.table_name}.created_on ASC"
acts_as_attachable acts_as_attachable
belongs_to :last_reply, :class_name => 'Message', :foreign_key => 'last_reply_id' belongs_to :last_reply, :class_name => 'Message', :foreign_key => 'last_reply_id'
acts_as_searchable :columns => ['subject', 'content'], acts_as_searchable :columns => ['subject', 'content'],
:include => {:board => :project}, :include => {:board => :project},
:project_key => "#{Board.table_name}.project_id", :project_key => 'project_id',
:date_column => "#{table_name}.created_on" :date_column => "#{table_name}.created_on"
acts_as_event :title => Proc.new {|o| "#{o.board.name}: #{o.subject}"}, acts_as_event :title => Proc.new {|o| "#{o.board.name}: #{o.subject}"},
:description => :content, :description => :content,
@@ -35,32 +35,29 @@ class Message < ActiveRecord::Base
acts_as_activity_provider :find_options => {:include => [{:board => :project}, :author]}, acts_as_activity_provider :find_options => {:include => [{:board => :project}, :author]},
:author_key => :author_id :author_key => :author_id
acts_as_watchable acts_as_watchable
attr_protected :locked, :sticky attr_protected :locked, :sticky
validates_presence_of :board, :subject, :content validates_presence_of :board, :subject, :content
validates_length_of :subject, :maximum => 255 validates_length_of :subject, :maximum => 255
after_create :add_author_as_watcher after_create :add_author_as_watcher
named_scope :visible, lambda {|*args| { :include => {:board => :project},
:conditions => Project.allowed_to_condition(args.shift || User.current, :view_messages, *args) } }
def visible?(user=User.current) def visible?(user=User.current)
!user.nil? && user.allowed_to?(:view_messages, project) !user.nil? && user.allowed_to?(:view_messages, project)
end end
def validate_on_create def validate_on_create
# Can not reply to a locked topic # Can not reply to a locked topic
errors.add_to_base 'Topic is locked' if root.locked? && self != root errors.add_to_base 'Topic is locked' if root.locked? && self != root
end end
def after_create def after_create
if parent if parent
parent.reload.update_attribute(:last_reply_id, self.id) parent.reload.update_attribute(:last_reply_id, self.id)
end end
board.reset_counters! board.reset_counters!
end end
def after_update def after_update
if board_id_changed? if board_id_changed?
Message.update_all("board_id = #{board_id}", ["id = ? OR parent_id = ?", root.id, root.id]) Message.update_all("board_id = #{board_id}", ["id = ? OR parent_id = ?", root.id, root.id])
@@ -68,19 +65,19 @@ class Message < ActiveRecord::Base
Board.reset_counters!(board_id) Board.reset_counters!(board_id)
end end
end end
def after_destroy def after_destroy
board.reset_counters! board.reset_counters!
end end
def sticky=(arg) def sticky=(arg)
write_attribute :sticky, (arg == true || arg.to_s == '1' ? 1 : 0) write_attribute :sticky, (arg == true || arg.to_s == '1' ? 1 : 0)
end end
def sticky? def sticky?
sticky == 1 sticky == 1
end end
def project def project
board.project board.project
end end
@@ -92,9 +89,9 @@ class Message < ActiveRecord::Base
def destroyable_by?(usr) def destroyable_by?(usr)
usr && usr.logged? && (usr.allowed_to?(:delete_messages, project) || (self.author == usr && usr.allowed_to?(:delete_own_messages, project))) usr && usr.logged? && (usr.allowed_to?(:delete_messages, project) || (self.author == usr && usr.allowed_to?(:delete_own_messages, project)))
end end
private private
def add_author_as_watcher def add_author_as_watcher
Watcher.create(:watchable => self.root, :user => author) Watcher.create(:watchable => self.root, :user => author)
end end
+4 -4
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+9 -18
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2008 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -19,7 +19,7 @@ class News < ActiveRecord::Base
belongs_to :project belongs_to :project
belongs_to :author, :class_name => 'User', :foreign_key => 'author_id' belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
has_many :comments, :as => :commented, :dependent => :delete_all, :order => "created_on" has_many :comments, :as => :commented, :dependent => :delete_all, :order => "created_on"
validates_presence_of :title, :description validates_presence_of :title, :description
validates_length_of :title, :maximum => 60 validates_length_of :title, :maximum => 60
validates_length_of :summary, :maximum => 255 validates_length_of :summary, :maximum => 255
@@ -28,27 +28,18 @@ class News < ActiveRecord::Base
acts_as_event :url => Proc.new {|o| {:controller => 'news', :action => 'show', :id => o.id}} acts_as_event :url => Proc.new {|o| {:controller => 'news', :action => 'show', :id => o.id}}
acts_as_activity_provider :find_options => {:include => [:project, :author]}, acts_as_activity_provider :find_options => {:include => [:project, :author]},
:author_key => :author_id :author_key => :author_id
acts_as_watchable
named_scope :visible, lambda {|*args| {
after_create :add_author_as_watcher
named_scope :visible, lambda {|*args| {
:include => :project, :include => :project,
:conditions => Project.allowed_to_condition(args.shift || User.current, :view_news, *args) :conditions => Project.allowed_to_condition(args.first || User.current, :view_news)
}} }}
def visible?(user=User.current) def visible?(user=User.current)
!user.nil? && user.allowed_to?(:view_news, project) !user.nil? && user.allowed_to?(:view_news, project)
end end
# returns latest news for projects visible by user # returns latest news for projects visible by user
def self.latest(user = User.current, count = 5) def self.latest(user = User.current, count = 5)
find(:all, :limit => count, :conditions => Project.allowed_to_condition(user, :view_news), :include => [ :author, :project ], :order => "#{News.table_name}.created_on DESC") find(:all, :limit => count, :conditions => Project.allowed_to_condition(user, :view_news), :include => [ :author, :project ], :order => "#{News.table_name}.created_on DESC")
end end
private
def add_author_as_watcher
Watcher.create(:watchable => self, :user => author)
end
end end
+32 -83
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -84,7 +84,7 @@ class Project < ActiveRecord::Base
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] } } 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] } }
named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"} named_scope :active, { :conditions => "#{Project.table_name}.status = #{STATUS_ACTIVE}"}
named_scope :all_public, { :conditions => { :is_public => true } } named_scope :all_public, { :conditions => { :is_public => true } }
named_scope :visible, lambda {|*args| {:conditions => Project.visible_condition(args.shift || User.current, *args) }} named_scope :visible, lambda { { :conditions => Project.visible_by(User.current) } }
def initialize(attributes = nil) def initialize(attributes = nil)
super super
@@ -115,36 +115,27 @@ class Project < ActiveRecord::Base
# returns latest created projects # returns latest created projects
# non public projects will be returned only if user is a member of those # non public projects will be returned only if user is a member of those
def self.latest(user=nil, count=5) def self.latest(user=nil, count=5)
visible(user).find(:all, :limit => count, :order => "created_on DESC") find(:all, :limit => count, :conditions => visible_by(user), :order => "created_on DESC")
end end
# Returns true if the project is visible to +user+ or to the current user. # Returns a SQL :conditions string used to find all active projects for the specified user.
def visible?(user=User.current)
user.allowed_to?(:view_project, self)
end
def self.visible_by(user=nil)
ActiveSupport::Deprecation.warn "Project.visible_by is deprecated and will be removed in Redmine 1.3.0. Use Project.visible_condition instead."
visible_condition(user || User.current)
end
# Returns a SQL conditions string used to find all projects visible by the specified user.
# #
# Examples: # Examples:
# Project.visible_condition(admin) => "projects.status = 1" # Projects.visible_by(admin) => "projects.status = 1"
# Project.visible_condition(normal_user) => "((projects.status = 1) AND (projects.is_public = 1 OR projects.id IN (1,3,4)))" # Projects.visible_by(normal_user) => "projects.status = 1 AND projects.is_public = 1"
# Project.visible_condition(anonymous) => "((projects.status = 1) AND (projects.is_public = 1))" def self.visible_by(user=nil)
def self.visible_condition(user, options={}) user ||= User.current
allowed_to_condition(user, :view_project, options) if user && user.admin?
return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
elsif user && user.memberships.any?
return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND (#{Project.table_name}.is_public = #{connection.quoted_true} or #{Project.table_name}.id IN (#{user.memberships.collect{|m| m.project_id}.join(',')}))"
else
return "#{Project.table_name}.status=#{Project::STATUS_ACTIVE} AND #{Project.table_name}.is_public = #{connection.quoted_true}"
end
end end
# Returns a SQL conditions string used to find all projects for which +user+ has the given +permission+
#
# Valid options:
# * :project => limit the condition to project
# * :with_subprojects => limit the condition to project and its subprojects
# * :member => limit the condition to the user projects
def self.allowed_to_condition(user, permission, options={}) def self.allowed_to_condition(user, permission, options={})
statements = []
base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}" base_statement = "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"
if perm = Redmine::AccessControl.permission(permission) if perm = Redmine::AccessControl.permission(permission)
unless perm.project_module.nil? unless perm.project_module.nil?
@@ -157,37 +148,24 @@ class Project < ActiveRecord::Base
project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects] project_statement << " OR (#{Project.table_name}.lft > #{options[:project].lft} AND #{Project.table_name}.rgt < #{options[:project].rgt})" if options[:with_subprojects]
base_statement = "(#{project_statement}) AND (#{base_statement})" base_statement = "(#{project_statement}) AND (#{base_statement})"
end end
if user.admin? if user.admin?
base_statement # no restriction
else else
statement_by_role = {} statements << "1=0"
unless options[:member]
role = user.logged? ? Role.non_member : Role.anonymous
if role.allowed_to?(permission)
statement_by_role[role] = "#{Project.table_name}.is_public = #{connection.quoted_true}"
end
end
if user.logged? if user.logged?
user.projects_by_role.each do |role, projects| if Role.non_member.allowed_to?(permission) && !options[:member]
if role.allowed_to?(permission) statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
statement_by_role[role] = "#{Project.table_name}.id IN (#{projects.collect(&:id).join(',')})"
end
end end
end allowed_project_ids = user.memberships.select {|m| m.roles.detect {|role| role.allowed_to?(permission)}}.collect {|m| m.project_id}
if statement_by_role.empty? statements << "#{Project.table_name}.id IN (#{allowed_project_ids.join(',')})" if allowed_project_ids.any?
"1=0"
else else
if block_given? if Role.anonymous.allowed_to?(permission) && !options[:member]
statement_by_role.each do |role, statement| # anonymous user allowed on public project
if s = yield(role, user) statements << "#{Project.table_name}.is_public = #{connection.quoted_true}"
statement_by_role[role] = "(#{statement} AND (#{s}))" end
end
end
end
"((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))"
end end
end end
statements.empty? ? base_statement : "((#{base_statement}) AND (#{statements.join(' OR ')}))"
end end
# Returns the Systemwide and project specific activities # Returns the Systemwide and project specific activities
@@ -369,7 +347,7 @@ class Project < ActiveRecord::Base
# Returns an array of the trackers used by the project and its active sub projects # Returns an array of the trackers used by the project and its active sub projects
def rolled_up_trackers def rolled_up_trackers
@rolled_up_trackers ||= @rolled_up_trackers ||=
Tracker.find(:all, :joins => :projects, Tracker.find(:all, :include => :projects,
:select => "DISTINCT #{Tracker.table_name}.*", :select => "DISTINCT #{Tracker.table_name}.*",
:conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt], :conditions => ["#{Project.table_name}.lft >= ? AND #{Project.table_name}.rgt <= ? AND #{Project.table_name}.status = #{STATUS_ACTIVE}", lft, rgt],
:order => "#{Tracker.table_name}.position") :order => "#{Tracker.table_name}.position")
@@ -395,17 +373,15 @@ class Project < ActiveRecord::Base
# Returns a scope of the Versions used by the project # Returns a scope of the Versions used by the project
def shared_versions def shared_versions
@shared_versions ||= begin @shared_versions ||=
r = root? ? self : root
Version.scoped(:include => :project, Version.scoped(:include => :project,
:conditions => "#{Project.table_name}.id = #{id}" + :conditions => "#{Project.table_name}.id = #{id}" +
" OR (#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND (" + " OR (#{Project.table_name}.status = #{Project::STATUS_ACTIVE} AND (" +
" #{Version.table_name}.sharing = 'system'" + " #{Version.table_name}.sharing = 'system'" +
" OR (#{Project.table_name}.lft >= #{r.lft} AND #{Project.table_name}.rgt <= #{r.rgt} AND #{Version.table_name}.sharing = 'tree')" + " OR (#{Project.table_name}.lft >= #{root.lft} AND #{Project.table_name}.rgt <= #{root.rgt} AND #{Version.table_name}.sharing = 'tree')" +
" OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" + " OR (#{Project.table_name}.lft < #{lft} AND #{Project.table_name}.rgt > #{rgt} AND #{Version.table_name}.sharing IN ('hierarchy', 'descendants'))" +
" OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" + " OR (#{Project.table_name}.lft > #{lft} AND #{Project.table_name}.rgt < #{rgt} AND #{Version.table_name}.sharing = 'hierarchy')" +
"))") "))")
end
end end
# Returns a hash of project users grouped by role # Returns a hash of project users grouped by role
@@ -447,12 +423,6 @@ class Project < ActiveRecord::Base
def all_issue_custom_fields def all_issue_custom_fields
@all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort @all_issue_custom_fields ||= (IssueCustomField.for_all + issue_custom_fields).uniq.sort
end end
# Returns an array of all custom fields enabled for project time entries
# (explictly associated custom fields and custom fields enabled for all projects)
def all_time_entry_custom_fields
@all_time_entry_custom_fields ||= (TimeEntryCustomField.for_all + time_entry_custom_fields).uniq.sort
end
def project def project
self self
@@ -549,27 +519,7 @@ class Project < ActiveRecord::Base
def enabled_module_names def enabled_module_names
enabled_modules.collect(&:name) enabled_modules.collect(&:name)
end end
# Enable a specific module
#
# Examples:
# project.enable_module!(:issue_tracking)
# project.enable_module!("issue_tracking")
def enable_module!(name)
enabled_modules << EnabledModule.new(:name => name.to_s) unless module_enabled?(name)
end
# Disable a module if it exists
#
# Examples:
# project.disable_module!(:issue_tracking)
# project.disable_module!("issue_tracking")
# project.disable_module!(project.enabled_modules.first)
def disable_module!(target)
target = enabled_modules.detect{|mod| target.to_s == mod.name} unless enabled_modules.include?(target)
target.destroy unless target.blank?
end
safe_attributes 'name', safe_attributes 'name',
'description', 'description',
'homepage', 'homepage',
@@ -714,7 +664,6 @@ class Project < ActiveRecord::Base
end end
# Copies issues from +project+ # Copies issues from +project+
# Note: issues assigned to a closed version won't be copied due to validation rules
def copy_issues(project) def copy_issues(project)
# Stores the source issue id as a key and the copied issues as the # Stores the source issue id as a key and the copied issues as the
# value. Used to map the two togeather for issue relations. # value. Used to map the two togeather for issue relations.
+102 -126
View File
@@ -1,24 +1,24 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2008 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class QueryColumn class QueryColumn
attr_accessor :name, :sortable, :groupable, :default_order attr_accessor :name, :sortable, :groupable, :default_order
include Redmine::I18n include Redmine::I18n
def initialize(name, options={}) def initialize(name, options={})
self.name = name self.name = name
self.sortable = options[:sortable] self.sortable = options[:sortable]
@@ -29,23 +29,19 @@ class QueryColumn
self.default_order = options[:default_order] self.default_order = options[:default_order]
@caption_key = options[:caption] || "field_#{name}" @caption_key = options[:caption] || "field_#{name}"
end end
def caption def caption
l(@caption_key) l(@caption_key)
end end
# Returns true if the column is sortable, otherwise false # Returns true if the column is sortable, otherwise false
def sortable? def sortable?
!sortable.nil? !sortable.nil?
end end
def value(issue) def value(issue)
issue.send name issue.send name
end end
def css_classes
name
end
end end
class QueryCustomFieldColumn < QueryColumn class QueryCustomFieldColumn < QueryColumn
@@ -59,41 +55,37 @@ class QueryCustomFieldColumn < QueryColumn
self.groupable ||= false self.groupable ||= false
@cf = custom_field @cf = custom_field
end end
def caption def caption
@cf.name @cf.name
end end
def custom_field def custom_field
@cf @cf
end end
def value(issue) def value(issue)
cv = issue.custom_values.detect {|v| v.custom_field_id == @cf.id} cv = issue.custom_values.detect {|v| v.custom_field_id == @cf.id}
cv && @cf.cast_value(cv.value) cv && @cf.cast_value(cv.value)
end end
def css_classes
@css_classes ||= "#{name} #{@cf.field_format}"
end
end end
class Query < ActiveRecord::Base class Query < ActiveRecord::Base
class StatementInvalid < ::ActiveRecord::StatementInvalid class StatementInvalid < ::ActiveRecord::StatementInvalid
end end
belongs_to :project belongs_to :project
belongs_to :user belongs_to :user
serialize :filters serialize :filters
serialize :column_names serialize :column_names
serialize :sort_criteria, Array serialize :sort_criteria, Array
attr_protected :project_id, :user_id attr_protected :project_id, :user_id
validates_presence_of :name, :on => :save validates_presence_of :name, :on => :save
validates_length_of :name, :maximum => 255 validates_length_of :name, :maximum => 255
@@operators = { "=" => :label_equals, @@operators = { "=" => :label_equals,
"!" => :label_not_equals, "!" => :label_not_equals,
"o" => :label_open_issues, "o" => :label_open_issues,
"c" => :label_closed_issues, "c" => :label_closed_issues,
@@ -113,7 +105,7 @@ class Query < ActiveRecord::Base
"!~" => :label_not_contains } "!~" => :label_not_contains }
cattr_reader :operators cattr_reader :operators
@@operators_by_filter_type = { :list => [ "=", "!" ], @@operators_by_filter_type = { :list => [ "=", "!" ],
:list_status => [ "o", "=", "!", "c", "*" ], :list_status => [ "o", "=", "!", "c", "*" ],
:list_optional => [ "=", "!", "!*", "*" ], :list_optional => [ "=", "!", "!*", "*" ],
@@ -145,32 +137,27 @@ class Query < ActiveRecord::Base
QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'), QueryColumn.new(:created_on, :sortable => "#{Issue.table_name}.created_on", :default_order => 'desc'),
] ]
cattr_reader :available_columns cattr_reader :available_columns
def initialize(attributes = nil) def initialize(attributes = nil)
super attributes super attributes
self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} } self.filters ||= { 'status_id' => {:operator => "o", :values => [""]} }
end end
def after_initialize def after_initialize
# Store the fact that project is nil (used in #editable_by?) # Store the fact that project is nil (used in #editable_by?)
@is_for_all = project.nil? @is_for_all = project.nil?
end end
def validate def validate
filters.each_key do |field| filters.each_key do |field|
errors.add label_for(field), :blank unless errors.add label_for(field), :blank unless
# filter requires one or more values # filter requires one or more values
(values_for(field) and !values_for(field).first.blank?) or (values_for(field) and !values_for(field).first.blank?) or
# filter doesn't require any value # filter doesn't require any value
["o", "c", "!*", "*", "t", "w"].include? operator_for(field) ["o", "c", "!*", "*", "t", "w"].include? operator_for(field)
end if filters end if filters
end end
# Returns true if the query is visible to +user+ or the current user.
def visible?(user=User.current)
self.is_public? || self.user_id == user.id
end
def editable_by?(user) def editable_by?(user)
return false unless user return false unless user
# Admin can edit them all and regular users can edit their private queries # Admin can edit them all and regular users can edit their private queries
@@ -178,23 +165,23 @@ class Query < ActiveRecord::Base
# Members can not edit public queries that are for all project (only admin is allowed to) # Members can not edit public queries that are for all project (only admin is allowed to)
is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project) is_public && !@is_for_all && user.allowed_to?(:manage_public_queries, project)
end end
def available_filters def available_filters
return @available_filters if @available_filters return @available_filters if @available_filters
trackers = project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers trackers = project.nil? ? Tracker.find(:all, :order => 'position') : project.rolled_up_trackers
@available_filters = { "status_id" => { :type => :list_status, :order => 1, :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } }, @available_filters = { "status_id" => { :type => :list_status, :order => 1, :values => IssueStatus.find(:all, :order => 'position').collect{|s| [s.name, s.id.to_s] } },
"tracker_id" => { :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] } }, "tracker_id" => { :type => :list, :order => 2, :values => trackers.collect{|s| [s.name, s.id.to_s] } },
"priority_id" => { :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] } }, "priority_id" => { :type => :list, :order => 3, :values => IssuePriority.all.collect{|s| [s.name, s.id.to_s] } },
"subject" => { :type => :text, :order => 8 }, "subject" => { :type => :text, :order => 8 },
"created_on" => { :type => :date_past, :order => 9 }, "created_on" => { :type => :date_past, :order => 9 },
"updated_on" => { :type => :date_past, :order => 10 }, "updated_on" => { :type => :date_past, :order => 10 },
"start_date" => { :type => :date, :order => 11 }, "start_date" => { :type => :date, :order => 11 },
"due_date" => { :type => :date, :order => 12 }, "due_date" => { :type => :date, :order => 12 },
"estimated_hours" => { :type => :integer, :order => 13 }, "estimated_hours" => { :type => :integer, :order => 13 },
"done_ratio" => { :type => :integer, :order => 14 }} "done_ratio" => { :type => :integer, :order => 14 }}
user_values = [] user_values = []
user_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged? user_values << ["<< #{l(:label_me)} >>", "me"] if User.current.logged?
if project if project
@@ -204,7 +191,7 @@ class Query < ActiveRecord::Base
if all_projects.any? if all_projects.any?
# members of visible projects # members of visible projects
user_values += User.active.find(:all, :conditions => ["#{User.table_name}.id IN (SELECT DISTINCT user_id FROM members WHERE project_id IN (?))", all_projects.collect(&:id)]).sort.collect{|s| [s.name, s.id.to_s] } user_values += User.active.find(:all, :conditions => ["#{User.table_name}.id IN (SELECT DISTINCT user_id FROM members WHERE project_id IN (?))", all_projects.collect(&:id)]).sort.collect{|s| [s.name, s.id.to_s] }
# project filter # project filter
project_values = [] project_values = []
Project.project_tree(all_projects) do |p, level| Project.project_tree(all_projects) do |p, level|
@@ -222,26 +209,21 @@ class Query < ActiveRecord::Base
role_values = Role.givable.collect {|r| [r.name, r.id.to_s] } role_values = Role.givable.collect {|r| [r.name, r.id.to_s] }
@available_filters["assigned_to_role"] = { :type => :list_optional, :order => 7, :values => role_values } unless role_values.empty? @available_filters["assigned_to_role"] = { :type => :list_optional, :order => 7, :values => role_values } unless role_values.empty?
if User.current.logged? if User.current.logged?
@available_filters["watcher_id"] = { :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]] } @available_filters["watcher_id"] = { :type => :list, :order => 15, :values => [["<< #{l(:label_me)} >>", "me"]] }
end end
if project if project
# project specific filters # project specific filters
categories = @project.issue_categories.all unless @project.issue_categories.empty?
unless categories.empty? @available_filters["category_id"] = { :type => :list_optional, :order => 6, :values => @project.issue_categories.collect{|s| [s.name, s.id.to_s] } }
@available_filters["category_id"] = { :type => :list_optional, :order => 6, :values => categories.collect{|s| [s.name, s.id.to_s] } }
end end
versions = @project.shared_versions.all unless @project.shared_versions.empty?
unless versions.empty? @available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => @project.shared_versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
@available_filters["fixed_version_id"] = { :type => :list_optional, :order => 7, :values => versions.sort.collect{|s| ["#{s.project.name} - #{s.name}", s.id.to_s] } }
end end
unless @project.leaf? unless @project.descendants.active.empty?
subprojects = @project.descendants.visible.all @available_filters["subproject_id"] = { :type => :list_subprojects, :order => 13, :values => @project.descendants.visible.collect{|s| [s.name, s.id.to_s] } }
unless subprojects.empty?
@available_filters["subproject_id"] = { :type => :list_subprojects, :order => 13, :values => subprojects.collect{|s| [s.name, s.id.to_s] } }
end
end end
add_custom_fields_filters(@project.all_issue_custom_fields) add_custom_fields_filters(@project.all_issue_custom_fields)
else else
@@ -254,7 +236,7 @@ class Query < ActiveRecord::Base
end end
@available_filters @available_filters
end end
def add_filter(field, operator, values) def add_filter(field, operator, values)
# values must be an array # values must be an array
return unless values and values.is_a? Array # and !values.first.empty? return unless values and values.is_a? Array # and !values.first.empty?
@@ -269,7 +251,7 @@ class Query < ActiveRecord::Base
filters[field] = {:operator => operator, :values => values } filters[field] = {:operator => operator, :values => values }
end end
end end
def add_short_filter(field, expression) def add_short_filter(field, expression)
return unless expression return unless expression
parms = expression.scan(/^(o|c|!\*|!|\*)?(.*)$/).first parms = expression.scan(/^(o|c|!\*|!|\*)?(.*)$/).first
@@ -284,19 +266,19 @@ class Query < ActiveRecord::Base
end end
end end
end end
def has_filter?(field) def has_filter?(field)
filters and filters[field] filters and filters[field]
end end
def operator_for(field) def operator_for(field)
has_filter?(field) ? filters[field][:operator] : nil has_filter?(field) ? filters[field][:operator] : nil
end end
def values_for(field) def values_for(field)
has_filter?(field) ? filters[field][:values] : nil has_filter?(field) ? filters[field][:values] : nil
end end
def label_for(field) def label_for(field)
label = available_filters[field][:name] if available_filters.has_key?(field) label = available_filters[field][:name] if available_filters.has_key?(field)
label ||= field.gsub(/\_id$/, "") label ||= field.gsub(/\_id$/, "")
@@ -308,17 +290,17 @@ class Query < ActiveRecord::Base
@available_columns += (project ? @available_columns += (project ?
project.all_issue_custom_fields : project.all_issue_custom_fields :
IssueCustomField.find(:all) IssueCustomField.find(:all)
).collect {|cf| QueryCustomFieldColumn.new(cf) } ).collect {|cf| QueryCustomFieldColumn.new(cf) }
end end
def self.available_columns=(v) def self.available_columns=(v)
self.available_columns = (v) self.available_columns = (v)
end end
def self.add_available_column(column) def self.add_available_column(column)
self.available_columns << (column) if column.is_a?(QueryColumn) self.available_columns << (column) if column.is_a?(QueryColumn)
end end
# Returns an array of columns that can be used to group the results # Returns an array of columns that can be used to group the results
def groupable_columns def groupable_columns
available_columns.select {|c| c.groupable} available_columns.select {|c| c.groupable}
@@ -331,42 +313,39 @@ class Query < ActiveRecord::Base
h h
}) })
end end
def columns def columns
# preserve the column_names order if has_default_columns?
(has_default_columns? ? default_columns_names : column_names).collect do |name| available_columns.select do |c|
available_columns.find { |col| col.name == name } # Adds the project column by default for cross-project lists
end.compact Setting.issue_list_default_columns.include?(c.name.to_s) || (c.name == :project && project.nil?)
end end
else
def default_columns_names # preserve the column_names order
@default_columns_names ||= begin column_names.collect {|name| available_columns.find {|col| col.name == name}}.compact
default_columns = Setting.issue_list_default_columns.map(&:to_sym)
project.present? ? default_columns : [:project] | default_columns
end end
end end
def column_names=(names) def column_names=(names)
if names if names
names = names.select {|n| n.is_a?(Symbol) || !n.blank? } names = names.select {|n| n.is_a?(Symbol) || !n.blank? }
names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym } names = names.collect {|n| n.is_a?(Symbol) ? n : n.to_sym }
# Set column_names to nil if default columns # Set column_names to nil if default columns
if names == default_columns_names if names.map(&:to_s) == Setting.issue_list_default_columns
names = nil names = nil
end end
end end
write_attribute(:column_names, names) write_attribute(:column_names, names)
end end
def has_column?(column) def has_column?(column)
column_names && column_names.include?(column.name) column_names && column_names.include?(column.name)
end end
def has_default_columns? def has_default_columns?
column_names.nil? || column_names.empty? column_names.nil? || column_names.empty?
end end
def sort_criteria=(arg) def sort_criteria=(arg)
c = [] c = []
if arg.is_a?(Hash) if arg.is_a?(Hash)
@@ -375,19 +354,19 @@ class Query < ActiveRecord::Base
c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, o == 'desc' ? o : 'asc']} c = arg.select {|k,o| !k.to_s.blank?}.slice(0,3).collect {|k,o| [k.to_s, o == 'desc' ? o : 'asc']}
write_attribute(:sort_criteria, c) write_attribute(:sort_criteria, c)
end end
def sort_criteria def sort_criteria
read_attribute(:sort_criteria) || [] read_attribute(:sort_criteria) || []
end end
def sort_criteria_key(arg) def sort_criteria_key(arg)
sort_criteria && sort_criteria[arg] && sort_criteria[arg].first sort_criteria && sort_criteria[arg] && sort_criteria[arg].first
end end
def sort_criteria_order(arg) def sort_criteria_order(arg)
sort_criteria && sort_criteria[arg] && sort_criteria[arg].last sort_criteria && sort_criteria[arg] && sort_criteria[arg].last
end end
# Returns the SQL sort order that should be prepended for grouping # Returns the SQL sort order that should be prepended for grouping
def group_by_sort_order def group_by_sort_order
if grouped? && (column = group_by_column) if grouped? && (column = group_by_column)
@@ -396,20 +375,20 @@ class Query < ActiveRecord::Base
"#{column.sortable} #{column.default_order}" "#{column.sortable} #{column.default_order}"
end end
end end
# Returns true if the query is a grouped query # Returns true if the query is a grouped query
def grouped? def grouped?
!group_by_column.nil? !group_by_column.nil?
end end
def group_by_column def group_by_column
groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by} groupable_columns.detect {|c| c.groupable && c.name.to_s == group_by}
end end
def group_by_statement def group_by_statement
group_by_column.try(:groupable) group_by_column.try(:groupable)
end end
def project_statement def project_statement
project_clauses = [] project_clauses = []
if project && !@project.descendants.active.empty? if project && !@project.descendants.active.empty?
@@ -432,7 +411,8 @@ class Query < ActiveRecord::Base
elsif project elsif project
project_clauses << "#{Project.table_name}.id = %d" % project.id project_clauses << "#{Project.table_name}.id = %d" % project.id
end end
project_clauses.any? ? project_clauses.join(' AND ') : nil project_clauses << Project.allowed_to_condition(User.current, :view_issues)
project_clauses.join(' AND ')
end end
def statement def statement
@@ -443,12 +423,12 @@ class Query < ActiveRecord::Base
v = values_for(field).clone v = values_for(field).clone
next unless v and !v.empty? next unless v and !v.empty?
operator = operator_for(field) operator = operator_for(field)
# "me" value subsitution # "me" value subsitution
if %w(assigned_to_id author_id watcher_id).include?(field) if %w(assigned_to_id author_id watcher_id).include?(field)
v.push(User.current.logged? ? User.current.id.to_s : "0") if v.delete("me") v.push(User.current.logged? ? User.current.id.to_s : "0") if v.delete("me")
end end
sql = '' sql = ''
if field =~ /^cf_(\d+)$/ if field =~ /^cf_(\d+)$/
# custom field # custom field
@@ -480,7 +460,7 @@ class Query < ActiveRecord::Base
end end
user_ids.flatten.uniq.compact user_ids.flatten.uniq.compact
}.sort.collect(&:to_s) }.sort.collect(&:to_s)
sql << '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')' sql << '(' + sql_for_field("assigned_to_id", operator, members_of_groups, Issue.table_name, "assigned_to_id", false) + ')'
elsif field == "assigned_to_role" # named field elsif field == "assigned_to_role" # named field
@@ -494,14 +474,14 @@ class Query < ActiveRecord::Base
roles = Role.givable.find_all_by_id(v) roles = Role.givable.find_all_by_id(v)
end end
roles ||= [] roles ||= []
members_of_roles = roles.inject([]) {|user_ids, role| members_of_roles = roles.inject([]) {|user_ids, role|
if role && role.members if role && role.members
user_ids << role.members.collect(&:user_id) user_ids << role.members.collect(&:user_id)
end end
user_ids.flatten.uniq.compact user_ids.flatten.uniq.compact
}.sort.collect(&:to_s) }.sort.collect(&:to_s)
sql << '(' + sql_for_field("assigned_to_id", operator, members_of_roles, Issue.table_name, "assigned_to_id", false) + ')' sql << '(' + sql_for_field("assigned_to_id", operator, members_of_roles, Issue.table_name, "assigned_to_id", false) + ')'
else else
# regular field # regular field
@@ -510,29 +490,26 @@ class Query < ActiveRecord::Base
sql << '(' + sql_for_field(field, operator, v, db_table, db_field) + ')' sql << '(' + sql_for_field(field, operator, v, db_table, db_field) + ')'
end end
filters_clauses << sql filters_clauses << sql
end if filters and valid? end if filters and valid?
filters_clauses << project_statement (filters_clauses << project_statement).join(' AND ')
filters_clauses.reject!(&:blank?)
filters_clauses.any? ? filters_clauses.join(' AND ') : nil
end end
# Returns the issue count # Returns the issue count
def issue_count def issue_count
Issue.visible.count(:include => [:status, :project], :conditions => statement) Issue.count(:include => [:status, :project], :conditions => statement)
rescue ::ActiveRecord::StatementInvalid => e rescue ::ActiveRecord::StatementInvalid => e
raise StatementInvalid.new(e.message) raise StatementInvalid.new(e.message)
end end
# Returns the issue count by group or nil if query is not grouped # Returns the issue count by group or nil if query is not grouped
def issue_count_by_group def issue_count_by_group
r = nil r = nil
if grouped? if grouped?
begin begin
# Rails will raise an (unexpected) RecordNotFound if there's only a nil group value # Rails will raise an (unexpected) RecordNotFound if there's only a nil group value
r = Issue.visible.count(:group => group_by_statement, :include => [:status, :project], :conditions => statement) r = Issue.count(:group => group_by_statement, :include => [:status, :project], :conditions => statement)
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
r = {nil => issue_count} r = {nil => issue_count}
end end
@@ -545,14 +522,14 @@ class Query < ActiveRecord::Base
rescue ::ActiveRecord::StatementInvalid => e rescue ::ActiveRecord::StatementInvalid => e
raise StatementInvalid.new(e.message) raise StatementInvalid.new(e.message)
end end
# Returns the issues # Returns the issues
# Valid options are :order, :offset, :limit, :include, :conditions # Valid options are :order, :offset, :limit, :include, :conditions
def issues(options={}) def issues(options={})
order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',') order_option = [group_by_sort_order, options[:order]].reject {|s| s.blank?}.join(',')
order_option = nil if order_option.blank? order_option = nil if order_option.blank?
Issue.visible.find :all, :include => ([:status, :project] + (options[:include] || [])).uniq, Issue.find :all, :include => ([:status, :project] + (options[:include] || [])).uniq,
:conditions => Query.merge_conditions(statement, options[:conditions]), :conditions => Query.merge_conditions(statement, options[:conditions]),
:order => order_option, :order => order_option,
:limit => options[:limit], :limit => options[:limit],
@@ -564,7 +541,7 @@ class Query < ActiveRecord::Base
# Returns the journals # Returns the journals
# Valid options are :order, :offset, :limit # Valid options are :order, :offset, :limit
def journals(options={}) def journals(options={})
Journal.visible.find :all, :include => [:details, :user, {:issue => [:project, :author, :tracker, :status]}], Journal.find :all, :include => [:details, :user, {:issue => [:project, :author, :tracker, :status]}],
:conditions => statement, :conditions => statement,
:order => options[:order], :order => options[:order],
:limit => options[:limit], :limit => options[:limit],
@@ -572,18 +549,18 @@ class Query < ActiveRecord::Base
rescue ::ActiveRecord::StatementInvalid => e rescue ::ActiveRecord::StatementInvalid => e
raise StatementInvalid.new(e.message) raise StatementInvalid.new(e.message)
end end
# Returns the versions # Returns the versions
# Valid options are :conditions # Valid options are :conditions
def versions(options={}) def versions(options={})
Version.visible.find :all, :include => :project, Version.find :all, :include => :project,
:conditions => Query.merge_conditions(project_statement, options[:conditions]) :conditions => Query.merge_conditions(project_statement, options[:conditions])
rescue ::ActiveRecord::StatementInvalid => e rescue ::ActiveRecord::StatementInvalid => e
raise StatementInvalid.new(e.message) raise StatementInvalid.new(e.message)
end end
private private
# Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+ # Helper method to generate the WHERE sql for a +field+, +operator+ and a +value+
def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false) def sql_for_field(field, operator, value, db_table, db_field, is_custom_filter=false)
sql = '' sql = ''
@@ -631,22 +608,24 @@ class Query < ActiveRecord::Base
when "t" when "t"
sql = date_range_clause(db_table, db_field, 0, 0) sql = date_range_clause(db_table, db_field, 0, 0)
when "w" when "w"
first_day_of_week = l(:general_first_day_of_week).to_i from = l(:general_first_day_of_week) == '7' ?
day_of_week = Date.today.cwday # week starts on sunday
days_ago = (day_of_week >= first_day_of_week ? day_of_week - first_day_of_week : day_of_week + 7 - first_day_of_week) ((Date.today.cwday == 7) ? Time.now.at_beginning_of_day : Time.now.at_beginning_of_week - 1.day) :
sql = date_range_clause(db_table, db_field, - days_ago, - days_ago + 6) # week starts on monday (Rails default)
Time.now.at_beginning_of_week
sql = "#{db_table}.#{db_field} BETWEEN '%s' AND '%s'" % [connection.quoted_date(from), connection.quoted_date(from + 7.days)]
when "~" when "~"
sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'" sql = "LOWER(#{db_table}.#{db_field}) LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
when "!~" when "!~"
sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'" sql = "LOWER(#{db_table}.#{db_field}) NOT LIKE '%#{connection.quote_string(value.first.to_s.downcase)}%'"
end end
return sql return sql
end end
def add_custom_fields_filters(custom_fields) def add_custom_fields_filters(custom_fields)
@available_filters ||= {} @available_filters ||= {}
custom_fields.select(&:is_filter?).each do |field| custom_fields.select(&:is_filter?).each do |field|
case field.field_format case field.field_format
when "text" when "text"
@@ -657,16 +636,13 @@ class Query < ActiveRecord::Base
options = { :type => :date, :order => 20 } options = { :type => :date, :order => 20 }
when "bool" when "bool"
options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 } options = { :type => :list, :values => [[l(:general_text_yes), "1"], [l(:general_text_no), "0"]], :order => 20 }
when "user", "version"
next unless project
options = { :type => :list_optional, :values => field.possible_values_options(project), :order => 20}
else else
options = { :type => :string, :order => 20 } options = { :type => :string, :order => 20 }
end end
@available_filters["cf_#{field.id}"] = options.merge({ :name => field.name }) @available_filters["cf_#{field.id}"] = options.merge({ :name => field.name })
end end
end end
# Returns a SQL clause for a date or datetime field. # Returns a SQL clause for a date or datetime field.
def date_range_clause(table, field, from, to) def date_range_clause(table, field, from, to)
s = [] s = []
+41 -145
View File
@@ -1,89 +1,52 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class Repository < ActiveRecord::Base class Repository < ActiveRecord::Base
include Redmine::Ciphering
belongs_to :project belongs_to :project
has_many :changesets, :order => "#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC" has_many :changesets, :order => "#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC"
has_many :changes, :through => :changesets has_many :changes, :through => :changesets
serialize :extra_info
# Raw SQL to delete changesets and changes in the database # Raw SQL to delete changesets and changes in the database
# has_many :changesets, :dependent => :destroy is too slow for big repositories # has_many :changesets, :dependent => :destroy is too slow for big repositories
before_destroy :clear_changesets before_destroy :clear_changesets
validates_length_of :password, :maximum => 255, :allow_nil => true
# Checks if the SCM is enabled when creating a repository # Checks if the SCM is enabled when creating a repository
validate_on_create { |r| r.errors.add(:type, :invalid) unless Setting.enabled_scm.include?(r.class.name.demodulize) } validate_on_create { |r| r.errors.add(:type, :invalid) unless Setting.enabled_scm.include?(r.class.name.demodulize) }
def self.human_attribute_name(attribute_key_name)
attr_name = attribute_key_name
if attr_name == "log_encoding"
attr_name = "commit_logs_encoding"
end
super(attr_name)
end
# Removes leading and trailing whitespace # Removes leading and trailing whitespace
def url=(arg) def url=(arg)
write_attribute(:url, arg ? arg.to_s.strip : nil) write_attribute(:url, arg ? arg.to_s.strip : nil)
end end
# Removes leading and trailing whitespace # Removes leading and trailing whitespace
def root_url=(arg) def root_url=(arg)
write_attribute(:root_url, arg ? arg.to_s.strip : nil) write_attribute(:root_url, arg ? arg.to_s.strip : nil)
end end
def password
read_ciphered_attribute(:password)
end
def password=(arg)
write_ciphered_attribute(:password, arg)
end
def scm_adapter
self.class.scm_adapter_class
end
def scm def scm
@scm ||= self.scm_adapter.new(url, root_url, @scm ||= self.scm_adapter.new url, root_url, login, password
login, password, path_encoding)
update_attribute(:root_url, @scm.root_url) if root_url.blank? update_attribute(:root_url, @scm.root_url) if root_url.blank?
@scm @scm
end end
def scm_name def scm_name
self.class.scm_name self.class.scm_name
end end
def merge_extra_info(arg)
h = extra_info || {}
return h if arg.nil?
h.merge!(arg)
write_attribute(:extra_info, h)
end
def report_last_commit
true
end
def supports_cat? def supports_cat?
scm.supports_cat? scm.supports_cat?
end end
@@ -91,19 +54,11 @@ class Repository < ActiveRecord::Base
def supports_annotate? def supports_annotate?
scm.supports_annotate? scm.supports_annotate?
end end
def supports_all_revisions?
true
end
def supports_directory_revisions?
false
end
def entry(path=nil, identifier=nil) def entry(path=nil, identifier=nil)
scm.entry(path, identifier) scm.entry(path, identifier)
end end
def entries(path=nil, identifier=nil) def entries(path=nil, identifier=nil)
scm.entries(path, identifier) scm.entries(path, identifier)
end end
@@ -117,28 +72,21 @@ class Repository < ActiveRecord::Base
end end
def default_branch def default_branch
nil scm.default_branch
end end
def properties(path, identifier=nil) def properties(path, identifier=nil)
scm.properties(path, identifier) scm.properties(path, identifier)
end end
def cat(path, identifier=nil) def cat(path, identifier=nil)
scm.cat(path, identifier) scm.cat(path, identifier)
end end
def diff(path, rev, rev_to) def diff(path, rev, rev_to)
scm.diff(path, rev, rev_to) scm.diff(path, rev, rev_to)
end end
def diff_format_revisions(cs, cs_to, sep=':')
text = ""
text << cs_to.format_identifier + sep if cs_to
text << cs.format_identifier if cs
text
end
# Returns a path relative to the url of the repository # Returns a path relative to the url of the repository
def relative_path(path) def relative_path(path)
path path
@@ -147,8 +95,7 @@ class Repository < ActiveRecord::Base
# Finds and returns a revision with a number or the beginning of a hash # Finds and returns a revision with a number or the beginning of a hash
def find_changeset_by_name(name) def find_changeset_by_name(name)
return nil if name.blank? return nil if name.blank?
changesets.find(:first, :conditions => (name.match(/^\d*$/) ? changesets.find(:first, :conditions => (name.match(/^\d*$/) ? ["revision = ?", name.to_s] : ["revision LIKE ?", name + '%']))
["revision = ?", name.to_s] : ["revision LIKE ?", name + '%']))
end end
def latest_changeset def latest_changeset
@@ -159,32 +106,26 @@ class Repository < ActiveRecord::Base
# Default behaviour is to search in cached changesets # Default behaviour is to search in cached changesets
def latest_changesets(path, rev, limit=10) def latest_changesets(path, rev, limit=10)
if path.blank? if path.blank?
changesets.find( changesets.find(:all, :include => :user,
:all, :order => "#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC",
:include => :user, :limit => limit)
:order => "#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC",
:limit => limit)
else else
changes.find( changes.find(:all, :include => {:changeset => :user},
:all, :conditions => ["path = ?", path.with_leading_slash],
:include => {:changeset => :user}, :order => "#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC",
:conditions => ["path = ?", path.with_leading_slash], :limit => limit).collect(&:changeset)
:order => "#{Changeset.table_name}.committed_on DESC, #{Changeset.table_name}.id DESC",
:limit => limit
).collect(&:changeset)
end end
end end
def scan_changesets_for_issue_ids def scan_changesets_for_issue_ids
self.changesets.each(&:scan_comment_for_issue_ids) self.changesets.each(&:scan_comment_for_issue_ids)
end end
# Returns an array of committers usernames and associated user_id # Returns an array of committers usernames and associated user_id
def committers def committers
@committers ||= Changeset.connection.select_rows( @committers ||= Changeset.connection.select_rows("SELECT DISTINCT committer, user_id FROM #{Changeset.table_name} WHERE repository_id = #{id}")
"SELECT DISTINCT committer, user_id FROM #{Changeset.table_name} WHERE repository_id = #{id}")
end end
# Maps committers username to a user ids # Maps committers username to a user ids
def committer_ids=(h) def committer_ids=(h)
if h.is_a?(Hash) if h.is_a?(Hash)
@@ -192,19 +133,17 @@ class Repository < ActiveRecord::Base
new_user_id = h[committer] new_user_id = h[committer]
if new_user_id && (new_user_id.to_i != user_id.to_i) if new_user_id && (new_user_id.to_i != user_id.to_i)
new_user_id = (new_user_id.to_i > 0 ? new_user_id.to_i : nil) new_user_id = (new_user_id.to_i > 0 ? new_user_id.to_i : nil)
Changeset.update_all( Changeset.update_all("user_id = #{ new_user_id.nil? ? 'NULL' : new_user_id }", ["repository_id = ? AND committer = ?", id, committer])
"user_id = #{ new_user_id.nil? ? 'NULL' : new_user_id }",
["repository_id = ? AND committer = ?", id, committer])
end end
end end
@committers = nil @committers = nil
@found_committer_users = nil @found_committer_users = nil
true true
else else
false false
end end
end end
# Returns the Redmine User corresponding to the given +committer+ # Returns the Redmine User corresponding to the given +committer+
# It will return nil if the committer is not yet mapped and if no User # It will return nil if the committer is not yet mapped and if no User
# with the same username or email was found # with the same username or email was found
@@ -212,7 +151,7 @@ class Repository < ActiveRecord::Base
unless committer.blank? unless committer.blank?
@found_committer_users ||= {} @found_committer_users ||= {}
return @found_committer_users[committer] if @found_committer_users.has_key?(committer) return @found_committer_users[committer] if @found_committer_users.has_key?(committer)
user = nil user = nil
c = changesets.find(:first, :conditions => {:committer => committer}, :include => :user) c = changesets.find(:first, :conditions => {:committer => committer}, :include => :user)
if c && c.user if c && c.user
@@ -227,27 +166,18 @@ class Repository < ActiveRecord::Base
user user
end end
end end
def repo_log_encoding
encoding = log_encoding.to_s.strip
encoding.blank? ? 'UTF-8' : encoding
end
# Fetches new changesets for all repositories of active projects # Fetches new changesets for all repositories of active projects
# Can be called periodically by an external script # Can be called periodically by an external script
# eg. ruby script/runner "Repository.fetch_changesets" # eg. ruby script/runner "Repository.fetch_changesets"
def self.fetch_changesets def self.fetch_changesets
Project.active.has_module(:repository).find(:all, :include => :repository).each do |project| Project.active.has_module(:repository).find(:all, :include => :repository).each do |project|
if project.repository if project.repository
begin project.repository.fetch_changesets
project.repository.fetch_changesets
rescue Redmine::Scm::Adapters::CommandFailed => e
logger.error "scm: error during fetching changesets: #{e.message}"
end
end end
end end
end end
# scan changeset comments to find related and fixed issues for all repositories # scan changeset comments to find related and fixed issues for all repositories
def self.scan_changesets_for_issue_ids def self.scan_changesets_for_issue_ids
find(:all).each(&:scan_changesets_for_issue_ids) find(:all).each(&:scan_changesets_for_issue_ids)
@@ -256,61 +186,27 @@ class Repository < ActiveRecord::Base
def self.scm_name def self.scm_name
'Abstract' 'Abstract'
end end
def self.available_scm def self.available_scm
subclasses.collect {|klass| [klass.scm_name, klass.name]} subclasses.collect {|klass| [klass.scm_name, klass.name]}
end end
def self.factory(klass_name, *args) def self.factory(klass_name, *args)
klass = "Repository::#{klass_name}".constantize klass = "Repository::#{klass_name}".constantize
klass.new(*args) klass.new(*args)
rescue rescue
nil nil
end end
def self.scm_adapter_class
nil
end
def self.scm_command
ret = ""
begin
ret = self.scm_adapter_class.client_command if self.scm_adapter_class
rescue Exception => e
logger.error "scm: error during get command: #{e.message}"
end
ret
end
def self.scm_version_string
ret = ""
begin
ret = self.scm_adapter_class.client_version_string if self.scm_adapter_class
rescue Exception => e
logger.error "scm: error during get version string: #{e.message}"
end
ret
end
def self.scm_available
ret = false
begin
ret = self.scm_adapter_class.client_available if self.scm_adapter_class
rescue Exception => e
logger.error "scm: error during get scm available: #{e.message}"
end
ret
end
private private
def before_save def before_save
# Strips url and root_url # Strips url and root_url
url.strip! url.strip!
root_url.strip! root_url.strip!
true true
end end
def clear_changesets def clear_changesets
cs, ch, ci = Changeset.table_name, Change.table_name, "#{table_name_prefix}changesets_issues#{table_name_suffix}" cs, ch, ci = Changeset.table_name, Change.table_name, "#{table_name_prefix}changesets_issues#{table_name_suffix}"
connection.delete("DELETE FROM #{ch} WHERE #{ch}.changeset_id IN (SELECT #{cs}.id FROM #{cs} WHERE #{cs}.repository_id = #{id})") connection.delete("DELETE FROM #{ch} WHERE #{ch}.changeset_id IN (SELECT #{cs}.id FROM #{cs} WHERE #{cs}.repository_id = #{id})")
+24 -37
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -19,24 +19,16 @@ require 'redmine/scm/adapters/bazaar_adapter'
class Repository::Bazaar < Repository class Repository::Bazaar < Repository
attr_protected :root_url attr_protected :root_url
validates_presence_of :url, :log_encoding validates_presence_of :url
def self.human_attribute_name(attribute_key_name) def scm_adapter
attr_name = attribute_key_name
if attr_name == "url"
attr_name = "path_to_repository"
end
super(attr_name)
end
def self.scm_adapter_class
Redmine::Scm::Adapters::BazaarAdapter Redmine::Scm::Adapters::BazaarAdapter
end end
def self.scm_name def self.scm_name
'Bazaar' 'Bazaar'
end end
def entries(path=nil, identifier=nil) def entries(path=nil, identifier=nil)
entries = scm.entries(path, identifier) entries = scm.entries(path, identifier)
if entries if entries
@@ -47,24 +39,19 @@ class Repository::Bazaar < Repository
full_path = File.join(root_url, e.path) full_path = File.join(root_url, e.path)
e.size = File.stat(full_path).size if File.file?(full_path) e.size = File.stat(full_path).size if File.file?(full_path)
end end
c = Change.find( c = Change.find(:first,
:first, :include => :changeset,
:include => :changeset, :conditions => ["#{Change.table_name}.revision = ? and #{Changeset.table_name}.repository_id = ?", e.lastrev.revision, id],
:conditions => [ :order => "#{Changeset.table_name}.revision DESC")
"#{Change.table_name}.revision = ? and #{Changeset.table_name}.repository_id = ?",
e.lastrev.revision,
id
],
:order => "#{Changeset.table_name}.revision DESC")
if c if c
e.lastrev.identifier = c.changeset.revision e.lastrev.identifier = c.changeset.revision
e.lastrev.name = c.changeset.revision e.lastrev.name = c.changeset.revision
e.lastrev.author = c.changeset.committer e.lastrev.author = c.changeset.committer
end end
end end
end end
end end
def fetch_changesets def fetch_changesets
scm_info = scm.info scm_info = scm.info
if scm_info if scm_info
@@ -81,18 +68,18 @@ class Repository::Bazaar < Repository
revisions = scm.revisions('', identifier_to, identifier_from, :with_paths => true) revisions = scm.revisions('', identifier_to, identifier_from, :with_paths => true)
transaction do transaction do
revisions.reverse_each do |revision| revisions.reverse_each do |revision|
changeset = Changeset.create(:repository => self, changeset = Changeset.create(:repository => self,
:revision => revision.identifier, :revision => revision.identifier,
:committer => revision.author, :committer => revision.author,
:committed_on => revision.time, :committed_on => revision.time,
:scmid => revision.scmid, :scmid => revision.scmid,
:comments => revision.message) :comments => revision.message)
revision.paths.each do |change| revision.paths.each do |change|
Change.create(:changeset => changeset, Change.create(:changeset => changeset,
:action => change[:action], :action => change[:action],
:path => change[:path], :path => change[:path],
:revision => change[:revision]) :revision => change[:revision])
end end
end end
end unless revisions.nil? end unless revisions.nil?
+74 -118
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -19,95 +19,67 @@ require 'redmine/scm/adapters/cvs_adapter'
require 'digest/sha1' require 'digest/sha1'
class Repository::Cvs < Repository class Repository::Cvs < Repository
validates_presence_of :url, :root_url, :log_encoding validates_presence_of :url, :root_url
def self.human_attribute_name(attribute_key_name) def scm_adapter
attr_name = attribute_key_name
if attr_name == "root_url"
attr_name = "cvsroot"
elsif attr_name == "url"
attr_name = "cvs_module"
end
super(attr_name)
end
def self.scm_adapter_class
Redmine::Scm::Adapters::CvsAdapter Redmine::Scm::Adapters::CvsAdapter
end end
def self.scm_name def self.scm_name
'CVS' 'CVS'
end end
def entry(path=nil, identifier=nil) def entry(path=nil, identifier=nil)
rev = identifier.nil? ? nil : changesets.find_by_revision(identifier) rev = identifier.nil? ? nil : changesets.find_by_revision(identifier)
scm.entry(path, rev.nil? ? nil : rev.committed_on) scm.entry(path, rev.nil? ? nil : rev.committed_on)
end end
def entries(path=nil, identifier=nil) def entries(path=nil, identifier=nil)
rev = nil rev = identifier.nil? ? nil : changesets.find_by_revision(identifier)
if ! identifier.nil?
rev = changesets.find_by_revision(identifier)
return nil if rev.nil?
end
entries = scm.entries(path, rev.nil? ? nil : rev.committed_on) entries = scm.entries(path, rev.nil? ? nil : rev.committed_on)
if entries if entries
entries.each() do |entry| entries.each() do |entry|
if ( ! entry.lastrev.nil? ) && ( ! entry.lastrev.revision.nil? ) unless entry.lastrev.nil? || entry.lastrev.identifier
change=changes.find_by_revision_and_path( change=changes.find_by_revision_and_path( entry.lastrev.revision, scm.with_leading_slash(entry.path) )
entry.lastrev.revision,
scm.with_leading_slash(entry.path) )
if change if change
entry.lastrev.identifier = change.changeset.revision entry.lastrev.identifier=change.changeset.revision
entry.lastrev.revision = change.changeset.revision entry.lastrev.author=change.changeset.committer
entry.lastrev.author = change.changeset.committer entry.lastrev.revision=change.revision
# entry.lastrev.branch = change.branch entry.lastrev.branch=change.branch
end end
end end
end end
end end
entries entries
end end
def cat(path, identifier=nil) def cat(path, identifier=nil)
rev = nil rev = identifier.nil? ? nil : changesets.find_by_revision(identifier)
if ! identifier.nil?
rev = changesets.find_by_revision(identifier)
return nil if rev.nil?
end
scm.cat(path, rev.nil? ? nil : rev.committed_on) scm.cat(path, rev.nil? ? nil : rev.committed_on)
end end
def annotate(path, identifier=nil)
rev = nil
if ! identifier.nil?
rev = changesets.find_by_revision(identifier)
return nil if rev.nil?
end
scm.annotate(path, rev.nil? ? nil : rev.committed_on)
end
def diff(path, rev, rev_to) def diff(path, rev, rev_to)
# convert rev to revision. CVS can't handle changesets here #convert rev to revision. CVS can't handle changesets here
diff=[] diff=[]
changeset_from = changesets.find_by_revision(rev) changeset_from=changesets.find_by_revision(rev)
if rev_to.to_i > 0 if rev_to.to_i > 0
changeset_to = changesets.find_by_revision(rev_to) changeset_to=changesets.find_by_revision(rev_to)
end end
changeset_from.changes.each() do |change_from| changeset_from.changes.each() do |change_from|
revision_from = nil
revision_to = nil revision_from=nil
if path.nil? || (change_from.path.starts_with? scm.with_leading_slash(path)) revision_to=nil
revision_from = change_from.revision
end revision_from=change_from.revision if path.nil? || (change_from.path.starts_with? scm.with_leading_slash(path))
if revision_from if revision_from
if changeset_to if changeset_to
changeset_to.changes.each() do |change_to| changeset_to.changes.each() do |change_to|
revision_to = change_to.revision if change_to.path == change_from.path revision_to=change_to.revision if change_to.path==change_from.path
end end
end end
unless revision_to unless revision_to
revision_to = scm.get_previous_revision(revision_from) revision_to=scm.get_previous_revision(revision_from)
end end
file_diff = scm.diff(change_from.path, revision_from, revision_to) file_diff = scm.diff(change_from.path, revision_from, revision_to)
diff = diff + file_diff unless file_diff.nil? diff = diff + file_diff unless file_diff.nil?
@@ -115,91 +87,75 @@ class Repository::Cvs < Repository
end end
return diff return diff
end end
def fetch_changesets def fetch_changesets
# some nifty bits to introduce a commit-id with cvs # some nifty bits to introduce a commit-id with cvs
# natively cvs doesn't provide any kind of changesets, # natively cvs doesn't provide any kind of changesets, there is only a revision per file.
# there is only a revision per file.
# we now take a guess using the author, the commitlog and the commit-date. # we now take a guess using the author, the commitlog and the commit-date.
# last one is the next step to take. the commit-date is not equal for all # last one is the next step to take. the commit-date is not equal for all
# commits in one changeset. cvs update the commit-date when the *,v file was touched. so # commits in one changeset. cvs update the commit-date when the *,v file was touched. so
# we use a small delta here, to merge all changes belonging to _one_ changeset # we use a small delta here, to merge all changes belonging to _one_ changeset
time_delta = 10.seconds time_delta=10.seconds
fetch_since = latest_changeset ? latest_changeset.committed_on : nil fetch_since = latest_changeset ? latest_changeset.committed_on : nil
transaction do transaction do
tmp_rev_num = 1 tmp_rev_num = 1
scm.revisions('', fetch_since, nil, :log_encoding => repo_log_encoding) do |revision| scm.revisions('', fetch_since, nil, :with_paths => true) do |revision|
# only add the change to the database, if it doen't exists. the cvs log # only add the change to the database, if it doen't exists. the cvs log
# is not exclusive at all. # is not exclusive at all.
tmp_time = revision.time.clone unless changes.find_by_path_and_revision(scm.with_leading_slash(revision.paths[0][:path]), revision.paths[0][:revision])
unless changes.find_by_path_and_revision( revision
scm.with_leading_slash(revision.paths[0][:path]), cs = changesets.find(:first, :conditions=>{
revision.paths[0][:revision] :committed_on=>revision.time-time_delta..revision.time+time_delta,
) :committer=>revision.author,
cmt = Changeset.normalize_comments(revision.message, repo_log_encoding) :comments=>Changeset.normalize_comments(revision.message)
author_utf8 = Changeset.to_utf8(revision.author, repo_log_encoding) })
cs = changesets.find(
:first, # create a new changeset....
:conditions => {
:committed_on => tmp_time - time_delta .. tmp_time + time_delta,
:committer => author_utf8,
:comments => cmt
}
)
# create a new changeset....
unless cs unless cs
# we use a temporaray revision number here (just for inserting) # we use a temporaray revision number here (just for inserting)
# later on, we calculate a continous positive number # later on, we calculate a continous positive number
tmp_time2 = tmp_time.clone.gmtime latest = changesets.find(:first, :order => 'id DESC')
branch = revision.paths[0][:branch] cs = Changeset.create(:repository => self,
scmid = branch + "-" + tmp_time2.strftime("%Y%m%d-%H%M%S") :revision => "_#{tmp_rev_num}",
cs = Changeset.create(:repository => self, :committer => revision.author,
:revision => "tmp#{tmp_rev_num}", :committed_on => revision.time,
:scmid => scmid, :comments => revision.message)
:committer => revision.author,
:committed_on => tmp_time,
:comments => revision.message)
tmp_rev_num += 1 tmp_rev_num += 1
end end
# convert CVS-File-States to internal Action-abbrevations
# default action is (M)odified #convert CVS-File-States to internal Action-abbrevations
action = "M" #default action is (M)odified
if revision.paths[0][:action] == "Exp" && revision.paths[0][:revision] == "1.1" action="M"
action = "A" # add-action always at first revision (= 1.1) if revision.paths[0][:action]=="Exp" && revision.paths[0][:revision]=="1.1"
elsif revision.paths[0][:action] == "dead" action="A" #add-action always at first revision (= 1.1)
action = "D" # dead-state is similar to Delete elsif revision.paths[0][:action]=="dead"
action="D" #dead-state is similar to Delete
end end
Change.create(
:changeset => cs, Change.create(:changeset => cs,
:action => action, :action => action,
:path => scm.with_leading_slash(revision.paths[0][:path]), :path => scm.with_leading_slash(revision.paths[0][:path]),
:revision => revision.paths[0][:revision], :revision => revision.paths[0][:revision],
:branch => revision.paths[0][:branch] :branch => revision.paths[0][:branch]
) )
end end
end end
# Renumber new changesets in chronological order # Renumber new changesets in chronological order
changesets.find( changesets.find(:all, :order => 'committed_on ASC, id ASC', :conditions => "revision LIKE '_%'").each do |changeset|
:all,
:order => 'committed_on ASC, id ASC',
:conditions => "revision LIKE 'tmp%'"
).each do |changeset|
changeset.update_attribute :revision, next_revision_number changeset.update_attribute :revision, next_revision_number
end end
end # transaction end # transaction
@current_revision_number = nil
end end
private private
# Returns the next revision number to assign to a CVS changeset # Returns the next revision number to assign to a CVS changeset
def next_revision_number def next_revision_number
# Need to retrieve existing revision numbers to sort them as integers # Need to retrieve existing revision numbers to sort them as integers
sql = "SELECT revision FROM #{Changeset.table_name} " @current_revision_number ||= (connection.select_values("SELECT revision FROM #{Changeset.table_name} WHERE repository_id = #{id} AND revision NOT LIKE '_%'").collect(&:to_i).max || 0)
sql << "WHERE repository_id = #{id} AND revision NOT LIKE 'tmp%'"
@current_revision_number ||= (connection.select_values(sql).collect(&:to_i).max || 0)
@current_revision_number += 1 @current_revision_number += 1
end end
end end
+25 -42
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -18,62 +18,44 @@
require 'redmine/scm/adapters/darcs_adapter' require 'redmine/scm/adapters/darcs_adapter'
class Repository::Darcs < Repository class Repository::Darcs < Repository
validates_presence_of :url, :log_encoding validates_presence_of :url
def self.human_attribute_name(attribute_key_name) def scm_adapter
attr_name = attribute_key_name
if attr_name == "url"
attr_name = "path_to_repository"
end
super(attr_name)
end
def self.scm_adapter_class
Redmine::Scm::Adapters::DarcsAdapter Redmine::Scm::Adapters::DarcsAdapter
end end
def self.scm_name def self.scm_name
'Darcs' 'Darcs'
end end
def supports_directory_revisions?
true
end
def entry(path=nil, identifier=nil) def entry(path=nil, identifier=nil)
patch = identifier.nil? ? nil : changesets.find_by_revision(identifier) patch = identifier.nil? ? nil : changesets.find_by_revision(identifier)
scm.entry(path, patch.nil? ? nil : patch.scmid) scm.entry(path, patch.nil? ? nil : patch.scmid)
end end
def entries(path=nil, identifier=nil) def entries(path=nil, identifier=nil)
patch = nil patch = identifier.nil? ? nil : changesets.find_by_revision(identifier)
if ! identifier.nil?
patch = changesets.find_by_revision(identifier)
return nil if patch.nil?
end
entries = scm.entries(path, patch.nil? ? nil : patch.scmid) entries = scm.entries(path, patch.nil? ? nil : patch.scmid)
if entries if entries
entries.each do |entry| entries.each do |entry|
# Search the DB for the entry's last change # Search the DB for the entry's last change
if entry.lastrev && !entry.lastrev.scmid.blank? changeset = changesets.find_by_scmid(entry.lastrev.scmid) if entry.lastrev && !entry.lastrev.scmid.blank?
changeset = changesets.find_by_scmid(entry.lastrev.scmid)
end
if changeset if changeset
entry.lastrev.identifier = changeset.revision entry.lastrev.identifier = changeset.revision
entry.lastrev.name = changeset.revision entry.lastrev.name = changeset.revision
entry.lastrev.time = changeset.committed_on entry.lastrev.time = changeset.committed_on
entry.lastrev.author = changeset.committer entry.lastrev.author = changeset.committer
end end
end end
end end
entries entries
end end
def cat(path, identifier=nil) def cat(path, identifier=nil)
patch = identifier.nil? ? nil : changesets.find_by_revision(identifier.to_s) patch = identifier.nil? ? nil : changesets.find_by_revision(identifier.to_s)
scm.cat(path, patch.nil? ? nil : patch.scmid) scm.cat(path, patch.nil? ? nil : patch.scmid)
end end
def diff(path, rev, rev_to) def diff(path, rev, rev_to)
patch_from = changesets.find_by_revision(rev) patch_from = changesets.find_by_revision(rev)
return nil if patch_from.nil? return nil if patch_from.nil?
@@ -83,24 +65,25 @@ class Repository::Darcs < Repository
end end
patch_from ? scm.diff(path, patch_from.scmid, patch_to ? patch_to.scmid : nil) : nil patch_from ? scm.diff(path, patch_from.scmid, patch_to ? patch_to.scmid : nil) : nil
end end
def fetch_changesets def fetch_changesets
scm_info = scm.info scm_info = scm.info
if scm_info if scm_info
db_last_id = latest_changeset ? latest_changeset.scmid : nil db_last_id = latest_changeset ? latest_changeset.scmid : nil
next_rev = latest_changeset ? latest_changeset.revision.to_i + 1 : 1 next_rev = latest_changeset ? latest_changeset.revision.to_i + 1 : 1
# latest revision in the repository # latest revision in the repository
scm_revision = scm_info.lastrev.scmid scm_revision = scm_info.lastrev.scmid
unless changesets.find_by_scmid(scm_revision) unless changesets.find_by_scmid(scm_revision)
revisions = scm.revisions('', db_last_id, nil, :with_path => true) revisions = scm.revisions('', db_last_id, nil, :with_path => true)
transaction do transaction do
revisions.reverse_each do |revision| revisions.reverse_each do |revision|
changeset = Changeset.create(:repository => self, changeset = Changeset.create(:repository => self,
:revision => next_rev, :revision => next_rev,
:scmid => revision.scmid, :scmid => revision.scmid,
:committer => revision.author, :committer => revision.author,
:committed_on => revision.time, :committed_on => revision.time,
:comments => revision.message) :comments => revision.message)
revision.paths.each do |change| revision.paths.each do |change|
changeset.create_change(change) changeset.create_change(change)
end end
+8 -19
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# FileSystem adapter # FileSystem adapter
# File written by Paul Rivier, at Demotera. # File written by Paul Rivier, at Demotera.
@@ -8,12 +8,12 @@
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -24,26 +24,14 @@ class Repository::Filesystem < Repository
attr_protected :root_url attr_protected :root_url
validates_presence_of :url validates_presence_of :url
def self.human_attribute_name(attribute_key_name) def scm_adapter
attr_name = attribute_key_name
if attr_name == "url"
attr_name = "root_directory"
end
super(attr_name)
end
def self.scm_adapter_class
Redmine::Scm::Adapters::FilesystemAdapter Redmine::Scm::Adapters::FilesystemAdapter
end end
def self.scm_name def self.scm_name
'Filesystem' 'Filesystem'
end end
def supports_all_revisions?
false
end
def entries(path=nil, identifier=nil) def entries(path=nil, identifier=nil)
scm.entries(path, identifier) scm.entries(path, identifier)
end end
@@ -51,4 +39,5 @@ class Repository::Filesystem < Repository
def fetch_changesets def fetch_changesets
nil nil
end end
end end
+30 -130
View File
@@ -1,17 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# Copyright (C) 2007 Patrick Aljord patcito@ŋmail.com # Copyright (C) 2007 Patrick Aljord patcito@ŋmail.com
#
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -22,41 +21,14 @@ class Repository::Git < Repository
attr_protected :root_url attr_protected :root_url
validates_presence_of :url validates_presence_of :url
def self.human_attribute_name(attribute_key_name) def scm_adapter
attr_name = attribute_key_name
if attr_name == "url"
attr_name = "path_to_repository"
end
super(attr_name)
end
def self.scm_adapter_class
Redmine::Scm::Adapters::GitAdapter Redmine::Scm::Adapters::GitAdapter
end end
def self.scm_name def self.scm_name
'Git' 'Git'
end end
def report_last_commit
extra_report_last_commit
end
def extra_report_last_commit
return false if extra_info.nil?
v = extra_info["extra_report_last_commit"]
return false if v.nil?
v.to_s != '0'
end
def supports_directory_revisions?
true
end
def repo_log_encoding
'UTF-8'
end
# Returns the identifier for the given git changeset # Returns the identifier for the given git changeset
def self.changeset_identifier(changeset) def self.changeset_identifier(changeset)
changeset.scmid changeset.scmid
@@ -75,114 +47,42 @@ class Repository::Git < Repository
scm.tags scm.tags
end end
def default_branch # With SCM's that have a sequential commit numbering, redmine is able to be
scm.default_branch # clever and only fetch changesets going forward from the most recent one
end # it knows about. However, with git, you never know if people have merged
# commits into the middle of the repository history, so we should parse
def find_changeset_by_name(name) # the entire log. Since it's way too slow for large repositories, we only
return nil if name.nil? || name.empty? # parse 1 week before the last known commit.
e = changesets.find(:first, :conditions => ['revision = ?', name.to_s])
return e if e
changesets.find(:first, :conditions => ['scmid LIKE ?', "#{name}%"])
end
def entries(path=nil, identifier=nil)
scm.entries(path,
identifier,
options = {:report_last_commit => extra_report_last_commit})
end
# With SCMs that have a sequential commit numbering,
# such as Subversion and Mercurial,
# Redmine is able to be clever and only fetch changesets
# going forward from the most recent one it knows about.
#
# However, Git does not have a sequential commit numbering.
#
# In order to fetch only new adding revisions,
# Redmine needs to parse revisions per branch.
# Branch "last_scmid" is for this requirement.
#
# In Git and Mercurial, revisions are not in date order.
# Redmine Mercurial fixed issues.
# * Redmine Takes Too Long On Large Mercurial Repository
# http://www.redmine.org/issues/3449
# * Sorting for changesets might go wrong on Mercurial repos
# http://www.redmine.org/issues/3567
#
# Database revision column is text, so Redmine can not sort by revision.
# Mercurial has revision number, and revision number guarantees revision order.
# Redmine Mercurial model stored revisions ordered by database id to database.
# So, Redmine Mercurial model can use correct ordering revisions.
#
# Redmine Mercurial adapter uses "hg log -r 0:tip --limit 10"
# to get limited revisions from old to new.
# But, Git 1.7.3.4 does not support --reverse with -n or --skip.
#
# The repository can still be fully reloaded by calling #clear_changesets # The repository can still be fully reloaded by calling #clear_changesets
# before fetching changesets (eg. for offline resync) # before fetching changesets (eg. for offline resync)
def fetch_changesets def fetch_changesets
scm_brs = branches c = changesets.find(:first, :order => 'committed_on DESC')
return if scm_brs.nil? || scm_brs.empty? since = (c ? c.committed_on - 7.days : nil)
h1 = extra_info || {}
h = h1.dup
h["branches"] ||= {}
h["db_consistent"] ||= {}
if changesets.count == 0
h["db_consistent"]["ordering"] = 1
merge_extra_info(h)
self.save
elsif ! h["db_consistent"].has_key?("ordering")
h["db_consistent"]["ordering"] = 0
merge_extra_info(h)
self.save
end
scm_brs.each do |br|
from_scmid = nil
from_scmid = h["branches"][br]["last_scmid"] if h["branches"][br]
h["branches"][br] ||= {}
scm.revisions('', from_scmid, br, {:reverse => true}) do |rev|
db_rev = find_changeset_by_name(rev.revision)
transaction do
if db_rev.nil?
save_revision(rev)
end
h["branches"][br]["last_scmid"] = rev.scmid
merge_extra_info(h)
self.save
end
end
end
end
def save_revision(rev) revisions = scm.revisions('', nil, nil, :all => true, :since => since)
changeset = Changeset.new( return if revisions.nil? || revisions.empty?
:repository => self,
:revision => rev.identifier, recent_changesets = changesets.find(:all, :conditions => ['committed_on >= ?', since])
:scmid => rev.scmid,
:committer => rev.author, # Clean out revisions that are no longer in git
:committed_on => rev.time, recent_changesets.each {|c| c.destroy unless revisions.detect {|r| r.scmid.to_s == c.scmid.to_s }}
:comments => rev.message
) # Subtract revisions that redmine already knows about
if changeset.save recent_revisions = recent_changesets.map{|c| c.scmid}
rev.paths.each do |file| revisions.reject!{|r| recent_revisions.include?(r.scmid)}
Change.create(
:changeset => changeset, # Save the remaining ones to the database
:action => file[:action], revisions.each{|r| r.save(self)} unless revisions.nil?
:path => file[:path])
end
end
end end
private :save_revision
def latest_changesets(path,rev,limit=10) def latest_changesets(path,rev,limit=10)
revisions = scm.revisions(path, nil, rev, :limit => limit, :all => false) revisions = scm.revisions(path, nil, rev, :limit => limit, :all => false)
return [] if revisions.nil? || revisions.empty? return [] if revisions.nil? || revisions.empty?
changesets.find( changesets.find(
:all, :all,
:conditions => [ :conditions => [
"scmid IN (?)", "scmid IN (?)",
revisions.map!{|c| c.scmid} revisions.map!{|c| c.scmid}
], ],
:order => 'committed_on DESC' :order => 'committed_on DESC'
+73 -115
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -24,124 +24,82 @@ class Repository::Mercurial < Repository
attr_protected :root_url attr_protected :root_url
validates_presence_of :url validates_presence_of :url
FETCH_AT_ONCE = 100 # number of changesets to fetch at once def scm_adapter
def self.human_attribute_name(attribute_key_name)
attr_name = attribute_key_name
if attr_name == "url"
attr_name = "path_to_repository"
end
super(attr_name)
end
def self.scm_adapter_class
Redmine::Scm::Adapters::MercurialAdapter Redmine::Scm::Adapters::MercurialAdapter
end end
def self.scm_name def self.scm_name
'Mercurial' 'Mercurial'
end end
def supports_directory_revisions? def entries(path=nil, identifier=nil)
true entries=scm.entries(path, identifier)
end if entries
entries.each do |entry|
def repo_log_encoding next unless entry.is_file?
'UTF-8' # Set the filesize unless browsing a specific revision
end if identifier.nil?
full_path = File.join(root_url, entry.path)
# Returns the readable identifier for the given mercurial changeset entry.size = File.stat(full_path).size if File.file?(full_path)
def self.format_changeset_identifier(changeset) end
"#{changeset.revision}:#{changeset.scmid}" # Search the DB for the entry's last change
end change = changes.find(:first, :conditions => ["path = ?", scm.with_leading_slash(entry.path)], :order => "#{Changeset.table_name}.committed_on DESC")
if change
# Returns the identifier for the given Mercurial changeset entry.lastrev.identifier = change.changeset.revision
def self.changeset_identifier(changeset) entry.lastrev.name = change.changeset.revision
changeset.scmid entry.lastrev.author = change.changeset.committer
end entry.lastrev.revision = change.revision
end
def diff_format_revisions(cs, cs_to, sep=':') end
super(cs, cs_to, ' ') end
end entries
end
# Finds and returns a revision with a number or the beginning of a hash
def find_changeset_by_name(name) # Returns the latest changesets for +path+; sorted by revision number
return nil if name.nil? || name.empty? def latest_changesets(path, rev, limit=10)
if /[^\d]/ =~ name or name.to_s.size > 8 if path.blank?
e = changesets.find(:first, :conditions => ['scmid = ?', name.to_s]) changesets.find(:all, :include => :user, :limit => limit, :order => "id DESC")
else else
e = changesets.find(:first, :conditions => ['revision = ?', name.to_s]) changes.find(:all, :include => {:changeset => :user},
end :conditions => ["path = ?", path.with_leading_slash],
return e if e :order => "#{Changeset.table_name}.id DESC",
changesets.find(:first, :conditions => ['scmid LIKE ?', "#{name}%"]) # last ditch :limit => limit).collect(&:changeset)
end end
end
# Returns the latest changesets for +path+; sorted by revision number
# def fetch_changesets
# Because :order => 'id DESC' is defined at 'has_many', scm_info = scm.info
# there is no need to set 'order'. if scm_info
# But, MySQL test fails. # latest revision found in database
# Sqlite3 and PostgreSQL pass. db_revision = latest_changeset ? latest_changeset.revision.to_i : -1
# Is this MySQL bug? # latest revision in the repository
def latest_changesets(path, rev, limit=10) latest_revision = scm_info.lastrev
changesets.find(:all, :include => :user, return if latest_revision.nil?
:conditions => latest_changesets_cond(path, rev, limit), scm_revision = latest_revision.identifier.to_i
:limit => limit, :order => "#{Changeset.table_name}.id DESC") if db_revision < scm_revision
end logger.debug "Fetching changesets for repository #{url}" if logger && logger.debug?
identifier_from = db_revision + 1
def latest_changesets_cond(path, rev, limit) while (identifier_from <= scm_revision)
cond, args = [], [] # loads changesets by batches of 100
if scm.branchmap.member? rev identifier_to = [identifier_from + 99, scm_revision].min
# Mercurial named branch is *stable* in each revision. revisions = scm.revisions('', identifier_from, identifier_to, :with_paths => true)
# So, named branch can be stored in database. transaction do
# Mercurial provides *bookmark* which is equivalent with git branch. revisions.each do |revision|
# But, bookmark is not implemented. changeset = Changeset.create(:repository => self,
cond << "#{Changeset.table_name}.scmid IN (?)" :revision => revision.identifier,
# Revisions in root directory and sub directory are not equal. :scmid => revision.scmid,
# So, in order to get correct limit, we need to get all revisions. :committer => revision.author,
# But, it is very heavy. :committed_on => revision.time,
# Mercurial does not treat direcotry. :comments => revision.message)
# So, "hg log DIR" is very heavy.
branch_limit = path.blank? ? limit : ( limit * 5 ) revision.paths.each do |change|
args << scm.nodes_in_branch(rev, :limit => branch_limit) changeset.create_change(change)
elsif last = rev ? find_changeset_by_name(scm.tagmap[rev] || rev) : nil end
cond << "#{Changeset.table_name}.id <= ?" end
args << last.id end unless revisions.nil?
end identifier_from = identifier_to + 1
unless path.blank?
cond << "EXISTS (SELECT * FROM #{Change.table_name}
WHERE #{Change.table_name}.changeset_id = #{Changeset.table_name}.id
AND (#{Change.table_name}.path = ?
OR #{Change.table_name}.path LIKE ? ESCAPE ?))"
args << path.with_leading_slash
args << "#{path.with_leading_slash.gsub(/[%_\\]/) { |s| "\\#{s}" }}/%" << '\\'
end
[cond.join(' AND '), *args] unless cond.empty?
end
private :latest_changesets_cond
def fetch_changesets
return if scm.info.nil?
scm_rev = scm.info.lastrev.revision.to_i
db_rev = latest_changeset ? latest_changeset.revision.to_i : -1
return unless db_rev < scm_rev # already up-to-date
logger.debug "Fetching changesets for repository #{url}" if logger
(db_rev + 1).step(scm_rev, FETCH_AT_ONCE) do |i|
transaction do
scm.each_revision('', i, [i + FETCH_AT_ONCE - 1, scm_rev].min) do |re|
cs = Changeset.create(:repository => self,
:revision => re.revision,
:scmid => re.scmid,
:committer => re.author,
:committed_on => re.time,
:comments => re.message)
re.paths.each { |e| cs.create_change(e) }
end end
end end
end end
self
end end
end end
+15 -23
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -22,32 +22,24 @@ class Repository::Subversion < Repository
validates_presence_of :url validates_presence_of :url
validates_format_of :url, :with => /^(http|https|svn(\+[^\s:\/\\]+)?|file):\/\/.+/i validates_format_of :url, :with => /^(http|https|svn(\+[^\s:\/\\]+)?|file):\/\/.+/i
def self.scm_adapter_class def scm_adapter
Redmine::Scm::Adapters::SubversionAdapter Redmine::Scm::Adapters::SubversionAdapter
end end
def self.scm_name def self.scm_name
'Subversion' 'Subversion'
end end
def supports_directory_revisions?
true
end
def repo_log_encoding
'UTF-8'
end
def latest_changesets(path, rev, limit=10) def latest_changesets(path, rev, limit=10)
revisions = scm.revisions(path, rev, nil, :limit => limit) revisions = scm.revisions(path, rev, nil, :limit => limit)
revisions ? changesets.find_all_by_revision(revisions.collect(&:identifier), :order => "committed_on DESC", :include => :user) : [] revisions ? changesets.find_all_by_revision(revisions.collect(&:identifier), :order => "committed_on DESC", :include => :user) : []
end end
# Returns a path relative to the url of the repository # Returns a path relative to the url of the repository
def relative_path(path) def relative_path(path)
path.gsub(Regexp.new("^\/?#{Regexp.escape(relative_url)}"), '') path.gsub(Regexp.new("^\/?#{Regexp.escape(relative_url)}"), '')
end end
def fetch_changesets def fetch_changesets
scm_info = scm.info scm_info = scm.info
if scm_info if scm_info
@@ -64,12 +56,12 @@ class Repository::Subversion < Repository
revisions = scm.revisions('', identifier_to, identifier_from, :with_paths => true) revisions = scm.revisions('', identifier_to, identifier_from, :with_paths => true)
revisions.reverse_each do |revision| revisions.reverse_each do |revision|
transaction do transaction do
changeset = Changeset.create(:repository => self, changeset = Changeset.create(:repository => self,
:revision => revision.identifier, :revision => revision.identifier,
:committer => revision.author, :committer => revision.author,
:committed_on => revision.time, :committed_on => revision.time,
:comments => revision.message) :comments => revision.message)
revision.paths.each do |change| revision.paths.each do |change|
changeset.create_change(change) changeset.create_change(change)
end unless changeset.new_record? end unless changeset.new_record?
@@ -80,9 +72,9 @@ class Repository::Subversion < Repository
end end
end end
end end
private private
# Returns the relative url of the repository # Returns the relative url of the repository
# Eg: root_url = file:///var/svn/foo # Eg: root_url = file:///var/svn/foo
# url = file:///var/svn/foo/bar # url = file:///var/svn/foo/bar
+4 -20
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -19,12 +19,6 @@ class Role < ActiveRecord::Base
# Built-in roles # Built-in roles
BUILTIN_NON_MEMBER = 1 BUILTIN_NON_MEMBER = 1
BUILTIN_ANONYMOUS = 2 BUILTIN_ANONYMOUS = 2
ISSUES_VISIBILITY_OPTIONS = [
['all', :label_issues_visibility_all],
['default', :label_issues_visibility_public],
['own', :label_issues_visibility_own]
]
named_scope :givable, { :conditions => "builtin = 0", :order => 'position' } named_scope :givable, { :conditions => "builtin = 0", :order => 'position' }
named_scope :builtin, lambda { |*args| named_scope :builtin, lambda { |*args|
@@ -49,10 +43,8 @@ class Role < ActiveRecord::Base
validates_presence_of :name validates_presence_of :name
validates_uniqueness_of :name validates_uniqueness_of :name
validates_length_of :name, :maximum => 30 validates_length_of :name, :maximum => 30
validates_inclusion_of :issues_visibility, validates_format_of :name, :with => /^[\w\s\'\-]*$/i
:in => ISSUES_VISIBILITY_OPTIONS.collect(&:first),
:if => lambda {|role| role.respond_to?(:issues_visibility)}
def permissions def permissions
read_attribute(:permissions) || [] read_attribute(:permissions) || []
end end
@@ -93,14 +85,6 @@ class Role < ActiveRecord::Base
name name
end end
def name
case builtin
when 1; l(:label_role_non_member, :default => read_attribute(:name))
when 2; l(:label_role_anonymous, :default => read_attribute(:name))
else; read_attribute(:name)
end
end
# Return true if the role is a builtin role # Return true if the role is a builtin role
def builtin? def builtin?
self.builtin != 0 self.builtin != 0
+20 -21
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -28,12 +28,12 @@ class Setting < ActiveRecord::Base
'%b %d, %Y', '%b %d, %Y',
'%B %d, %Y' '%B %d, %Y'
] ]
TIME_FORMATS = [ TIME_FORMATS = [
'%H:%M', '%H:%M',
'%I:%M %p' '%I:%M %p'
] ]
ENCODINGS = %w(US-ASCII ENCODINGS = %w(US-ASCII
windows-1250 windows-1250
windows-1251 windows-1251
@@ -65,7 +65,6 @@ class Setting < ActiveRecord::Base
UTF-16LE UTF-16LE
EUC-JP EUC-JP
Shift_JIS Shift_JIS
CP932
GB18030 GB18030
GBK GBK
ISCII91 ISCII91
@@ -73,22 +72,22 @@ class Setting < ActiveRecord::Base
Big5 Big5
Big5-HKSCS Big5-HKSCS
TIS-620) TIS-620)
cattr_accessor :available_settings cattr_accessor :available_settings
@@available_settings = YAML::load(File.open("#{RAILS_ROOT}/config/settings.yml")) @@available_settings = YAML::load(File.open("#{RAILS_ROOT}/config/settings.yml"))
Redmine::Plugin.all.each do |plugin| Redmine::Plugin.all.each do |plugin|
next unless plugin.settings next unless plugin.settings
@@available_settings["plugin_#{plugin.id}"] = {'default' => plugin.settings[:default], 'serialized' => true} @@available_settings["plugin_#{plugin.id}"] = {'default' => plugin.settings[:default], 'serialized' => true}
end end
validates_uniqueness_of :name validates_uniqueness_of :name
validates_inclusion_of :name, :in => @@available_settings.keys validates_inclusion_of :name, :in => @@available_settings.keys
validates_numericality_of :value, :only_integer => true, :if => Proc.new { |setting| @@available_settings[setting.name]['format'] == 'int' } validates_numericality_of :value, :only_integer => true, :if => Proc.new { |setting| @@available_settings[setting.name]['format'] == 'int' }
# Hash used to cache setting values # Hash used to cache setting values
@cached_settings = {} @cached_settings = {}
@cached_cleared_on = Time.now @cached_cleared_on = Time.now
def value def value
v = read_attribute(:value) v = read_attribute(:value)
# Unserialize serialized settings # Unserialize serialized settings
@@ -96,18 +95,18 @@ class Setting < ActiveRecord::Base
v = v.to_sym if @@available_settings[name]['format'] == 'symbol' && !v.blank? v = v.to_sym if @@available_settings[name]['format'] == 'symbol' && !v.blank?
v v
end end
def value=(v) def value=(v)
v = v.to_yaml if v && @@available_settings[name] && @@available_settings[name]['serialized'] v = v.to_yaml if v && @@available_settings[name] && @@available_settings[name]['serialized']
write_attribute(:value, v.to_s) write_attribute(:value, v.to_s)
end end
# Returns the value of the setting named name # Returns the value of the setting named name
def self.[](name) def self.[](name)
v = @cached_settings[name] v = @cached_settings[name]
v ? v : (@cached_settings[name] = find_or_default(name).value) v ? v : (@cached_settings[name] = find_or_default(name).value)
end end
def self.[]=(name, v) def self.[]=(name, v)
setting = find_or_default(name) setting = find_or_default(name)
setting.value = (v ? v : "") setting.value = (v ? v : "")
@@ -115,7 +114,7 @@ class Setting < ActiveRecord::Base
setting.save setting.save
setting.value setting.value
end end
# Defines getter and setter for each setting # Defines getter and setter for each setting
# Then setting values can be read using: Setting.some_setting_name # Then setting values can be read using: Setting.some_setting_name
# or set using Setting.some_setting_name = "some value" # or set using Setting.some_setting_name = "some value"
@@ -135,16 +134,16 @@ class Setting < ActiveRecord::Base
END_SRC END_SRC
class_eval src, __FILE__, __LINE__ class_eval src, __FILE__, __LINE__
end end
# Helper that returns an array based on per_page_options setting # Helper that returns an array based on per_page_options setting
def self.per_page_options_array def self.per_page_options_array
per_page_options.split(%r{[\s,]}).collect(&:to_i).select {|n| n > 0}.sort per_page_options.split(%r{[\s,]}).collect(&:to_i).select {|n| n > 0}.sort
end end
def self.openid? def self.openid?
Object.const_defined?(:OpenID) && self[:openid].to_i > 0 Object.const_defined?(:OpenID) && self[:openid].to_i > 0
end end
# Checks if settings have changed since the values were read # Checks if settings have changed since the values were read
# and clears the cache hash if it's the case # and clears the cache hash if it's the case
# Called once per request # Called once per request
@@ -156,13 +155,13 @@ class Setting < ActiveRecord::Base
logger.info "Settings cache cleared." if logger logger.info "Settings cache cleared." if logger
end end
end end
private private
# Returns the Setting instance for the setting named name # Returns the Setting instance for the setting named name
# (record found in database or new record with default value) # (record found in database or new record with default value)
def self.find_or_default(name) def self.find_or_default(name)
name = name.to_s name = name.to_s
raise "There's no setting named #{name}" unless @@available_settings.has_key?(name) raise "There's no setting named #{name}" unless @@available_settings.has_key?(name)
setting = find_by_name(name) setting = find_by_name(name)
setting ||= new(:name => name, :value => @@available_settings[name]['default']) if @@available_settings.has_key? name setting ||= new(:name => name, :value => @@available_settings[name]['default']) if @@available_settings.has_key? name
end end
+12 -19
View File
@@ -1,16 +1,16 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2008 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -22,7 +22,7 @@ class TimeEntry < ActiveRecord::Base
belongs_to :issue belongs_to :issue
belongs_to :user belongs_to :user
belongs_to :activity, :class_name => 'TimeEntryActivity', :foreign_key => 'activity_id' belongs_to :activity, :class_name => 'TimeEntryActivity', :foreign_key => 'activity_id'
attr_protected :project_id, :user_id, :tyear, :tmonth, :tweek attr_protected :project_id, :user_id, :tyear, :tmonth, :tweek
acts_as_customizable acts_as_customizable
@@ -33,17 +33,12 @@ class TimeEntry < ActiveRecord::Base
acts_as_activity_provider :timestamp => "#{table_name}.created_on", acts_as_activity_provider :timestamp => "#{table_name}.created_on",
:author_key => :user_id, :author_key => :user_id,
:find_options => {:include => :project} :find_options => {:include => :project}
validates_presence_of :user_id, :activity_id, :project_id, :hours, :spent_on validates_presence_of :user_id, :activity_id, :project_id, :hours, :spent_on
validates_numericality_of :hours, :allow_nil => true, :message => :invalid validates_numericality_of :hours, :allow_nil => true, :message => :invalid
validates_length_of :comments, :maximum => 255, :allow_nil => true validates_length_of :comments, :maximum => 255, :allow_nil => true
named_scope :visible, lambda {|*args| {
:include => :project,
:conditions => Project.allowed_to_condition(args.shift || User.current, :view_time_entries, *args)
}}
def after_initialize def after_initialize
if new_record? && self.activity.nil? if new_record? && self.activity.nil?
if default_activity = TimeEntryActivity.default if default_activity = TimeEntryActivity.default
@@ -52,21 +47,21 @@ class TimeEntry < ActiveRecord::Base
self.hours = nil if hours == 0 self.hours = nil if hours == 0
end end
end end
def before_validation def before_validation
self.project = issue.project if issue && project.nil? self.project = issue.project if issue && project.nil?
end end
def validate def validate
errors.add :hours, :invalid if hours && (hours < 0 || hours >= 1000) errors.add :hours, :invalid if hours && (hours < 0 || hours >= 1000)
errors.add :project_id, :invalid if project.nil? errors.add :project_id, :invalid if project.nil?
errors.add :issue_id, :invalid if (issue_id && !issue) || (issue && project!=issue.project) errors.add :issue_id, :invalid if (issue_id && !issue) || (issue && project!=issue.project)
end end
def hours=(h) def hours=(h)
write_attribute :hours, (h.is_a?(String) ? (h.to_hours || h) : h) write_attribute :hours, (h.is_a?(String) ? (h.to_hours || h) : h)
end end
# tyear, tmonth, tweek assigned where setting spent_on attributes # tyear, tmonth, tweek assigned where setting spent_on attributes
# these attributes make time aggregations easier # these attributes make time aggregations easier
def spent_on=(date) def spent_on=(date)
@@ -78,15 +73,13 @@ class TimeEntry < ActiveRecord::Base
self.tmonth = spent_on ? spent_on.month : nil self.tmonth = spent_on ? spent_on.month : nil
self.tweek = spent_on ? Date.civil(spent_on.year, spent_on.month, spent_on.day).cweek : nil self.tweek = spent_on ? Date.civil(spent_on.year, spent_on.month, spent_on.day).cweek : nil
end end
# Returns true if the time entry can be edited by usr, otherwise false # Returns true if the time entry can be edited by usr, otherwise false
def editable_by?(usr) def editable_by?(usr)
(usr == user && usr.allowed_to?(:edit_own_time_entries, project)) || usr.allowed_to?(:edit_time_entries, project) (usr == user && usr.allowed_to?(:edit_own_time_entries, project)) || usr.allowed_to?(:edit_time_entries, project)
end end
# TODO: remove this method in 1.3.0
def self.visible_by(usr) def self.visible_by(usr)
ActiveSupport::Deprecation.warn "TimeEntry.visible_by is deprecated and will be removed in Redmine 1.3.0. Use the visible scope instead."
with_scope(:find => { :conditions => Project.allowed_to_condition(usr, :view_time_entries) }) do with_scope(:find => { :conditions => Project.allowed_to_condition(usr, :view_time_entries) }) do
yield yield
end end
+1 -2
View File
@@ -31,9 +31,8 @@ class Tracker < ActiveRecord::Base
validates_presence_of :name validates_presence_of :name
validates_uniqueness_of :name validates_uniqueness_of :name
validates_length_of :name, :maximum => 30 validates_length_of :name, :maximum => 30
validates_format_of :name, :with => /^[\w\s\'\-]*$/i
named_scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
def to_s; name end def to_s; name end
def <=>(tracker) def <=>(tracker)
+15 -110
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2009 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -48,8 +48,8 @@ class User < Principal
has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify
has_many :changesets, :dependent => :nullify has_many :changesets, :dependent => :nullify
has_one :preference, :dependent => :destroy, :class_name => 'UserPreference' has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'" has_one :rss_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='feeds'"
has_one :api_token, :class_name => 'Token', :conditions => "action='api'" has_one :api_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='api'"
belongs_to :auth_source belongs_to :auth_source
# Active non-anonymous users scope # Active non-anonymous users scope
@@ -68,23 +68,13 @@ class User < Principal
# Login must contain lettres, numbers, underscores only # Login must contain lettres, numbers, underscores only
validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
validates_length_of :login, :maximum => 30 validates_length_of :login, :maximum => 30
validates_format_of :firstname, :lastname, :with => /^[\w\s\'\-\.]*$/i
validates_length_of :firstname, :lastname, :maximum => 30 validates_length_of :firstname, :lastname, :maximum => 30
validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_nil => true validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_nil => true
validates_length_of :mail, :maximum => 60, :allow_nil => true validates_length_of :mail, :maximum => 60, :allow_nil => true
validates_confirmation_of :password, :allow_nil => true validates_confirmation_of :password, :allow_nil => true
validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
before_destroy :remove_references_before_destroy
named_scope :in_group, lambda {|group|
group_id = group.is_a?(Group) ? group.id : group.to_i
{ :conditions => ["#{User.table_name}.id IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id] }
}
named_scope :not_in_group, lambda {|group|
group_id = group.is_a?(Group) ? group.id : group.to_i
{ :conditions => ["#{User.table_name}.id NOT IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id] }
}
def before_create def before_create
self.mail_notification = Setting.default_notification_option if self.mail_notification.blank? self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
true true
@@ -92,14 +82,11 @@ class User < Principal
def before_save def before_save
# update hashed_password if password was set # update hashed_password if password was set
if self.password && self.auth_source_id.blank? self.hashed_password = User.hash_password(self.password) if self.password && self.auth_source_id.blank?
salt_password(password)
end
end end
def reload(*args) def reload(*args)
@name = nil @name = nil
@projects_by_role = nil
super super
end end
@@ -133,7 +120,7 @@ class User < Principal
return nil unless user.auth_source.authenticate(login, password) return nil unless user.auth_source.authenticate(login, password)
else else
# authentication with local password # authentication with local password
return nil unless user.check_password?(password) return nil unless User.hash_password(password) == user.hashed_password
end end
else else
# user is not yet registered, try to authenticate with available sources # user is not yet registered, try to authenticate with available sources
@@ -212,21 +199,13 @@ class User < Principal
update_attribute(:status, STATUS_LOCKED) update_attribute(:status, STATUS_LOCKED)
end end
# Returns true if +clear_password+ is the correct user's password, otherwise false
def check_password?(clear_password) def check_password?(clear_password)
if auth_source_id.present? if auth_source_id.present?
auth_source.authenticate(self.login, clear_password) auth_source.authenticate(self.login, clear_password)
else else
User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password User.hash_password(clear_password) == self.hashed_password
end end
end end
# Generates a random salt and computes hashed_password for +clear_password+
# The hashed password is stored in the following form: SHA1(salt + SHA1(password))
def salt_password(clear_password)
self.salt = User.generate_salt
self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
end
# Does the backend storage allow this user to change their password? # Does the backend storage allow this user to change their password?
def change_password_allowed? def change_password_allowed?
@@ -371,33 +350,16 @@ class User < Principal
!roles_for_project(project).detect {|role| role.member?}.nil? !roles_for_project(project).detect {|role| role.member?}.nil?
end end
# Returns a hash of user's projects grouped by roles
def projects_by_role
return @projects_by_role if @projects_by_role
@projects_by_role = Hash.new {|h,k| h[k]=[]}
memberships.each do |membership|
membership.roles.each do |role|
@projects_by_role[role] << membership.project if membership.project
end
end
@projects_by_role.each do |role, projects|
projects.uniq!
end
@projects_by_role
end
# Return true if the user is allowed to do the specified action on a specific context # Return true if the user is allowed to do the specified action on a specific context
# Action can be: # Action can be:
# * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit') # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
# * a permission Symbol (eg. :edit_project) # * a permission Symbol (eg. :edit_project)
# Context can be: # Context can be:
# * a project : returns true if user is allowed to do the specified action on this project # * a project : returns true if user is allowed to do the specified action on this project
# * an array of projects : returns true if user is allowed on every project # * a group of projects : returns true if user is allowed on every project
# * nil with options[:global] set : check if user has at least one role allowed for this action, # * nil with options[:global] set : check if user has at least one role allowed for this action,
# or falls back to Non Member / Anonymous permissions depending if the user is logged # or falls back to Non Member / Anonymous permissions depending if the user is logged
def allowed_to?(action, context, options={}, &block) def allowed_to?(action, context, options={})
if context && context.is_a?(Project) if context && context.is_a?(Project)
# No action allowed on archived projects # No action allowed on archived projects
return false unless context.active? return false unless context.active?
@@ -408,15 +370,12 @@ class User < Principal
roles = roles_for_project(context) roles = roles_for_project(context)
return false unless roles return false unless roles
roles.detect {|role| roles.detect {|role| (context.is_public? || role.member?) && role.allowed_to?(action)}
(context.is_public? || role.member?) &&
role.allowed_to?(action) &&
(block_given? ? yield(role, self) : true)
}
elsif context && context.is_a?(Array) elsif context && context.is_a?(Array)
# Authorize if user is authorized on every element of the array # Authorize if user is authorized on every element of the array
context.map do |project| context.map do |project|
allowed_to?(action, project, options, &block) allowed_to?(action,project,options)
end.inject do |memo,allowed| end.inject do |memo,allowed|
memo && allowed memo && allowed
end end
@@ -426,11 +385,7 @@ class User < Principal
# authorize if user has at least one role that has this permission # authorize if user has at least one role that has this permission
roles = memberships.collect {|m| m.roles}.flatten.uniq roles = memberships.collect {|m| m.roles}.flatten.uniq
roles << (self.logged? ? Role.non_member : Role.anonymous) roles.detect {|r| r.allowed_to?(action)} || (self.logged? ? Role.non_member.allowed_to?(action) : Role.anonymous.allowed_to?(action))
roles.detect {|role|
role.allowed_to?(action) &&
(block_given? ? yield(role, self) : true)
}
else else
false false
end end
@@ -438,8 +393,8 @@ class User < Principal
# Is the user allowed to do the specified action on any project? # Is the user allowed to do the specified action on any project?
# See allowed_to? for the actions and valid options. # See allowed_to? for the actions and valid options.
def allowed_to_globally?(action, options, &block) def allowed_to_globally?(action, options)
allowed_to?(action, nil, options.reverse_merge(:global => true), &block) allowed_to?(action, nil, options.reverse_merge(:global => true))
end end
safe_attributes 'login', safe_attributes 'login',
@@ -517,20 +472,6 @@ class User < Principal
end end
anonymous_user anonymous_user
end end
# Salts all existing unsalted passwords
# It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
# This method is used in the SaltPasswords migration and is to be kept as is
def self.salt_unsalted_passwords!
transaction do
User.find_each(:conditions => "salt IS NULL OR salt = ''") do |user|
next if user.hashed_password.blank?
salt = User.generate_salt
hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
User.update_all("salt = '#{salt}', hashed_password = '#{hashed_password}'", ["id = ?", user.id] )
end
end
end
protected protected
@@ -542,42 +483,11 @@ class User < Principal
end end
private private
# Removes references that are not handled by associations
# Things that are not deleted are reassociated with the anonymous user
def remove_references_before_destroy
return if self.id.nil?
substitute = User.anonymous
Attachment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Comment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Issue.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Issue.update_all 'assigned_to_id = NULL', ['assigned_to_id = ?', id]
Journal.update_all ['user_id = ?', substitute.id], ['user_id = ?', id]
JournalDetail.update_all ['old_value = ?', substitute.id.to_s], ["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s]
JournalDetail.update_all ['value = ?', substitute.id.to_s], ["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s]
Message.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
News.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
# Remove private queries and keep public ones
Query.delete_all ['user_id = ? AND is_public = ?', id, false]
Query.update_all ['user_id = ?', substitute.id], ['user_id = ?', id]
TimeEntry.update_all ['user_id = ?', substitute.id], ['user_id = ?', id]
Token.delete_all ['user_id = ?', id]
Watcher.delete_all ['user_id = ?', id]
WikiContent.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
WikiContent::Version.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
end
# Return password digest # Return password digest
def self.hash_password(clear_password) def self.hash_password(clear_password)
Digest::SHA1.hexdigest(clear_password || "") Digest::SHA1.hexdigest(clear_password || "")
end end
# Returns a 128bits random salt as a hex string (32 chars long)
def self.generate_salt
ActiveSupport::SecureRandom.hex(16)
end
end end
class AnonymousUser < User class AnonymousUser < User
@@ -598,9 +508,4 @@ class AnonymousUser < User
def mail; nil end def mail; nil end
def time_zone; nil end def time_zone; nil end
def rss_key; nil end def rss_key; nil end
# Anonymous user can not be destroyed
def destroy
false
end
end end
-3
View File
@@ -51,7 +51,4 @@ class UserPreference < ActiveRecord::Base
def comments_sorting; self[:comments_sorting] end def comments_sorting; self[:comments_sorting] end
def comments_sorting=(order); self[:comments_sorting]=order end def comments_sorting=(order); self[:comments_sorting]=order end
def warn_on_leaving_unsaved; self[:warn_on_leaving_unsaved] || '1'; end
def warn_on_leaving_unsaved=(value); self[:warn_on_leaving_unsaved]=value; end
end end
-1
View File
@@ -33,7 +33,6 @@ class Version < ActiveRecord::Base
validates_inclusion_of :status, :in => VERSION_STATUSES validates_inclusion_of :status, :in => VERSION_STATUSES
validates_inclusion_of :sharing, :in => VERSION_SHARINGS validates_inclusion_of :sharing, :in => VERSION_SHARINGS
named_scope :named, lambda {|arg| { :conditions => ["LOWER(#{table_name}.name) = LOWER(?)", arg.to_s.strip]}}
named_scope :open, :conditions => {:status => 'open'} named_scope :open, :conditions => {:status => 'open'}
named_scope :visible, lambda {|*args| { :include => :project, named_scope :visible, lambda {|*args| { :include => :project,
:conditions => Project.allowed_to_condition(args.first || User.current, :view_issues) } } :conditions => Project.allowed_to_condition(args.first || User.current, :view_issues) } }
+1 -10
View File
@@ -44,26 +44,17 @@ class Wiki < ActiveRecord::Base
# find the page with the given title # find the page with the given title
def find_page(title, options = {}) def find_page(title, options = {})
@page_found_with_redirect = false
title = start_page if title.blank? title = start_page if title.blank?
title = Wiki.titleize(title) title = Wiki.titleize(title)
page = pages.first(:conditions => ["LOWER(title) = LOWER(?)", title]) page = pages.first(:conditions => ["LOWER(title) = LOWER(?)", title])
if !page && !(options[:with_redirect] == false) if !page && !(options[:with_redirect] == false)
# search for a redirect # search for a redirect
redirect = redirects.first(:conditions => ["LOWER(title) = LOWER(?)", title]) redirect = redirects.first(:conditions => ["LOWER(title) = LOWER(?)", title])
if redirect page = find_page(redirect.redirects_to, :with_redirect => false) if redirect
page = find_page(redirect.redirects_to, :with_redirect => false)
@page_found_with_redirect = true
end
end end
page page
end end
# Returns true if the last page was found with a redirect
def page_found_with_redirect?
@page_found_with_redirect
end
# Finds a page by title # Finds a page by title
# The given string can be of one of the forms: "title" or "project:title" # The given string can be of one of the forms: "title" or "project:title"
# Examples: # Examples:
+15 -15
View File
@@ -1,16 +1,16 @@
# RedMine - project management software # redMine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2007 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version. # of the License, or (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
@@ -23,28 +23,28 @@ class WikiContent < ActiveRecord::Base
belongs_to :author, :class_name => 'User', :foreign_key => 'author_id' belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
validates_presence_of :text validates_presence_of :text
validates_length_of :comments, :maximum => 255, :allow_nil => true validates_length_of :comments, :maximum => 255, :allow_nil => true
acts_as_versioned acts_as_versioned
def visible?(user=User.current) def visible?(user=User.current)
page.visible?(user) page.visible?(user)
end end
def project def project
page.project page.project
end end
def attachments def attachments
page.nil? ? [] : page.attachments page.nil? ? [] : page.attachments
end end
# Returns the mail adresses of users that should be notified # Returns the mail adresses of users that should be notified
def recipients def recipients
notified = project.notified_users notified = project.notified_users
notified.reject! {|user| !visible?(user)} notified.reject! {|user| !visible?(user)}
notified.collect(&:mail) notified.collect(&:mail)
end end
class Version class Version
belongs_to :page, :class_name => '::WikiPage', :foreign_key => 'page_id' belongs_to :page, :class_name => '::WikiPage', :foreign_key => 'page_id'
belongs_to :author, :class_name => '::User', :foreign_key => 'author_id' belongs_to :author, :class_name => '::User', :foreign_key => 'author_id'
@@ -84,7 +84,7 @@ class WikiContent < ActiveRecord::Base
end end
plain plain
end end
def text def text
@text ||= case compression @text ||= case compression
when 'gzip' when 'gzip'
@@ -92,16 +92,16 @@ class WikiContent < ActiveRecord::Base
else else
# uncompressed data # uncompressed data
data data
end end
end end
def project def project
page.project page.project
end end
# Returns the previous version or nil # Returns the previous version or nil
def previous def previous
@previous ||= WikiContent::Version.find(:first, @previous ||= WikiContent::Version.find(:first,
:order => 'version DESC', :order => 'version DESC',
:include => :author, :include => :author,
:conditions => ["wiki_content_id = ? AND version < ?", wiki_content_id, version]) :conditions => ["wiki_content_id = ? AND version < ?", wiki_content_id, version])
+10 -29
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2011 Jean-Philippe Lang # Copyright (C) 2006-2009 Jean-Philippe Lang
# #
# This program is free software; you can redistribute it and/or # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License # modify it under the terms of the GNU General Public License
@@ -30,9 +30,8 @@ class WikiPage < ActiveRecord::Base
:datetime => :created_on, :datetime => :created_on,
:url => Proc.new {|o| {:controller => 'wiki', :action => 'show', :project_id => o.wiki.project, :id => o.title}} :url => Proc.new {|o| {:controller => 'wiki', :action => 'show', :project_id => o.wiki.project, :id => o.title}}
acts_as_searchable :columns => ['title', "#{WikiContent.table_name}.text"], acts_as_searchable :columns => ['title', 'text'],
:include => [{:wiki => :project}, :content], :include => [{:wiki => :project}, :content],
:permission => :view_wiki_pages,
:project_key => "#{Wiki.table_name}.project_id" :project_key => "#{Wiki.table_name}.project_id"
attr_accessor :redirect_existing_links attr_accessor :redirect_existing_links
@@ -42,12 +41,6 @@ class WikiPage < ActiveRecord::Base
validates_uniqueness_of :title, :scope => :wiki_id, :case_sensitive => false validates_uniqueness_of :title, :scope => :wiki_id, :case_sensitive => false
validates_associated :content validates_associated :content
# eager load information about last updates, without loading text
named_scope :with_updated_on, {
:select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
:joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id"
}
# Wiki pages that are protected by default # Wiki pages that are protected by default
DEFAULT_PROTECTED_PAGES = %w(sidebar) DEFAULT_PROTECTED_PAGES = %w(sidebar)
@@ -128,18 +121,6 @@ class WikiPage < ActiveRecord::Base
content.text if content content.text if content
end end
def updated_on
unless @updated_on
if time = read_attribute(:updated_on)
# content updated_on was eager loaded with the page
@updated_on = Time.parse(time) rescue nil
else
@updated_on = content && content.updated_on
end
end
@updated_on
end
# Returns true if usr is allowed to edit the page, otherwise false # Returns true if usr is allowed to edit the page, otherwise false
def editable_by?(usr) def editable_by?(usr)
!protected? || usr.allowed_to?(:protect_wiki_pages, wiki.project) !protected? || usr.allowed_to?(:protect_wiki_pages, wiki.project)
@@ -168,13 +149,17 @@ class WikiPage < ActiveRecord::Base
end end
end end
class WikiDiff < Redmine::Helpers::Diff class WikiDiff
attr_reader :content_to, :content_from attr_reader :diff, :words, :content_to, :content_from
def initialize(content_to, content_from) def initialize(content_to, content_from)
@content_to = content_to @content_to = content_to
@content_from = content_from @content_from = content_from
super(content_to.text, content_from.text) @words = content_to.text.split(/(\s+)/)
@words = @words.select {|word| word != ' '}
words_from = content_from.text.split(/(\s+)/)
words_from = words_from.select {|word| word != ' '}
@diff = words_from.diff @words
end end
end end
@@ -212,10 +197,6 @@ class WikiAnnotate
break unless @lines.detect { |line| line[0].nil? } break unless @lines.detect { |line| line[0].nil? }
current = current.previous current = current.previous
end end
@lines.each { |line| @lines.each { |line| line[0] ||= current.version }
line[0] ||= current.version
# if the last known version is > 1 (eg. history was cleared), we don't know the author
line[1] ||= current.author if current.version == 1
}
end end
end end
+2 -2
View File
@@ -89,8 +89,8 @@ class Workflow < ActiveRecord::Base
else else
transaction do transaction do
delete_all :tracker_id => target_tracker.id, :role_id => target_role.id delete_all :tracker_id => target_tracker.id, :role_id => target_role.id
connection.insert "INSERT INTO #{Workflow.table_name} (tracker_id, role_id, old_status_id, new_status_id, author, assignee)" + connection.insert "INSERT INTO #{Workflow.table_name} (tracker_id, role_id, old_status_id, new_status_id)" +
" SELECT #{target_tracker.id}, #{target_role.id}, old_status_id, new_status_id, author, assignee" + " SELECT #{target_tracker.id}, #{target_role.id}, old_status_id, new_status_id" +
" FROM #{Workflow.table_name}" + " FROM #{Workflow.table_name}" +
" WHERE tracker_id = #{source_tracker.id} AND role_id = #{source_role.id}" " WHERE tracker_id = #{source_tracker.id} AND role_id = #{source_role.id}"
end end
+8 -6
View File
@@ -21,14 +21,16 @@
<%= content_tag('p', l(:label_no_data), :class => 'nodata') if @events_by_day.empty? %> <%= content_tag('p', l(:label_no_data), :class => 'nodata') if @events_by_day.empty? %>
<div style="float:left;"> <div style="float:left;">
<%= link_to_content_update('&#171; ' + l(:label_previous), <%= link_to_remote(('&#171; ' + l(:label_previous)),
params.merge(:from => @date_to - @days - 1), {:update => "content", :url => params.merge(:from => @date_to - @days - 1), :method => :get, :complete => 'window.scrollTo(0,0)'},
:title => l(:label_date_from_to, :start => format_date(@date_to - 2*@days), :end => format_date(@date_to - @days - 1))) %> {:href => url_for(params.merge(:from => @date_to - @days - 1)),
:title => l(:label_date_from_to, :start => format_date(@date_to - 2*@days), :end => format_date(@date_to - @days - 1))}) %>
</div> </div>
<div style="float:right;"> <div style="float:right;">
<%= link_to_content_update(l(:label_next) + ' &#187;', <%= link_to_remote((l(:label_next) + ' &#187;'),
params.merge(:from => @date_to + @days - 1), {:update => "content", :url => params.merge(:from => @date_to + @days - 1), :method => :get, :complete => 'window.scrollTo(0,0)'},
:title => l(:label_date_from_to, :start => format_date(@date_to), :end => format_date(@date_to + @days - 1))) unless @date_to >= Date.today %> {:href => url_for(params.merge(:from => @date_to + @days - 1)),
:title => l(:label_date_from_to, :start => format_date(@date_to), :end => format_date(@date_to + @days - 1))}) unless @date_to >= Date.today %>
</div> </div>
&nbsp; &nbsp;
<% other_formats_links do |f| %> <% other_formats_links do |f| %>
+4 -5
View File
@@ -4,11 +4,10 @@
<table class="list"> <table class="list">
<% @checklist.each do |label, result| %> <% @checklist.each do |label, result| %>
<tr class="<%= cycle 'odd', 'even' %>"> <tr class="<%= cycle 'odd', 'even' %>">
<td><%= l(label) %></td> <td><%= l(label) %></td>
<td width="30px"><%= image_tag((result ? 'true.png' : 'exclamation.png'), <td width="30px"><%= image_tag((result ? 'true.png' : 'exclamation.png'), :style => "vertical-align:bottom;") %></td>
:style => "vertical-align:bottom;") %></td> </tr>
</tr>
<% end %> <% end %>
</table> </table>
-1
View File
@@ -11,7 +11,6 @@
<label><%= l(:label_project) %>:</label> <label><%= l(:label_project) %>:</label>
<%= text_field_tag 'name', params[:name], :size => 30 %> <%= text_field_tag 'name', params[:name], :size => 30 %>
<%= submit_tag l(:button_apply), :class => "small", :name => nil %> <%= submit_tag l(:button_apply), :class => "small", :name => nil %>
<%= link_to l(:button_clear), {:controller => 'admin', :action => 'projects'}, :class => 'icon icon-reload' %>
</fieldset> </fieldset>
<% end %> <% end %>
&nbsp; &nbsp;

Some files were not shown because too many files have changed in this diff Show More