Compare commits

..
114 Commits
Author SHA1 Message Date
Jean-Philippe Lang a84920ca70 Merged r3865 and r3866 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3868 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-07-25 09:34:13 +00:00
Eric Davis 21d2de48b7 Merged r3836 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3838 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-07-08 03:54:53 +00:00
Eric Davis a19a37b600 Merged r3835 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3837 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-07-08 03:54:48 +00:00
Eric Davis 29e7b8d9ea Merged r3832 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3834 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-07-08 03:48:40 +00:00
Eric Davis f3b9c0027f Merged r3831 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3833 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-07-08 03:48:35 +00:00
Eric Davis a146c2d03f Merged r3815 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3817 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-28 02:48:12 +00:00
Eric Davis a62ff0841f Merged r3814 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3816 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-28 02:48:06 +00:00
Eric Davis d7ec02691f Merged r3811 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3812 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-24 02:39:21 +00:00
Eric Davis e7790bb6b5 Fix nil method error when no issue params are submitted. #5123
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3796 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-20 03:24:38 +00:00
Eric Davis 34f73b005b Merged r3785 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3795 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-19 23:03:12 +00:00
Eric Davis ba42e1e2ff Merged r3786 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3794 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-19 23:03:07 +00:00
Eric Davis 14074da8b1 Merged r3784 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3793 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-19 23:03:01 +00:00
Eric Davis 44851d079f Merged r3787 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3792 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-19 23:02:55 +00:00
Eric Davis e6d053c3fd Merged r3783 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3791 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-19 23:02:50 +00:00
Eric Davis f17924c60d Merged r3775 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3781 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-19 18:47:18 +00:00
Eric Davis 90e23e4d5d Merged r3777 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3780 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-19 18:47:13 +00:00
Eric Davis 88a2792778 Merged r3776 from trunk
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3779 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-19 18:47:08 +00:00
Eric Davis 4c881d54a7 Merged r3659 from trunk
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3778 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-06-19 18:47:03 +00:00
Jean-Philippe Lang a6d45cc68f Merged r3740 and r3741 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3742 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-05-22 08:55:56 +00:00
Jean-Philippe Lang f58f7e0e41 Merged r3727 from trunk for 0.9.4 release.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3728 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-05-01 12:38:44 +00:00
Jean-Philippe Lang 473366f887 Merged r3725 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3726 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-05-01 12:33:27 +00:00
Jean-Philippe Lang f6d2a4c29f Backported r3683 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3717 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-30 17:32:42 +00:00
Jean-Philippe Lang b26d0fe041 Merged r3705 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3715 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-30 17:20:59 +00:00
Jean-Philippe Lang 98f3e98d82 Merged r3702 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3714 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-30 17:19:40 +00:00
Jean-Philippe Lang 7b27280c9b Backported r3692 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3713 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-30 14:22:52 +00:00
Jean-Philippe Lang d287436627 Merged r3678 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3712 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-30 14:06:45 +00:00
Jean-Philippe Lang 666d3d6472 Merged r3682 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3711 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-30 14:05:37 +00:00
Eric Davis 36063f16ee Merged r3698 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3699 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-29 23:30:21 +00:00
Jean-Philippe Lang 4a295e723e Merged r3668 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3697 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-29 22:05:49 +00:00
Jean-Philippe Lang 6e67d76194 Merged r3613 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3662 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 15:24:49 +00:00
Jean-Philippe Lang eb55efd604 Merged r3612 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3661 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 15:23:30 +00:00
Jean-Philippe Lang 390eb7849c Merged r3611 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3660 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 15:21:08 +00:00
Jean-Philippe Lang 1588f3f6dc Merged r3397 from trunk to fix sqlite3 and pgsql test environments.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3658 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 15:06:43 +00:00
Jean-Philippe Lang 5ef8e8d45f Merged r3635 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3657 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:53:54 +00:00
Jean-Philippe Lang cd15eb77d9 Merged r3625 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3656 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:44:18 +00:00
Jean-Philippe Lang 3b699806d9 Merged r3614 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3655 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:43:29 +00:00
Jean-Philippe Lang d2367ccf53 Merged r3517 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3654 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:42:44 +00:00
Jean-Philippe Lang 9c00b8aa21 Merged r3530 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3653 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:41:59 +00:00
Jean-Philippe Lang bbb00b0bc4 Merged r3616 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3652 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:41:15 +00:00
Jean-Philippe Lang feac751318 Merged r3615 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3651 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:39:14 +00:00
Jean-Philippe Lang eb4a7f9f2e Merged r3566 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3650 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:37:59 +00:00
Jean-Philippe Lang 7ce9ba9e28 Merged r3562 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3649 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:34:05 +00:00
Jean-Philippe Lang 53880a4e08 Merged r3571 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3648 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:32:29 +00:00
Jean-Philippe Lang f92aa00705 Merged r3550 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3647 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:31:40 +00:00
Jean-Philippe Lang b240da3833 Merged r3532 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3646 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:30:50 +00:00
Jean-Philippe Lang da8624f7c7 Merged r3524 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3645 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:29:59 +00:00
Jean-Philippe Lang 46be83cd5e Merged r3537 and r3572 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3644 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:29:02 +00:00
Jean-Philippe Lang 667f7927a7 Merged r3494 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3643 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:21:47 +00:00
Jean-Philippe Lang 3e6f42e46d Backported r3608 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3642 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:20:40 +00:00
Jean-Philippe Lang 30c45a6187 Merged r3529 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3641 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:10:01 +00:00
Jean-Philippe Lang 32288ed5d7 Merged r3514 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3640 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:09:11 +00:00
Jean-Philippe Lang beb89eb8bb Merged r3558 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3639 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:08:03 +00:00
Jean-Philippe Lang 62d8016c4f Merged r3513 and r3531 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3638 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:06:10 +00:00
Jean-Philippe Lang 5a7a3b2392 Merged r3603 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3637 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:04:37 +00:00
Jean-Philippe Lang a2ad66a5c0 Merged r3539 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3636 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-04-11 14:03:28 +00:00
Jean-Philippe Lang bfd9164c0a Merged r3506 for 0.9.3 release.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3507 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-28 10:21:33 +00:00
Jean-Philippe Lang d80fb751fd Merged r3469, r3472 and r3473 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3505 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-28 10:10:55 +00:00
Jean-Philippe Lang aacabbe645 Merged r3498 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3504 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-28 09:59:31 +00:00
Jean-Philippe Lang 8eafcbede9 Merged r3481 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3503 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-28 09:58:33 +00:00
Jean-Philippe Lang 43c1481998 Merged r3446 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3502 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-28 09:56:55 +00:00
Jean-Philippe Lang 17f60af490 Merged r3394, r3466, r3467, r3468 and r3471 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3501 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-28 09:51:10 +00:00
Jean-Philippe Lang e5e5ad6b7a Merged r3398 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3465 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-20 10:40:02 +00:00
Jean-Philippe Lang 13fb739b56 Merged r3409 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3464 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-20 10:26:49 +00:00
Jean-Philippe Lang 73e849be58 Merged r3451 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3463 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-20 10:22:06 +00:00
Jean-Philippe Lang 0b7d4e818a Merged r3452 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3462 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-20 10:20:52 +00:00
Jean-Philippe Lang 40a4b111fa Merged r3447 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3461 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-20 10:19:02 +00:00
Jean-Philippe Lang 7d913f93c3 Merged r3448 and r3455 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3460 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-20 10:16:08 +00:00
Jean-Philippe Lang 864fd9c6a1 Merged bug fixes r3423 and r3427.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3433 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-14 15:57:56 +00:00
Jean-Philippe Lang 57dcbd7376 Merged bug fixes r3412 to r3414.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3432 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-14 15:55:00 +00:00
Jean-Philippe Lang 0ef11ef4fe Merged bug fixes r3402, r3405 to r3408 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3431 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-14 15:48:28 +00:00
Jean-Philippe Lang b5ee8c08ca Merged r3392 from trunk (0.9.2 update).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3393 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 12:48:56 +00:00
Jean-Philippe Lang 9487d8dd80 Merged r3389 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3391 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 12:37:12 +00:00
Jean-Philippe Lang f3bf588c82 Translations updated to trunk r3388.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3390 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 12:36:12 +00:00
Jean-Philippe Lang bd38623cca Merged r3379 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3387 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 11:58:42 +00:00
Jean-Philippe Lang bae86dc558 Merged r3377 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3386 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 11:57:49 +00:00
Jean-Philippe Lang 884c5be200 Backported r3368 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3385 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 11:56:49 +00:00
Jean-Philippe Lang ad24563b1e Merged r3378 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3384 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 11:53:17 +00:00
Jean-Philippe Lang cb8933ae55 Merged r3376 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3383 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 11:52:09 +00:00
Jean-Philippe Lang 5d75879046 Merged r3375 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3382 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 11:50:56 +00:00
Jean-Philippe Lang 69e5d91a2d Backported r3354 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3381 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 11:49:40 +00:00
Jean-Philippe Lang 7c1e877209 Merged r3357 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3380 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-07 11:45:31 +00:00
Eric Davis 76d9d01db0 Merged the Object Daddy exemplars from trunk. r3337, r3340, r3342
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3359 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-02-02 16:03:05 +00:00
Jean-Philippe Lang 27fa40d283 Merged r3351 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3352 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-30 11:24:10 +00:00
Jean-Philippe Lang 20a6d7eb86 Merged r3348 from trunk (version set to 0.9.1).
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3349 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-30 10:54:45 +00:00
Jean-Philippe Lang b87cf0c91c Merged r3346 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3347 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-30 10:37:05 +00:00
Jean-Philippe Lang 14ee72def2 Merged r3341 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3345 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-30 10:28:26 +00:00
Jean-Philippe Lang a843cfff36 Merged r3343 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3344 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-30 10:26:30 +00:00
Jean-Philippe Lang 3d7cb0f40e Merged r3333 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3334 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-18 18:01:19 +00:00
Jean-Philippe Lang 92b267a608 Merged r3328 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3329 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-17 12:01:33 +00:00
Jean-Philippe Lang c1be8bcf9f Merged r3325 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3326 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-17 11:18:04 +00:00
Jean-Philippe Lang ff9aa9db59 Merged r3323 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3324 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-17 11:09:29 +00:00
Jean-Philippe Lang 65ee523852 Merged r3312 and r3320 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3321 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-17 10:34:47 +00:00
Jean-Philippe Lang 1f5d95b027 Merged r3309 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3318 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-17 10:28:06 +00:00
Jean-Philippe Lang c5a59aff5b Merged r3305, r3306, r3307, r3311 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3317 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-16 13:57:41 +00:00
Eric Davis f60881518a Merged r3315 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3316 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-14 23:33:48 +00:00
Jean-Philippe Lang 1efb25a433 Merged r3298 to r3302 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3303 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-10 10:22:03 +00:00
Jean-Philippe Lang eaaa471d6a Merged r3295 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3296 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-09 11:50:31 +00:00
Jean-Philippe Lang 2b6d8125d1 Merged r3293 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3294 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-09 11:47:38 +00:00
Jean-Philippe Lang 12b75ded08 Locales updated to trunk @ r3291.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3292 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-09 10:41:27 +00:00
Jean-Philippe Lang 46bf2b9276 Merged r3289 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3290 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-09 10:27:50 +00:00
Jean-Philippe Lang 9d82bff1a8 Merged r3282 to r3284 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3287 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-09 10:04:21 +00:00
Jean-Philippe Lang 4c75864948 Merged r3258 and r3281 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3286 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-09 10:02:16 +00:00
Jean-Philippe Lang 9d2474c234 Merged r3277 to r3279 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3280 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-03 11:47:25 +00:00
Jean-Philippe Lang 7193817dea Translation updates.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3276 e93f8b46-1217-0410-a6f0-8f06a7374b81
2010-01-03 10:32:37 +00:00
Eric Davis 610d7d4ba4 Merged r3267 from trunk
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3268 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-30 00:51:08 +00:00
Eric Davis 4b41788848 Merged r3265 from trunk
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3266 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-30 00:26:48 +00:00
Eric Davis e1423c7c23 Merged r3263 from trunk
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3264 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-29 23:33:46 +00:00
Eric Davis 9c9f6722f6 Merged r3261 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3262 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-29 17:58:21 +00:00
Jean-Philippe Lang a8be47295a Merged r3259 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3260 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-29 14:56:17 +00:00
Eric Davis ba98197637 Merged r3256 from trunk
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3257 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-29 00:44:28 +00:00
Jean-Philippe Lang a23399f220 Merged r3249 to r3252 and r3254 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3255 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-27 12:41:27 +00:00
Jean-Philippe Lang 718cd596e0 Merged r3246 and r3247 from trunk.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3248 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-26 13:54:57 +00:00
Jean-Philippe Lang c5ccfede6d Set VERSION::BRANCH to stable.
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3245 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-26 10:27:46 +00:00
Jean-Philippe Lang 7702bdcdab 0.9-stable branch created
git-svn-id: svn+ssh://rubyforge.org/var/svn/redmine/branches/0.9-stable@3244 e93f8b46-1217-0410-a6f0-8f06a7374b81
2009-12-26 10:22:16 +00:00
2212 changed files with 75167 additions and 155011 deletions
-23
View File
@@ -1,42 +1,19 @@
/.project
/.loadpath
/.powrc
/.rvmrc
/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
/config/initializers/secret_token.rb
/coverage /coverage
/db/*.db /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
/plugins/*
!/plugins/README
/public/dispatch.* /public/dispatch.*
/public/plugin_assets /public/plugin_assets
/public/themes/*
!/public/themes/alternate
!/public/themes/classic
!/public/themes/README
/tmp/* /tmp/*
/tmp/cache/* /tmp/cache/*
/tmp/pdf/*
/tmp/sessions/* /tmp/sessions/*
/tmp/sockets/* /tmp/sockets/*
/tmp/test/* /tmp/test/*
/tmp/thumbnails/*
/vendor/cache
/vendor/rails /vendor/rails
*.rbc
/.bundle
/Gemfile.lock
/Gemfile.local
-41
View File
@@ -1,41 +0,0 @@
syntax: glob
.project
.loadpath
.powrc
.rvmrc
config/additional_environment.rb
config/configuration.yml
config/database.yml
config/email.yml
config/initializers/session_store.rb
config/initializers/secret_token.rb
coverage
db/*.db
db/*.sqlite3
db/schema.rb
files/*
lib/redmine/scm/adapters/mercurial/redminehelper.pyc
lib/redmine/scm/adapters/mercurial/redminehelper.pyo
log/*.log*
log/mongrel_debug
public/dispatch.*
public/plugin_assets
tmp/*
tmp/cache/*
tmp/pdf/*
tmp/sessions/*
tmp/sockets/*
tmp/test/*
tmp/thumbnails/*
vendor/cache
vendor/rails
*.rbc
.svn/
.git/
.bundle
Gemfile.lock
Gemfile.local
-8
View File
@@ -1,8 +0,0 @@
**Do not send a pull requst to this github repository**.
For more detail, please see [official website] wiki [Contribute].
[official website]: http://www.redmine.org
[Contribute]: http://www.redmine.org/projects/redmine/wiki/Contribute
-100
View File
@@ -1,100 +0,0 @@
source 'https://rubygems.org'
gem "rails", "3.2.13"
gem "jquery-rails", "~> 2.0.2"
gem "i18n", "~> 0.6.0"
gem "coderay", "~> 1.1.0"
gem "fastercsv", "~> 1.5.0", :platforms => [:mri_18, :mingw_18, :jruby]
gem "builder", "3.0.0"
# Optional gem for LDAP authentication
group :ldap do
gem "net-ldap", "~> 0.3.1"
end
# Optional gem for OpenID authentication
group :openid do
gem "ruby-openid", "~> 2.3.0", :require => "openid"
gem "rack-openid"
end
# Optional gem for exporting the gantt to a PNG file, not supported with jruby
platforms :mri, :mingw do
group :rmagick do
# RMagick 2 supports ruby 1.9
# RMagick 1 would be fine for ruby 1.8 but Bundler does not support
# different requirements for the same gem on different platforms
gem "rmagick", ">= 2.0.0"
end
end
platforms :jruby do
# jruby-openssl is bundled with JRuby 1.7.0
gem "jruby-openssl" if Object.const_defined?(:JRUBY_VERSION) && JRUBY_VERSION < '1.7.0'
gem "activerecord-jdbc-adapter", "~> 1.2.6"
end
# Include database gems for the adapters found in the database
# configuration file
require 'erb'
require 'yaml'
database_file = File.join(File.dirname(__FILE__), "config/database.yml")
if File.exist?(database_file)
database_config = YAML::load(ERB.new(IO.read(database_file)).result)
adapters = database_config.values.map {|c| c['adapter']}.compact.uniq
if adapters.any?
adapters.each do |adapter|
case adapter
when 'mysql2'
gem "mysql2", "~> 0.3.11", :platforms => [:mri, :mingw]
gem "activerecord-jdbcmysql-adapter", :platforms => :jruby
when 'mysql'
gem "mysql", "~> 2.8.1", :platforms => [:mri, :mingw]
gem "activerecord-jdbcmysql-adapter", :platforms => :jruby
when /postgresql/
gem "pg", ">= 0.11.0", :platforms => [:mri, :mingw]
gem "activerecord-jdbcpostgresql-adapter", :platforms => :jruby
when /sqlite3/
gem "sqlite3", :platforms => [:mri, :mingw]
gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
when /sqlserver/
gem "tiny_tds", "~> 0.5.1", :platforms => [:mri, :mingw]
gem "activerecord-sqlserver-adapter", :platforms => [:mri, :mingw]
else
warn("Unknown database adapter `#{adapter}` found in config/database.yml, use Gemfile.local to load your own database gems")
end
end
else
warn("No adapter found in config/database.yml, please configure it first")
end
else
warn("Please configure your config/database.yml first")
end
group :development do
gem "rdoc", ">= 2.4.2"
gem "yard"
end
group :test do
gem "shoulda", "~> 3.3.2"
gem "mocha", ">= 0.14", :require => 'mocha/api'
if RUBY_VERSION >= '1.9.3'
gem "capybara", "~> 2.1.0"
gem "selenium-webdriver"
gem "database_cleaner"
end
end
local_gemfile = File.join(File.dirname(__FILE__), "Gemfile.local")
if File.exists?(local_gemfile)
puts "Loading Gemfile.local ..." if $DEBUG # `ruby -d` or `bundle -v`
instance_eval File.read(local_gemfile)
end
# Load plugins' Gemfiles
Dir.glob File.expand_path("../plugins/*/Gemfile", __FILE__) do |file|
puts "Loading #{file} ..." if $DEBUG # `ruby -d` or `bundle -v`
#TODO: switch to "eval_gemfile file" when bundler >= 1.2.0 will be required (rails 4)
instance_eval File.read(file), file
end
+1 -1
View File
@@ -2,4 +2,4 @@
Redmine is a flexible project management web application written using Ruby on Rails framework. Redmine is a flexible project management web application written using Ruby on Rails framework.
More details can be found in the doc directory or on the official website http://www.redmine.org More details can be found at http://www.redmine.org
+7 -4
View File
@@ -1,7 +1,10 @@
#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake, # Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. # for example lib/tasks/switchtower.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__) require(File.join(File.dirname(__FILE__), 'config', 'boot'))
RedmineApp::Application.load_tasks require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'tasks/rails'
+63 -138
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -20,53 +20,41 @@ class AccountController < ApplicationController
include CustomFieldsHelper include CustomFieldsHelper
# prevents login action to be filtered by check_if_login_required application scope filter # prevents login action to be filtered by check_if_login_required application scope filter
skip_before_filter :check_if_login_required, :check_password_change skip_before_filter :check_if_login_required
# Login request and validation # Login request and validation
def login def login
if request.get? if request.get?
if User.current.logged? logout_user
redirect_to home_url
end
else else
authenticate_user # Authenticate user
if Setting.openid? && using_open_id?
open_id_authenticate(params[:openid_url])
else
password_authentication
end
end end
rescue AuthSourceException => e
logger.error "An error occured when authenticating #{params[:username]}: #{e.message}"
render_error :message => e.message
end end
# Log out current user and redirect to welcome page # Log out current user and redirect to welcome page
def logout def logout
if User.current.anonymous? logout_user
redirect_to home_url redirect_to home_url
elsif request.post?
logout_user
redirect_to home_url
end
# display the logout form
end end
# Lets user choose a new password # Enable user to choose a new password
def lost_password def lost_password
(redirect_to(home_url); return) unless Setting.lost_password? redirect_to(home_url) && return unless Setting.lost_password?
if params[:token] if params[:token]
@token = Token.find_token("recovery", params[:token].to_s) @token = Token.find_by_action_and_value("recovery", params[:token])
if @token.nil? || @token.expired? redirect_to(home_url) && return unless @token and !@token.expired?
redirect_to home_url
return
end
@user = @token.user @user = @token.user
unless @user && @user.active?
redirect_to home_url
return
end
if request.post? if request.post?
@user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation] @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
if @user.save if @user.save
@token.destroy @token.destroy
flash[:notice] = l(:notice_account_password_updated) flash[:notice] = l(:notice_account_password_updated)
redirect_to signin_path redirect_to :action => 'login'
return return
end end
end end
@@ -74,27 +62,17 @@ class AccountController < ApplicationController
return return
else else
if request.post? if request.post?
user = User.find_by_mail(params[:mail].to_s) user = User.find_by_mail(params[:mail])
# user not found # user not found in db
unless user (flash.now[:error] = l(:notice_account_unknown_email); return) unless user
flash.now[:error] = l(:notice_account_unknown_email) # user uses an external authentification
return (flash.now[:error] = l(:notice_can_t_change_password); return) if user.auth_source_id
end
unless user.active?
handle_inactive_user(user, lost_password_path)
return
end
# user cannot change its password
unless user.change_password_allowed?
flash.now[:error] = l(:notice_can_t_change_password)
return
end
# create a new token for password recovery # create a new token for password recovery
token = Token.new(:user => user, :action => "recovery") token = Token.new(:user => user, :action => "recovery")
if token.save if token.save
Mailer.lost_password(token).deliver Mailer.deliver_lost_password(token)
flash[:notice] = l(:notice_account_lost_email_sent) flash[:notice] = l(:notice_account_lost_email_sent)
redirect_to signin_path redirect_to :action => 'login'
return return
end end
end end
@@ -103,31 +81,27 @@ class AccountController < ApplicationController
# User self-registration # User self-registration
def register def register
(redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration] redirect_to(home_url) && return unless Setting.self_registration? || session[:auth_source_registration]
if request.get? if request.get?
session[:auth_source_registration] = nil session[:auth_source_registration] = nil
@user = User.new(:language => current_language.to_s) @user = User.new(:language => Setting.default_language)
else else
user_params = params[:user] || {} @user = User.new(params[:user])
@user = User.new
@user.safe_attributes = user_params
@user.admin = false @user.admin = false
@user.register @user.status = User::STATUS_REGISTERED
if session[:auth_source_registration] if session[:auth_source_registration]
@user.activate @user.status = User::STATUS_ACTIVE
@user.login = session[:auth_source_registration][:login] @user.login = session[:auth_source_registration][:login]
@user.auth_source_id = session[:auth_source_registration][:auth_source_id] @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
if @user.save if @user.save
session[:auth_source_registration] = nil session[:auth_source_registration] = nil
self.logged_user = @user self.logged_user = @user
flash[:notice] = l(:notice_account_activated) flash[:notice] = l(:notice_account_activated)
redirect_to my_account_path redirect_to :controller => 'my', :action => 'account'
end end
else else
@user.login = params[:user][:login] @user.login = params[:user][:login]
unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank? @user.password, @user.password_confirmation = params[:password], params[:password_confirmation]
@user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
end
case Setting.self_registration case Setting.self_registration
when '1' when '1'
@@ -143,44 +117,31 @@ class AccountController < ApplicationController
# Token based account activation # Token based account activation
def activate def activate
(redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present? redirect_to(home_url) && return unless Setting.self_registration? && params[:token]
token = Token.find_token('register', params[:token].to_s) token = Token.find_by_action_and_value('register', params[:token])
(redirect_to(home_url); return) unless token and !token.expired? redirect_to(home_url) && return unless token and !token.expired?
user = token.user user = token.user
(redirect_to(home_url); return) unless user.registered? redirect_to(home_url) && return unless user.status == User::STATUS_REGISTERED
user.activate user.status = User::STATUS_ACTIVE
if user.save if user.save
token.destroy token.destroy
flash[:notice] = l(:notice_account_activated) flash[:notice] = l(:notice_account_activated)
end end
redirect_to signin_path redirect_to :action => 'login'
end
# Sends a new account activation email
def activation_email
if session[:registered_user_id] && Setting.self_registration == '1'
user_id = session.delete(:registered_user_id).to_i
user = User.find_by_id(user_id)
if user && user.registered?
register_by_email_activation(user)
return
end
end
redirect_to(home_url)
end end
private private
def authenticate_user def logout_user
if Setting.openid? && using_open_id? if User.current.logged?
open_id_authenticate(params[:openid_url]) cookies.delete :autologin
else Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
password_authentication self.logged_user = nil
end end
end end
def password_authentication def password_authentication
user = User.try_to_login(params[:username], params[:password], false) user = User.try_to_login(params[:username], params[:password])
if user.nil? if user.nil?
invalid_credentials invalid_credentials
@@ -188,31 +149,26 @@ class AccountController < ApplicationController
onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id }) onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
else else
# Valid user # Valid user
if user.active? successful_authentication(user)
successful_authentication(user)
else
handle_inactive_user(user)
end
end end
end end
def open_id_authenticate(openid_url) def open_id_authenticate(openid_url)
back_url = signin_url(:autologin => params[:autologin]) authenticate_with_open_id(openid_url, :required => [:nickname, :fullname, :email], :return_to => signin_url) do |result, identity_url, registration|
authenticate_with_open_id(
openid_url, :required => [:nickname, :fullname, :email],
:return_to => back_url, :method => :post
) do |result, identity_url, registration|
if result.successful? if result.successful?
user = User.find_or_initialize_by_identity_url(identity_url) user = User.find_or_initialize_by_identity_url(identity_url)
if user.new_record? if user.new_record?
# Self-registration off # Self-registration off
(redirect_to(home_url); return) unless Setting.self_registration? redirect_to(home_url) && return unless Setting.self_registration?
# Create on the fly # Create on the fly
user.login = registration['nickname'] unless registration['nickname'].nil? user.login = registration['nickname'] unless registration['nickname'].nil?
user.mail = registration['email'] unless registration['email'].nil? user.mail = registration['email'] unless registration['email'].nil?
user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil? user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil?
user.random_password user.random_password
user.register user.status = User::STATUS_REGISTERED
case Setting.self_registration case Setting.self_registration
when '1' when '1'
register_by_email_activation(user) do register_by_email_activation(user) do
@@ -232,7 +188,7 @@ class AccountController < ApplicationController
if user.active? if user.active?
successful_authentication(user) successful_authentication(user)
else else
handle_inactive_user(user) account_pending
end end
end end
end end
@@ -240,27 +196,15 @@ class AccountController < ApplicationController
end end
def successful_authentication(user) def successful_authentication(user)
logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
# Valid user # Valid user
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 my_page_path redirect_back_or_default :controller => 'my', :action => 'page'
end
def set_autologin_cookie(user)
token = Token.create(:user => user, :action => '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[autologin_cookie_name] = cookie_options
end end
# Onthefly creation failed, display the registration form to fill/fix attributes # Onthefly creation failed, display the registration form to fill/fix attributes
@@ -271,7 +215,6 @@ class AccountController < ApplicationController
end end
def invalid_credentials def invalid_credentials
logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
flash.now[:error] = l(:notice_account_invalid_creditentials) flash.now[:error] = l(:notice_account_invalid_creditentials)
end end
@@ -281,9 +224,9 @@ class AccountController < ApplicationController
def register_by_email_activation(user, &block) def register_by_email_activation(user, &block)
token = Token.new(:user => user, :action => "register") token = Token.new(:user => user, :action => "register")
if user.save and token.save if user.save and token.save
Mailer.register(token).deliver Mailer.deliver_register(token)
flash[:notice] = l(:notice_account_register_done, :email => user.mail) flash[:notice] = l(:notice_account_register_done)
redirect_to signin_path redirect_to :action => 'login'
else else
yield if block_given? yield if block_given?
end end
@@ -294,12 +237,12 @@ class AccountController < ApplicationController
# Pass a block for behavior when a user fails to save # Pass a block for behavior when a user fails to save
def register_automatically(user, &block) def register_automatically(user, &block)
# Automatic activation # Automatic activation
user.activate user.status = User::STATUS_ACTIVE
user.last_login_on = Time.now user.last_login_on = Time.now
if user.save if user.save
self.logged_user = user self.logged_user = user
flash[:notice] = l(:notice_account_activated) flash[:notice] = l(:notice_account_activated)
redirect_to my_account_path redirect_to :controller => 'my', :action => 'account'
else else
yield if block_given? yield if block_given?
end end
@@ -311,33 +254,15 @@ class AccountController < ApplicationController
def register_manually_by_administrator(user, &block) def register_manually_by_administrator(user, &block)
if user.save if user.save
# Sends an email to the administrators # Sends an email to the administrators
Mailer.account_activation_request(user).deliver Mailer.deliver_account_activation_request(user)
account_pending(user) account_pending
else else
yield if block_given? yield if block_given?
end end
end end
def handle_inactive_user(user, redirect_path=signin_path) def account_pending
if user.registered? flash[:notice] = l(:notice_account_pending)
account_pending(user, redirect_path) redirect_to :action => 'login'
else
account_locked(user, redirect_path)
end
end
def account_pending(user, redirect_path=signin_path)
if Setting.self_registration == '1'
flash[:error] = l(:notice_account_not_activated_yet, :url => activation_email_path)
session[:registered_user_id] = user.id
else
flash[:error] = l(:notice_account_pending)
end
redirect_to redirect_path
end
def account_locked(user, redirect_path=signin_path)
flash[:error] = l(:notice_account_locked)
redirect_to redirect_path
end end
end end
-75
View File
@@ -1,75 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2013 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
menu_item :activity
before_filter :find_optional_project
accept_rss_auth :index
def index
@days = Setting.activity_days_default.to_i
if params[:from]
begin; @date_to = params[:from].to_date + 1; rescue; end
end
@date_to ||= Date.today + 1
@date_from = @date_to - @days
@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]))
@activity = Redmine::Activity::Fetcher.new(User.current, :project => @project,
:with_subprojects => @with_subprojects,
:author => @author)
@activity.scope_select {|t| !params["show_#{t}"].nil?}
@activity.scope = (@author.nil? ? :default : :all) if @activity.scope.empty?
events = @activity.events(@date_from, @date_to)
if events.empty? || stale?(:etag => [@activity.scope, @date_to, @date_from, @with_subprojects, @author, events.first, events.size, User.current, current_language])
respond_to do |format|
format.html {
@events_by_day = events.group_by {|event| User.current.time_to_date(event.event_datetime)}
render :layout => false if request.xhr?
}
format.atom {
title = l(:label_activity)
if @author
title = @author.name
elsif @activity.scope.size == 1
title = l("label_#{@activity.scope.first.singularize}_plural")
end
render_feed(events, :title => "#{@project || Setting.app_title}: #{title}")
}
end
end
rescue ActiveRecord::RecordNotFound
render_404
end
private
# TODO: refactor, duplicated in projects_controller
def find_optional_project
return true unless params[:id]
@project = Project.find(params[:id])
authorize
rescue ActiveRecord::RecordNotFound
render_404
end
end
+19 -16
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,11 +17,9 @@
class AdminController < ApplicationController class AdminController < ApplicationController
layout 'admin' layout 'admin'
menu_item :projects, :only => :projects
menu_item :plugins, :only => :plugins
menu_item :info, :only => :info
before_filter :require_admin before_filter :require_admin
helper :sort helper :sort
include SortHelper include SortHelper
@@ -30,11 +28,16 @@ class AdminController < ApplicationController
end end
def projects def projects
@status = params[:status] || 1 @status = params[:status] ? params[:status].to_i : 1
c = ARCondition.new(@status == 0 ? "status <> 0" : ["status = ?", @status])
scope = Project.status(@status).order('lft') unless params[:name].blank?
scope = scope.like(params[:name]) if params[:name].present? name = "%#{params[:name].strip.downcase}%"
@projects = scope.all c << ["LOWER(identifier) LIKE ? OR LOWER(name) LIKE ?", name, name]
end
@projects = Project.find :all, :order => 'lft',
:conditions => c.conditions
render :action => "projects", :layout => false if request.xhr? render :action => "projects", :layout => false if request.xhr?
end end
@@ -54,7 +57,7 @@ class AdminController < ApplicationController
flash[:error] = l(:error_can_t_load_default_data, e.message) flash[:error] = l(:error_can_t_load_default_data, e.message)
end end
end end
redirect_to admin_path redirect_to :action => 'index'
end end
def test_email def test_email
@@ -62,22 +65,22 @@ class AdminController < ApplicationController
# Force ActionMailer to raise delivery errors so we can catch it # Force ActionMailer to raise delivery errors so we can catch it
ActionMailer::Base.raise_delivery_errors = true ActionMailer::Base.raise_delivery_errors = true
begin begin
@test = Mailer.test_email(User.current).deliver @test = Mailer.deliver_test(User.current)
flash[:notice] = l(:notice_email_sent, User.current.mail) flash[:notice] = l(:notice_email_sent, User.current.mail)
rescue Exception => e rescue Exception => e
flash[:error] = l(:notice_email_error, Redmine::CodesetUtil.replace_invalid_utf8(e.message)) flash[:error] = l(:notice_email_error, e.message)
end end
ActionMailer::Base.raise_delivery_errors = raise_delivery_errors ActionMailer::Base.raise_delivery_errors = raise_delivery_errors
redirect_to settings_path(: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, User.default_admin_account_changed?], [:text_default_administrator_account_changed, 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?(Redmine::Plugin.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
+78 -399
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,69 +18,35 @@
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
include Redmine::Pagination
include RoutesHelper
helper :routes
class_attribute :accept_api_auth_actions
class_attribute :accept_rss_auth_actions
class_attribute :model_object
layout 'base' layout 'base'
protect_from_forgery # Remove broken cookie after upgrade from 0.8.x (#4292)
def handle_unverified_request # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
super # TODO: remove it when Rails is fixed
cookies.delete(autologin_cookie_name) before_filter :delete_broken_cookies
def delete_broken_cookies
if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
cookies.delete '_redmine_session'
redirect_to home_path
return false
end
end end
before_filter :session_expiration, :user_setup, :check_if_login_required, :check_password_change, :set_localization before_filter :user_setup, :check_if_login_required, :set_localization
filter_parameter_logging :password
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
rescue_from ::ActionView::MissingTemplate, :with => :missing_template
include Redmine::Search::Controller include Redmine::Search::Controller
include Redmine::MenuManager::MenuController include Redmine::MenuManager::MenuController
helper Redmine::MenuManager::MenuHelper helper Redmine::MenuManager::MenuHelper
def session_expiration REDMINE_SUPPORTED_SCM.each do |scm|
if session[:user_id] require_dependency "repository/#{scm.underscore}"
if session_expired? && !try_to_autologin
reset_session
flash[:error] = l(:error_session_expired)
redirect_to signin_url
else
session[:atime] = Time.now.utc.to_i
end
end
end
def session_expired?
if Setting.session_lifetime?
unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
return true
end
end
if Setting.session_timeout?
unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
return true
end
end
false
end
def start_user_session(user)
session[:user_id] = user.id
session[:ctime] = Time.now.utc.to_i
session[:atime] = Time.now.utc.to_i
if user.must_change_password?
session[:pwd] = '1'
end
end end
def user_setup def user_setup
@@ -88,65 +54,32 @@ class ApplicationController < ActionController::Base
Setting.check_cache Setting.check_cache
# Find the current user # Find the current user
User.current = find_current_user User.current = find_current_user
logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
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
user = nil if session[:user_id]
unless api_request? # existing session
if session[:user_id] (User.active.find(session[:user_id]) rescue nil)
# existing session elsif cookies[:autologin] && Setting.autologin?
user = (User.active.find(session[:user_id]) rescue nil) # auto-login feature starts a new session
elsif autologin_user = try_to_autologin user = User.try_to_autologin(cookies[:autologin])
user = autologin_user session[:user_id] = user.id if user
elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth? user
# RSS key authentication does not start a session elsif params[:format] == 'atom' && params[:key] && accept_key_auth_actions.include?(params[:action])
user = User.find_by_rss_key(params[:key]) # RSS key authentication does not start a session
end User.find_by_rss_key(params[:key])
end elsif Setting.rest_api_enabled? && ['xml', 'json'].include?(params[:format]) && accept_key_auth_actions.include?(params[:action])
if user.nil? && Setting.rest_api_enabled? && accept_api_auth? if params[:key].present?
if (key = api_key_from_request)
# Use API key # Use API key
user = User.find_by_api_key(key) User.find_by_api_key(params[:key])
else else
# HTTP Basic, either username/password or API key/random # HTTP Basic, either username/password or API key/random
authenticate_with_http_basic do |username, password| authenticate_with_http_basic do |username, password|
user = User.try_to_login(username, password) || User.find_by_api_key(username) User.try_to_login(username, password) || User.find_by_api_key(username)
end
if user && user.must_change_password?
render_error :message => 'You must change your password', :status => 403
return
end end
end end
# Switch user if requested by an admin user
if user && user.admin? && (username = api_switch_user_from_request)
su = User.find_by_login(username)
if su && su.active?
logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
user = su
else
render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
end
end
end
user
end
def autologin_cookie_name
Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
end
def try_to_autologin
if cookies[autologin_cookie_name] && Setting.autologin?
# auto-login feature starts a new session
user = User.try_to_autologin(cookies[autologin_cookie_name])
if user
reset_session
start_user_session(user)
end
user
end end
end end
@@ -155,21 +88,12 @@ class ApplicationController < ActionController::Base
reset_session reset_session
if user && user.is_a?(User) if user && user.is_a?(User)
User.current = user User.current = user
start_user_session(user) session[:user_id] = user.id
else else
User.current = User.anonymous User.current = User.anonymous
end end
end end
# Logs out current user
def logout_user
if User.current.logged?
cookies.delete(autologin_cookie_name)
Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
self.logged_user = nil
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
@@ -177,16 +101,6 @@ class ApplicationController < ActionController::Base
require_login if Setting.login_required? require_login if Setting.login_required?
end end
def check_password_change
if session[:pwd]
if User.current.must_change_password?
redirect_to my_password_path
else
session.delete(:pwd)
end
end
end
def set_localization def set_localization
lang = nil lang = nil
if User.current.logged? if User.current.logged?
@@ -212,17 +126,10 @@ class ApplicationController < ActionController::Base
url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id]) url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
end end
respond_to do |format| respond_to do |format|
format.html { format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
if request.xhr?
head :unauthorized
else
redirect_to :controller => "account", :action => "login", :back_url => url
end
}
format.atom { redirect_to :controller => "account", :action => "login", :back_url => url } format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' } format.xml { head :unauthorized }
format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' } format.json { head :unauthorized }
format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
end end
return false return false
end end
@@ -244,16 +151,8 @@ class ApplicationController < ActionController::Base
# Authorize the user for the requested action # Authorize the user for the requested action
def authorize(ctrl = params[:controller], action = params[:action], global = false) def authorize(ctrl = params[:controller], action = params[:action], global = false)
allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global) allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project, :global => global)
if allowed allowed ? true : deny_access
true
else
if @project && @project.archived?
render_403 :message => :notice_not_authorized_archived_project
else
deny_access
end
end
end end
# Authorize the user for the requested action outside a project # Authorize the user for the requested action outside a project
@@ -261,93 +160,14 @@ class ApplicationController < ActionController::Base
authorize(ctrl, action, global) authorize(ctrl, action, global)
end end
# Find project of id params[:id]
def find_project
@project = Project.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
# Find project of id params[:project_id]
def find_project_by_project_id
@project = Project.find(params[:project_id])
rescue ActiveRecord::RecordNotFound
render_404
end
# Find a project based on params[:project_id]
# TODO: some subclasses override this, see about merging their logic
def find_optional_project
@project = Project.find(params[:project_id]) unless params[:project_id].blank?
allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
allowed ? true : deny_access
rescue ActiveRecord::RecordNotFound
render_404
end
# Finds and sets @project based on @object.project
def find_project_from_association
render_404 unless @object.present?
@project = @object.project
end
def find_model_object
model = self.class.model_object
if model
@object = model.find(params[:id])
self.instance_variable_set('@' + controller_name.singularize, @object) if @object
end
rescue ActiveRecord::RecordNotFound
render_404
end
def self.model_object(model)
self.model_object = model
end
# Find the issue whose id is the :id parameter
# Raises a Unauthorized exception if the issue is not visible
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])
raise Unauthorized unless @issue.visible?
@project = @issue.project
rescue ActiveRecord::RecordNotFound
render_404
end
# Find issues with a single :id param or :ids array param
# Raises a Unauthorized exception if one of the issues is not visible
def find_issues
@issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
raise ActiveRecord::RecordNotFound if @issues.empty?
raise Unauthorized unless @issues.all?(&:visible?)
@projects = @issues.collect(&:project).compact.uniq
@project = @projects.first if @projects.size == 1
rescue ActiveRecord::RecordNotFound
render_404
end
def find_attachments
if (attachments = params[:attachments]).present?
att = attachments.values.collect do |attachment|
Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
end
att.compact!
end
@attachments = att || []
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
if @project && !@project.archived? if @project && @project.active?
if @project.visible? if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
true true
else else
deny_access User.current.logged? ? render_403 : require_login
end end
else else
@project = nil @project = nil
@@ -356,17 +176,9 @@ class ApplicationController < ActionController::Base
end end
end end
def back_url
url = params[:back_url]
if url.nil? && referer = request.env['HTTP_REFERER']
url = CGI.unescape(referer.to_s)
end
url
end
def redirect_back_or_default(default) def redirect_back_or_default(default)
back_url = params[:back_url].to_s back_url = CGI.unescape(params[:back_url].to_s)
if back_url.present? if !back_url.blank?
begin begin
uri = URI.parse(back_url) uri = URI.parse(back_url)
# do not redirect user to another host or to the login or register page # do not redirect user to another host or to the login or register page
@@ -375,85 +187,29 @@ class ApplicationController < ActionController::Base
return return
end end
rescue URI::InvalidURIError rescue URI::InvalidURIError
logger.warn("Could not redirect to invalid URL #{back_url}")
# redirect to default # redirect to default
end end
end end
redirect_to default redirect_to default
false
end end
# Redirects to the request referer if present, redirects to args or call block otherwise. def render_403
def redirect_to_referer_or(*args, &block)
redirect_to :back
rescue ::ActionController::RedirectBackError
if args.any?
redirect_to *args
elsif block_given?
block.call
else
raise "#redirect_to_referer_or takes arguments or a block"
end
end
def render_403(options={})
@project = nil @project = nil
render_error({:message => :notice_not_authorized, :status => 403}.merge(options)) render :template => "common/403", :layout => (request.xhr? ? false : 'base'), :status => 403
return false return false
end end
def render_404(options={}) def render_404
render_error({:message => :notice_file_not_found, :status => 404}.merge(options)) render :template => "common/404", :layout => !request.xhr?, :status => 404
return false return false
end end
# Renders an error response def render_error(msg)
def render_error(arg) flash.now[:error] = msg
arg = {:message => arg} unless arg.is_a?(Hash) render :text => '', :layout => !request.xhr?, :status => 500
@message = arg[:message]
@message = l(@message) if @message.is_a?(Symbol)
@status = arg[:status] || 500
respond_to do |format|
format.html {
render :template => 'common/error', :layout => use_layout, :status => @status
}
format.any { head @status }
end
end
# Handler for ActionView::MissingTemplate exception
def missing_template
logger.warn "Missing template, responding with 404"
@project = nil
render_404
end
# Filter for actions that provide an API response
# but have no HTML representation for non admin users
def require_admin_or_api_request
return true if api_request?
if User.current.admin?
true
elsif User.current.logged?
render_error(:status => 406)
else
deny_access
end
end
# Picks which layout to use based on the request
#
# @return [boolean, string] name of the layout to use or false for no layout
def use_layout
request.xhr? ? false : 'base'
end end
def invalid_authenticity_token def invalid_authenticity_token
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)."
end
render_error "Invalid form authenticity token." render_error "Invalid form authenticity token."
end end
@@ -462,32 +218,37 @@ class ApplicationController < ActionController::Base
@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)
@title = options[:title] || Setting.app_title @title = options[:title] || Setting.app_title
render :template => "common/feed", :formats => [:atom], :layout => false, render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
:content_type => 'application/atom+xml'
end end
def self.accept_rss_auth(*actions) def self.accept_key_auth(*actions)
if actions.any? actions = actions.flatten.map(&:to_s)
self.accept_rss_auth_actions = actions write_inheritable_attribute('accept_key_auth_actions', actions)
else end
self.accept_rss_auth_actions || []
def accept_key_auth_actions
self.class.read_inheritable_attribute('accept_key_auth_actions') || []
end
# TODO: move to model
def attach_files(obj, attachments)
attached = []
unsaved = []
if attachments && attachments.is_a?(Hash)
attachments.each_value do |attachment|
file = attachment['file']
next unless file && file.size > 0
a = Attachment.create(:container => obj,
:file => file,
:description => attachment['description'].to_s.strip,
:author => User.current)
a.new_record? ? (unsaved << a) : (attached << a)
end
if unsaved.any?
flash[:warning] = l(:warning_attachments_not_saved, unsaved.size)
end
end end
end attached
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?
self.accept_api_auth_actions = actions
else
self.accept_api_auth_actions || []
end
end
def accept_api_auth?(action=action_name)
self.class.accept_api_auth.include?(action.to_sym)
end end
# Returns the number of objects that should be displayed # Returns the number of objects that should be displayed
@@ -505,30 +266,6 @@ class ApplicationController < ActionController::Base
per_page per_page
end end
# Returns offset and limit used to retrieve objects
# for an API response based on offset, limit and page parameters
def api_offset_and_limit(options=params)
if options[:offset].present?
offset = options[:offset].to_i
if offset < 0
offset = 0
end
end
limit = options[:limit].to_i
if limit < 1
limit = 25
elsif limit > 100
limit = 100
end
if offset.nil? && options[:page].present?
offset = (options[:page].to_i - 1) * limit
offset = 0 if offset < 0
end
offset ||= 0
[offset, limit]
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)
@@ -554,62 +291,4 @@ class ApplicationController < ActionController::Base
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?
%w(xml json).include? params[:format]
end
# Returns the API key present in the request
def api_key_from_request
if params[:key].present?
params[:key].to_s
elsif request.headers["X-Redmine-API-Key"].present?
request.headers["X-Redmine-API-Key"].to_s
end
end
# Returns the API 'switch user' value if present
def api_switch_user_from_request
request.headers["X-Redmine-Switch-User"].to_s.presence
end
# Renders a warning flash if obj has unsaved attachments
def render_attachment_warning_if_needed(obj)
flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
end
# Rescues an invalid query statement. Just in case...
def query_statement_invalid(exception)
logger.error "Query::StatementInvalid: #{exception.message}" if logger
session.delete(:query)
sort_clear if respond_to?(:sort_clear)
render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
end
# Renders a 200 response for successfull updates or deletions via the API
def render_api_ok
render_api_head :ok
end
# Renders a head API response
def render_api_head(status)
# #head would return a response body with one space
render :text => '', :status => status, :layout => nil
end
# Renders API response on validation failure
def render_validation_errors(objects)
if objects.is_a?(Array)
@error_messages = objects.map {|object| object.errors.full_messages}.flatten
else
@error_messages = objects.errors.full_messages
end
render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
end
# Overrides #_include_layout? so that #render with no arguments
# doesn't use the layout for api requests
def _include_layout?(*args)
api_request? ? false : super
end
end end
+22 -89
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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,34 +16,21 @@
# 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 AttachmentsController < ApplicationController class AttachmentsController < ApplicationController
before_filter :find_project, :except => :upload before_filter :find_project
before_filter :file_readable, :read_authorize, :only => [:show, :download, :thumbnail] before_filter :file_readable, :read_authorize, :except => :destroy
before_filter :delete_authorize, :only => :destroy before_filter :delete_authorize, :only => :destroy
before_filter :authorize_global, :only => :upload
accept_api_auth :show, :download, :upload verify :method => :post, :only => :destroy
def show def show
respond_to do |format| if @attachment.is_diff?
format.html { @diff = File.new(@attachment.diskfile, "rb").read
if @attachment.is_diff? render :action => 'diff'
@diff = File.new(@attachment.diskfile, "rb").read elsif @attachment.is_text? && @attachment.filesize <= Setting.file_max_size_displayed.to_i.kilobyte
@diff_type = params[:type] || User.current.pref[:diff_type] || 'inline' @content = File.new(@attachment.diskfile, "rb").read
@diff_type = 'inline' unless %w(inline sbs).include?(@diff_type) render :action => 'file'
# Save diff type as user preference else
if User.current.logged? && @diff_type != User.current.pref[:diff_type] download
User.current.pref[:diff_type] = @diff_type
User.current.preference.save
end
render :action => 'diff'
elsif @attachment.is_text? && @attachment.filesize <= Setting.file_max_size_displayed.to_i.kilobyte
@content = File.new(@attachment.diskfile, "rb").read
render :action => 'file'
else
download
end
}
format.api
end end
end end
@@ -52,68 +39,19 @@ class AttachmentsController < ApplicationController
@attachment.increment_download @attachment.increment_download
end end
if stale?(:etag => @attachment.digest) # 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 thumbnail
if @attachment.thumbnailable? && thumbnail = @attachment.thumbnail(:size => params[:size])
if stale?(:etag => thumbnail)
send_file thumbnail,
:filename => filename_for_content_disposition(@attachment.filename),
:type => detect_content_type(@attachment),
:disposition => 'inline'
end
else
# No thumbnail for the attachment or thumbnail could not be created
render :nothing => true, :status => 404
end
end
def upload
# Make sure that API users get used to set this content type
# as it won't trigger Rails' automatic parsing of the request body for parameters
unless request.content_type == 'application/octet-stream'
render :nothing => true, :status => 406
return
end
@attachment = Attachment.new(:file => request.raw_post)
@attachment.author = User.current
@attachment.filename = params[:filename].presence || Redmine::Utils.random_hex(16)
saved = @attachment.save
respond_to do |format|
format.js
format.api {
if saved
render :action => 'upload', :status => :created
else
render_validation_errors(@attachment)
end
}
end
end end
def destroy def destroy
if @attachment.container.respond_to?(:init_journal) # Make sure association callbacks are called
@attachment.container.init_journal(User.current) @attachment.container.attachments.delete(@attachment)
end redirect_to :back
if @attachment.container rescue ::ActionController::RedirectBackError
# Make sure association callbacks are called redirect_to :controller => 'projects', :action => 'show', :id => @project
@attachment.container.attachments.delete(@attachment)
else
@attachment.destroy
end
respond_to do |format|
format.html { redirect_to_referer_or project_path(@project) }
format.js
end
end end
private private
@@ -128,12 +66,7 @@ private
# Checks that the file exists and is readable # Checks that the file exists and is readable
def file_readable def file_readable
if @attachment.readable? @attachment.readable? ? true : render_404
true
else
logger.error "Cannot send attachment, #{@attachment.diskfile} does not exist or is unreadable."
render_404
end
end end
def read_authorize def read_authorize
+27 -39
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,80 +17,68 @@
class AuthSourcesController < ApplicationController class AuthSourcesController < ApplicationController
layout 'admin' layout 'admin'
menu_item :ldap_authentication
before_filter :require_admin before_filter :require_admin
before_filter :find_auth_source, :only => [:edit, :update, :test_connection, :destroy]
def index def index
@auth_source_pages, @auth_sources = paginate AuthSource, :per_page => 25 list
render :action => 'list' unless request.xhr?
end
# GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
verify :method => :post, :only => [ :destroy, :create, :update ],
:redirect_to => { :action => :list }
def list
@auth_source_pages, @auth_sources = paginate :auth_sources, :per_page => 10
render :action => "list", :layout => false if request.xhr?
end end
def new def new
klass_name = params[:type] || 'AuthSourceLdap' @auth_source = AuthSourceLdap.new
@auth_source = AuthSource.new_subclass_instance(klass_name, params[:auth_source])
render_404 unless @auth_source
end end
def create def create
@auth_source = AuthSource.new_subclass_instance(params[:type], params[:auth_source]) @auth_source = AuthSourceLdap.new(params[:auth_source])
if @auth_source.save if @auth_source.save
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to auth_sources_path redirect_to :action => 'list'
else else
render :action => 'new' render :action => 'new'
end end
end end
def edit def edit
@auth_source = AuthSource.find(params[:id])
end end
def update def update
@auth_source = AuthSource.find(params[:id])
if @auth_source.update_attributes(params[:auth_source]) if @auth_source.update_attributes(params[:auth_source])
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to auth_sources_path redirect_to :action => 'list'
else else
render :action => 'edit' render :action => 'edit'
end end
end end
def test_connection def test_connection
@auth_method = AuthSource.find(params[:id])
begin begin
@auth_source.test_connection @auth_method.test_connection
flash[:notice] = l(:notice_successful_connection) flash[:notice] = l(:notice_successful_connection)
rescue Exception => e rescue => text
flash[:error] = l(:error_unable_to_connect, e.message) flash[:error] = "Unable to connect (#{text})"
end end
redirect_to auth_sources_path redirect_to :action => 'list'
end end
def destroy def destroy
unless @auth_source.users.exists? @auth_source = AuthSource.find(params[:id])
unless @auth_source.users.find(:first)
@auth_source.destroy @auth_source.destroy
flash[:notice] = l(:notice_successful_delete) flash[:notice] = l(:notice_successful_delete)
end end
redirect_to auth_sources_path redirect_to :action => 'list'
end
def autocomplete_for_new_user
results = AuthSource.search(params[:term])
render :json => results.map {|result| {
'value' => result[:login],
'label' => "#{result[:login]} (#{result[:firstname]} #{result[:lastname]})",
'login' => result[:login].to_s,
'firstname' => result[:firstname].to_s,
'lastname' => result[:lastname].to_s,
'mail' => result[:mail].to_s,
'auth_source_id' => result[:auth_source_id].to_s
}}
end
private
def find_auth_source
@auth_source = AuthSource.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end end
end end
@@ -1,44 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2013 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 AutoCompletesController < ApplicationController
before_filter :find_project
def issues
@issues = []
q = (params[:q] || params[:term]).to_s.strip
if q.present?
scope = (params[:scope] == "all" || @project.nil? ? Issue : @project.issues).visible
if q.match(/\A#?(\d+)\z/)
@issues << scope.find_by_id($1.to_i)
end
@issues += scope.where("LOWER(#{Issue.table_name}.subject) LIKE LOWER(?)", "%#{q}%").order("#{Issue.table_name}.id DESC").limit(10).all
@issues.compact!
end
render :layout => false
end
private
def find_project
if params[:project_id].present?
@project = Project.find(params[:project_id])
end
rescue ActiveRecord::RecordNotFound
render_404
end
end
+29 -47
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,15 +17,17 @@
class BoardsController < ApplicationController class BoardsController < ApplicationController
default_search_scope :messages default_search_scope :messages
before_filter :find_project_by_project_id, :find_board_if_available, :authorize before_filter :find_project, :authorize
accept_rss_auth :index, :show
helper :messages
include MessagesHelper
helper :sort helper :sort
include SortHelper include SortHelper
helper :watchers helper :watchers
include WatchersHelper
def index def index
@boards = @project.boards.includes(:project, :last_message => :author).all @boards = @project.boards
# show the board if there is only one # show the board if there is only one
if @boards.size == 1 if @boards.size == 1
@board = @boards.first @board = @boards.first
@@ -37,73 +39,53 @@ class BoardsController < ApplicationController
respond_to do |format| respond_to do |format|
format.html { format.html {
sort_init 'updated_on', 'desc' sort_init 'updated_on', 'desc'
sort_update 'created_on' => "#{Message.table_name}.created_on", sort_update 'created_on' => "#{Message.table_name}.created_on",
'replies' => "#{Message.table_name}.replies_count", 'replies' => "#{Message.table_name}.replies_count",
'updated_on' => "COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on)" 'updated_on' => "#{Message.table_name}.updated_on"
@topic_count = @board.topics.count @topic_count = @board.topics.count
@topic_pages = Paginator.new @topic_count, per_page_option, params['page'] @topic_pages = Paginator.new self, @topic_count, per_page_option, params['page']
@topics = @board.topics. @topics = @board.topics.find :all, :order => ["#{Message.table_name}.sticky DESC", sort_clause].compact.join(', '),
reorder("#{Message.table_name}.sticky DESC"). :include => [:author, {:last_reply => :author}],
includes(:last_reply). :limit => @topic_pages.items_per_page,
limit(@topic_pages.per_page). :offset => @topic_pages.current.offset
offset(@topic_pages.offset). @message = Message.new
order(sort_clause).
preload(:author, {:last_reply => :author}).
all
@message = Message.new(:board => @board)
render :action => 'show', :layout => !request.xhr? render :action => 'show', :layout => !request.xhr?
} }
format.atom { format.atom {
@messages = @board.messages. @messages = @board.messages.find :all, :order => 'created_on DESC',
reorder('created_on DESC'). :include => [:author, :board],
includes(:author, :board). :limit => Setting.feeds_limit.to_i
limit(Setting.feeds_limit.to_i).
all
render_feed(@messages, :title => "#{@project}: #{@board}") render_feed(@messages, :title => "#{@project}: #{@board}")
} }
end end
end end
def new verify :method => :post, :only => [ :destroy ], :redirect_to => { :action => :index }
@board = @project.boards.build
@board.safe_attributes = params[:board]
end
def create def new
@board = @project.boards.build @board = Board.new(params[:board])
@board.safe_attributes = params[:board] @board.project = @project
if @board.save if request.post? && @board.save
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to_settings_in_projects redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'boards'
else
render :action => 'new'
end end
end end
def edit def edit
end if request.post? && @board.update_attributes(params[:board])
redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'boards'
def update
@board.safe_attributes = params[:board]
if @board.save
redirect_to_settings_in_projects
else
render :action => 'edit'
end end
end end
def destroy def destroy
@board.destroy @board.destroy
redirect_to_settings_in_projects redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'boards'
end end
private private
def redirect_to_settings_in_projects def find_project
redirect_to settings_project_path(@project, :tab => 'boards') @project = Project.find(params[:project_id])
end
def find_board_if_available
@board = @project.boards.find(params[:id]) if params[:id] @board = @project.boards.find(params[:id]) if params[:id]
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
-56
View File
@@ -1,56 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2013 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
menu_item :calendar
before_filter :find_optional_project
rescue_from Query::StatementInvalid, :with => :query_statement_invalid
helper :issues
helper :projects
helper :queries
include QueriesHelper
helper :sort
include SortHelper
def show
if params[:year] and params[:year].to_i > 1900
@year = params[:year].to_i
if params[:month] and params[:month].to_i > 0 and params[:month].to_i < 13
@month = params[:month].to_i
end
end
@year ||= Date.today.year
@month ||= Date.today.month
@calendar = Redmine::Helpers::Calendar.new(Date.civil(@year, @month, 1), current_language, :month)
retrieve_query
@query.group_by = nil
if @query.valid?
events = []
events += @query.issues(:include => [:tracker, :assigned_to, :priority],
:conditions => ["((start_date BETWEEN ? AND ?) OR (due_date BETWEEN ? AND ?))", @calendar.startdt, @calendar.enddt, @calendar.startdt, @calendar.enddt]
)
events += @query.versions(:conditions => ["effective_date BETWEEN ? AND ?", @calendar.startdt, @calendar.enddt])
@calendar.events = events
end
render :action => 'show', :layout => false if request.xhr?
end
end
-53
View File
@@ -1,53 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2013 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 CommentsController < ApplicationController
default_search_scope :news
model_object News
before_filter :find_model_object
before_filter :find_project_from_association
before_filter :authorize
def create
raise Unauthorized unless @news.commentable?
@comment = Comment.new
@comment.safe_attributes = params[:comment]
@comment.author = User.current
if @news.comments << @comment
flash[:notice] = l(:label_comment_added)
end
redirect_to news_path(@news)
end
def destroy
@news.comments.find(params[:comment_id]).destroy
redirect_to news_path(@news)
end
private
# ApplicationController's find_model_object sets it based on the controller
# name so it needs to be overriden and set to @news instead
def find_model_object
super
@news = @object
@comment = nil
@news
end
end
@@ -1,86 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2013 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 ContextMenusController < ApplicationController
helper :watchers
helper :issues
before_filter :find_issues, :only => :issues
def issues
if (@issues.size == 1)
@issue = @issues.first
end
@issue_ids = @issues.map(&:id).sort
@allowed_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
@can = {:edit => User.current.allowed_to?(:edit_issues, @projects),
:log_time => (@project && User.current.allowed_to?(:log_time, @project)),
:update => (User.current.allowed_to?(:edit_issues, @projects) || (User.current.allowed_to?(:change_status, @projects) && !@allowed_statuses.blank?)),
:move => (@project && User.current.allowed_to?(:move_issues, @project)),
:copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
:delete => User.current.allowed_to?(:delete_issues, @projects)
}
if @project
if @issue
@assignables = @issue.assignable_users
else
@assignables = @project.assignable_users
end
@trackers = @project.trackers
else
#when multiple projects, we only keep the intersection of each set
@assignables = @projects.map(&:assignable_users).reduce(:&)
@trackers = @projects.map(&:trackers).reduce(:&)
end
@versions = @projects.map {|p| p.shared_versions.open}.reduce(:&)
@priorities = IssuePriority.active.reverse
@back = back_url
@options_by_custom_field = {}
if @can[:edit]
custom_fields = @issues.map(&:available_custom_fields).reduce(:&).select do |f|
%w(bool list user version).include?(f.field_format) && !f.multiple?
end
custom_fields.each do |field|
values = field.possible_values_options(@projects)
if values.any?
@options_by_custom_field[field] = values
end
end
end
@safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
render :layout => false
end
def time_entries
@time_entries = TimeEntry.where(:id => params[:ids]).preload(:project).to_a
(render_404; return) unless @time_entries.present?
@projects = @time_entries.collect(&:project).compact.uniq
@project = @projects.first if @projects.size == 1
@activities = TimeEntryActivity.shared.active
@can = {:edit => User.current.allowed_to?(:edit_time_entries, @projects),
:delete => User.current.allowed_to?(:edit_time_entries, @projects)
}
@back = back_url
render :layout => false
end
end
+22 -49
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -19,71 +19,44 @@ class CustomFieldsController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin before_filter :require_admin
before_filter :build_new_custom_field, :only => [:new, :create]
before_filter :find_custom_field, :only => [:edit, :update, :destroy]
accept_api_auth :index
def index def index
respond_to do |format| @custom_fields_by_type = CustomField.find(:all).group_by {|f| f.class.name }
format.html { @tab = params[:tab] || 'IssueCustomField'
@custom_fields_by_type = CustomField.all.group_by {|f| f.class.name }
@tab = params[:tab] || 'IssueCustomField'
}
format.api {
@custom_fields = CustomField.all
}
end
end end
def new def new
end @custom_field = begin
if params[:type].to_s.match(/.+CustomField$/)
params[:type].to_s.constantize.new(params[:custom_field])
end
rescue
end
(redirect_to(:action => 'index'); return) unless @custom_field.is_a?(CustomField)
def create if request.post? and @custom_field.save
if @custom_field.save
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 custom_fields_path(:tab => @custom_field.class.name) redirect_to :action => 'index', :tab => @custom_field.class.name
else
render :action => 'new'
end end
@trackers = Tracker.find(:all, :order => 'position')
end end
def edit def edit
end @custom_field = CustomField.find(params[:id])
if request.post? and @custom_field.update_attributes(params[:custom_field])
def update
if @custom_field.update_attributes(params[:custom_field])
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 custom_fields_path(:tab => @custom_field.class.name) redirect_to :action => 'index', :tab => @custom_field.class.name
else
render :action => 'edit'
end end
@trackers = Tracker.find(:all, :order => 'position')
end end
def destroy def destroy
begin @custom_field = CustomField.find(params[:id]).destroy
@custom_field.destroy redirect_to :action => 'index', :tab => @custom_field.class.name
rescue rescue
flash[:error] = l(:error_can_not_delete_custom_field) flash[:error] = "Unable to delete custom field"
end redirect_to :action => 'index'
redirect_to custom_fields_path(:tab => @custom_field.class.name)
end
private
def build_new_custom_field
@custom_field = CustomField.new_subclass_instance(params[:type], params[:custom_field])
if @custom_field.nil?
render_404
else
@custom_field.default_value = nil
end
end
def find_custom_field
@custom_field = CustomField.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end end
end end
+31 -37
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,17 +17,15 @@
class DocumentsController < ApplicationController class DocumentsController < ApplicationController
default_search_scope :documents default_search_scope :documents
model_object Document before_filter :find_project, :only => [:index, :new]
before_filter :find_project_by_project_id, :only => [:index, :new, :create] before_filter :find_document, :except => [:index, :new]
before_filter :find_model_object, :except => [:index, :new, :create]
before_filter :find_project_from_association, :except => [:index, :new, :create]
before_filter :authorize before_filter :authorize
helper :attachments helper :attachments
def index def index
@sort_by = %w(category date title author).include?(params[:sort_by]) ? params[:sort_by] : 'category' @sort_by = %w(category date title author).include?(params[:sort_by]) ? params[:sort_by] : 'category'
documents = @project.documents.includes(:attachments, :category).all documents = @project.documents.find :all, :include => [:attachments, :category]
case @sort_by case @sort_by
when 'date' when 'date'
@grouped = documents.group_by {|d| d.updated_on.to_date } @grouped = documents.group_by {|d| d.updated_on.to_date }
@@ -43,52 +41,48 @@ class DocumentsController < ApplicationController
end end
def show def show
@attachments = @document.attachments.all @attachments = @document.attachments.find(:all, :order => "created_on DESC")
end end
def new def new
@document = @project.documents.build @document = @project.documents.build(params[:document])
@document.safe_attributes = params[:document] if request.post? and @document.save
end attach_files(@document, params[:attachments])
def create
@document = @project.documents.build
@document.safe_attributes = params[:document]
@document.save_attachments(params[:attachments])
if @document.save
render_attachment_warning_if_needed(@document)
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to project_documents_path(@project) redirect_to :action => 'index', :project_id => @project
else
render :action => 'new'
end end
end end
def edit def edit
end @categories = DocumentCategory.all
if request.post? and @document.update_attributes(params[:document])
def update
@document.safe_attributes = params[:document]
if request.put? and @document.save
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to document_path(@document) redirect_to :action => 'show', :id => @document
else
render :action => 'edit'
end end
end end
def destroy def destroy
@document.destroy if request.delete? @document.destroy
redirect_to project_documents_path(@project) redirect_to :controller => 'documents', :action => 'index', :project_id => @project
end end
def add_attachment def add_attachment
attachments = Attachment.attach_files(@document, params[:attachments]) attachments = attach_files(@document, params[:attachments])
render_attachment_warning_if_needed(@document) Mailer.deliver_attachments_added(attachments) if !attachments.empty? && Setting.notified_events.include?('document_added')
redirect_to :action => 'show', :id => @document
end
if attachments.present? && attachments[:files].present? && Setting.notified_events.include?('document_added') private
Mailer.attachments_added(attachments[:files]).deliver def find_project
end @project = Project.find(params[:project_id])
redirect_to document_path(@document) rescue ActiveRecord::RecordNotFound
render_404
end
def find_document
@document = Document.find(params[:id])
@project = @document.project
rescue ActiveRecord::RecordNotFound
render_404
end end
end end
+38 -45
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -18,79 +18,72 @@
class EnumerationsController < ApplicationController class EnumerationsController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin, :except => :index before_filter :require_admin
before_filter :require_admin_or_api_request, :only => :index
before_filter :build_new_enumeration, :only => [:new, :create]
before_filter :find_enumeration, :only => [:edit, :update, :destroy]
accept_api_auth :index
helper :custom_fields helper :custom_fields
include CustomFieldsHelper
def index def index
respond_to do |format| list
format.html render :action => 'list'
format.api { end
@klass = Enumeration.get_subclass(params[:type])
if @klass # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
@enumerations = @klass.shared.sorted.all verify :method => :post, :only => [ :destroy, :create, :update ],
else :redirect_to => { :action => :list }
render_404
end def list
}
end
end end
def new def new
begin
@enumeration = params[:type].constantize.new
rescue NameError
@enumeration = Enumeration.new
end
end end
def create def create
if request.post? && @enumeration.save @enumeration = Enumeration.new(params[:enumeration])
@enumeration.type = params[:enumeration][:type]
if @enumeration.save
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to enumerations_path redirect_to :action => 'list', :type => @enumeration.type
else else
render :action => 'new' render :action => 'new'
end end
end end
def edit def edit
@enumeration = Enumeration.find(params[:id])
end end
def update def update
if request.put? && @enumeration.update_attributes(params[:enumeration]) @enumeration = Enumeration.find(params[:id])
@enumeration.type = params[:enumeration][:type] if params[:enumeration][:type]
if @enumeration.update_attributes(params[:enumeration])
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to enumerations_path redirect_to :action => 'list', :type => @enumeration.type
else else
render :action => 'edit' render :action => 'edit'
end end
end end
def destroy def destroy
@enumeration = Enumeration.find(params[:id])
if !@enumeration.in_use? if !@enumeration.in_use?
# No associated objects # No associated objects
@enumeration.destroy @enumeration.destroy
redirect_to enumerations_path redirect_to :action => 'index'
return elsif params[:reassign_to_id]
elsif params[:reassign_to_id].present? && (reassign_to = @enumeration.class.find_by_id(params[:reassign_to_id].to_i)) if reassign_to = @enumeration.class.find_by_id(params[:reassign_to_id])
@enumeration.destroy(reassign_to) @enumeration.destroy(reassign_to)
redirect_to enumerations_path redirect_to :action => 'index'
return end
end end
@enumerations = @enumeration.class.system.all - [@enumeration] @enumerations = @enumeration.class.find(:all) - [@enumeration]
end #rescue
# flash[:error] = 'Unable to delete enumeration'
private # redirect_to :action => 'index'
def build_new_enumeration
class_name = params[:enumeration] && params[:enumeration][:type] || params[:type]
@enumeration = Enumeration.new_subclass_instance(class_name, params[:enumeration])
if @enumeration.nil?
render_404
end
end
def find_enumeration
@enumeration = Enumeration.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end end
end end
-53
View File
@@ -1,53 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2013 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 FilesController < ApplicationController
menu_item :files
before_filter :find_project_by_project_id
before_filter :authorize
helper :sort
include SortHelper
def index
sort_init 'filename', 'asc'
sort_update 'filename' => "#{Attachment.table_name}.filename",
'created_on' => "#{Attachment.table_name}.created_on",
'size' => "#{Attachment.table_name}.filesize",
'downloads' => "#{Attachment.table_name}.downloads"
@containers = [ Project.includes(:attachments).reorder(sort_clause).find(@project.id)]
@containers += @project.versions.includes(:attachments).reorder(sort_clause).all.sort.reverse
render :layout => !request.xhr?
end
def new
@versions = @project.versions.sort
end
def create
container = (params[:version_id].blank? ? @project : @project.versions.find_by_id(params[:version_id]))
attachments = Attachment.attach_files(container, params[:attachments])
render_attachment_warning_if_needed(container)
if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added')
Mailer.attachments_added(attachments[:files]).deliver
end
redirect_to project_files_path(@project)
end
end
-48
View File
@@ -1,48 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2013 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
menu_item :gantt
before_filter :find_optional_project
rescue_from Query::StatementInvalid, :with => :query_statement_invalid
helper :gantt
helper :issues
helper :projects
helper :queries
include QueriesHelper
helper :sort
include SortHelper
include Redmine::Export::PDF
def show
@gantt = Redmine::Helpers::Gantt.new(params)
@gantt.project = @project
retrieve_query
@query.group_by = nil
@gantt.query = @query if @query.valid?
basename = (@project ? "#{@project.identifier}-" : '') + 'gantt'
respond_to do |format|
format.html { render :action => "show", :layout => !request.xhr? }
format.png { send_data(@gantt.to_image, :disposition => 'inline', :type => 'image/png', :filename => "#{basename}.png") } if @gantt.respond_to?('to_image')
format.pdf { send_data(@gantt.to_pdf, :type => 'application/pdf', :filename => "#{basename}.pdf") }
end
end
end
+73 -51
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -19,123 +19,145 @@ class GroupsController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin before_filter :require_admin
before_filter :find_group, :except => [:index, :new, :create]
accept_api_auth :index, :show, :create, :update, :destroy, :add_users, :remove_user
helper :custom_fields helper :custom_fields
# GET /groups
# GET /groups.xml
def index def index
@groups = Group.sorted.all @groups = Group.find(:all, :order => 'lastname')
respond_to do |format| respond_to do |format|
format.html format.html # index.html.erb
format.api format.xml { render :xml => @groups }
end end
end end
# GET /groups/1
# GET /groups/1.xml
def show def show
@group = Group.find(params[:id])
respond_to do |format| respond_to do |format|
format.html format.html # show.html.erb
format.api format.xml { render :xml => @group }
end end
end end
# GET /groups/new
# GET /groups/new.xml
def new def new
@group = Group.new @group = Group.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @group }
end
end end
# GET /groups/1/edit
def edit
@group = Group.find(params[:id])
end
# POST /groups
# POST /groups.xml
def create def create
@group = Group.new @group = Group.new(params[:group])
@group.safe_attributes = params[:group]
respond_to do |format| respond_to do |format|
if @group.save if @group.save
format.html { flash[:notice] = l(:notice_successful_create)
flash[:notice] = l(:notice_successful_create) format.html { redirect_to(groups_path) }
redirect_to(params[:continue] ? new_group_path : groups_path) format.xml { render :xml => @group, :status => :created, :location => @group }
}
format.api { render :action => 'show', :status => :created, :location => group_url(@group) }
else else
format.html { render :action => "new" } format.html { render :action => "new" }
format.api { render_validation_errors(@group) } format.xml { render :xml => @group.errors, :status => :unprocessable_entity }
end end
end end
end end
def edit # PUT /groups/1
end # PUT /groups/1.xml
def update def update
@group.safe_attributes = params[:group] @group = Group.find(params[:id])
respond_to do |format| respond_to do |format|
if @group.save if @group.update_attributes(params[:group])
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
format.html { redirect_to(groups_path) } format.html { redirect_to(groups_path) }
format.api { render_api_ok } format.xml { head :ok }
else else
format.html { render :action => "edit" } format.html { render :action => "edit" }
format.api { render_validation_errors(@group) } format.xml { render :xml => @group.errors, :status => :unprocessable_entity }
end end
end end
end end
# DELETE /groups/1
# DELETE /groups/1.xml
def destroy def destroy
@group = Group.find(params[:id])
@group.destroy @group.destroy
respond_to do |format| respond_to do |format|
format.html { redirect_to(groups_path) } format.html { redirect_to(groups_url) }
format.api { render_api_ok } format.xml { head :ok }
end end
end end
def add_users def add_users
@users = User.find_all_by_id(params[:user_id] || params[:user_ids]) @group = Group.find(params[:id])
@group.users << @users if request.post? users = User.find_all_by_id(params[:user_ids])
@group.users << users if request.post?
respond_to do |format| respond_to do |format|
format.html { redirect_to edit_group_path(@group, :tab => 'users') } format.html { redirect_to :controller => 'groups', :action => 'edit', :id => @group, :tab => 'users' }
format.js format.js {
format.api { render_api_ok } render(:update) {|page|
page.replace_html "tab-content-users", :partial => 'groups/users'
users.each {|user| page.visual_effect(:highlight, "user-#{user.id}") }
}
}
end end
end end
def remove_user def remove_user
@group.users.delete(User.find(params[:user_id])) if request.delete? @group = Group.find(params[:id])
@group.users.delete(User.find(params[:user_id])) if request.post?
respond_to do |format| respond_to do |format|
format.html { redirect_to edit_group_path(@group, :tab => 'users') } format.html { redirect_to :controller => 'groups', :action => 'edit', :id => @group, :tab => 'users' }
format.js format.js { render(:update) {|page| page.replace_html "tab-content-users", :partial => 'groups/users'} }
format.api { render_api_ok }
end end
end end
def autocomplete_for_user def autocomplete_for_user
respond_to do |format| @group = Group.find(params[:id])
format.js @users = User.active.like(params[:q]).find(:all, :limit => 100) - @group.users
end render :layout => false
end end
def edit_membership def edit_membership
@membership = Member.edit_membership(params[:membership_id], params[:membership], @group) @group = Group.find(params[:id])
@membership = params[:membership_id] ? Member.find(params[:membership_id]) : Member.new(:principal => @group)
@membership.attributes = params[:membership]
@membership.save if request.post? @membership.save if request.post?
respond_to do |format| respond_to do |format|
format.html { redirect_to edit_group_path(@group, :tab => 'memberships') } format.html { redirect_to :controller => 'groups', :action => 'edit', :id => @group, :tab => 'memberships' }
format.js format.js {
end render(:update) {|page|
page.replace_html "tab-content-memberships", :partial => 'groups/memberships'
page.visual_effect(:highlight, "member-#{@membership.id}")
}
}
end
end end
def destroy_membership def destroy_membership
@group = Group.find(params[:id])
Member.find(params[:membership_id]).destroy if request.post? Member.find(params[:membership_id]).destroy if request.post?
respond_to do |format| respond_to do |format|
format.html { redirect_to edit_group_path(@group, :tab => 'memberships') } format.html { redirect_to :controller => 'groups', :action => 'edit', :id => @group, :tab => 'memberships' }
format.js format.js { render(:update) {|page| page.replace_html "tab-content-memberships", :partial => 'groups/memberships'} }
end end
end end
private
def find_group
@group = Group.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
end end
+20 -90
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,106 +17,36 @@
class IssueCategoriesController < ApplicationController class IssueCategoriesController < ApplicationController
menu_item :settings menu_item :settings
model_object IssueCategory before_filter :find_project, :authorize
before_filter :find_model_object, :except => [:index, :new, :create]
before_filter :find_project_from_association, :except => [:index, :new, :create]
before_filter :find_project_by_project_id, :only => [:index, :new, :create]
before_filter :authorize
accept_api_auth :index, :show, :create, :update, :destroy
def index verify :method => :post, :only => :destroy
respond_to do |format|
format.html { redirect_to_settings_in_projects }
format.api { @categories = @project.issue_categories.all }
end
end
def show
respond_to do |format|
format.html { redirect_to_settings_in_projects }
format.api
end
end
def new
@category = @project.issue_categories.build
@category.safe_attributes = params[:issue_category]
respond_to do |format|
format.html
format.js
end
end
def create
@category = @project.issue_categories.build
@category.safe_attributes = params[:issue_category]
if @category.save
respond_to do |format|
format.html do
flash[:notice] = l(:notice_successful_create)
redirect_to_settings_in_projects
end
format.js
format.api { render :action => 'show', :status => :created, :location => issue_category_path(@category) }
end
else
respond_to do |format|
format.html { render :action => 'new'}
format.js { render :action => 'new'}
format.api { render_validation_errors(@category) }
end
end
end
def edit def edit
end if request.post? and @category.update_attributes(params[:category])
flash[:notice] = l(:notice_successful_update)
def update redirect_to :controller => 'projects', :action => 'settings', :tab => 'categories', :id => @project
@category.safe_attributes = params[:issue_category]
if @category.save
respond_to do |format|
format.html {
flash[:notice] = l(:notice_successful_update)
redirect_to_settings_in_projects
}
format.api { render_api_ok }
end
else
respond_to do |format|
format.html { render :action => 'edit' }
format.api { render_validation_errors(@category) }
end
end end
end end
def destroy def destroy
@issue_count = @category.issues.size @issue_count = @category.issues.size
if @issue_count == 0 || params[:todo] || api_request? if @issue_count == 0
reassign_to = nil # No issue assigned to this category
if params[:reassign_to_id] && (params[:todo] == 'reassign' || params[:todo].blank?) @category.destroy
reassign_to = @project.issue_categories.find_by_id(params[:reassign_to_id]) redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'categories'
end elsif params[:todo]
reassign_to = @project.issue_categories.find_by_id(params[:reassign_to_id]) if params[:todo] == 'reassign'
@category.destroy(reassign_to) @category.destroy(reassign_to)
respond_to do |format| redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'categories'
format.html { redirect_to_settings_in_projects }
format.api { render_api_ok }
end
return
end end
@categories = @project.issue_categories - [@category] @categories = @project.issue_categories - [@category]
end end
private private
def find_project
def redirect_to_settings_in_projects @category = IssueCategory.find(params[:id])
redirect_to settings_project_path(@project, :tab => 'categories') @project = @category.project
end rescue ActiveRecord::RecordNotFound
render_404
# Wrap ApplicationController's find_model_object method to set
# @category instead of just @issue_category
def find_model_object
super
@category = @object
end end
end end
+25 -52
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,72 +16,45 @@
# 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 IssueRelationsController < ApplicationController class IssueRelationsController < ApplicationController
before_filter :find_issue, :find_project_from_association, :authorize, :only => [:index, :create] before_filter :find_project, :authorize
before_filter :find_relation, :except => [:index, :create]
accept_api_auth :index, :show, :create, :destroy def new
def index
@relations = @issue.relations
respond_to do |format|
format.html { render :nothing => true }
format.api
end
end
def show
raise Unauthorized unless @relation.visible?
respond_to do |format|
format.html { render :nothing => true }
format.api
end
end
def create
@relation = IssueRelation.new(params[:relation]) @relation = IssueRelation.new(params[:relation])
@relation.issue_from = @issue @relation.issue_from = @issue
if params[:relation] && m = params[:relation][:issue_to_id].to_s.strip.match(/^#?(\d+)$/) if params[:relation] && m = params[:relation][:issue_to_id].to_s.match(/^#?(\d+)$/)
@relation.issue_to = Issue.visible.find_by_id(m[1].to_i) @relation.issue_to = Issue.visible.find_by_id(m[1].to_i)
end end
saved = @relation.save @relation.save if request.post?
respond_to do |format| respond_to do |format|
format.html { redirect_to issue_path(@issue) } format.html { redirect_to :controller => 'issues', :action => 'show', :id => @issue }
format.js { format.js do
@relations = @issue.reload.relations.select {|r| r.other_issue(@issue) && r.other_issue(@issue).visible? } render :update do |page|
} page.replace_html "relations", :partial => 'issues/relations'
format.api { if @relation.errors.empty?
if saved page << "$('relation_delay').value = ''"
render :action => 'show', :status => :created, :location => relation_url(@relation) page << "$('relation_issue_to_id').value = ''"
else end
render_validation_errors(@relation)
end end
} end
end end
end end
def destroy def destroy
raise Unauthorized unless @relation.deletable? relation = IssueRelation.find(params[:id])
@relation.destroy if request.post? && @issue.relations.include?(relation)
relation.destroy
@issue.reload
end
respond_to do |format| respond_to do |format|
format.html { redirect_to issue_path(@relation.issue_from) } format.html { redirect_to :controller => 'issues', :action => 'show', :id => @issue }
format.js format.js { render(:update) {|page| page.replace_html "relations", :partial => 'issues/relations'} }
format.api { render_api_ok }
end end
end end
private private
def find_issue def find_project
@issue = @object = Issue.find(params[:issue_id]) @issue = Issue.find(params[:issue_id])
rescue ActiveRecord::RecordNotFound @project = @issue.project
render_404
end
def find_relation
@relation = IssueRelation.find(params[:id])
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
+20 -21
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -18,20 +18,19 @@
class IssueStatusesController < ApplicationController class IssueStatusesController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin, :except => :index before_filter :require_admin
before_filter :require_admin_or_api_request, :only => :index
accept_api_auth :index verify :method => :post, :only => [ :destroy, :create, :update, :move, :update_issue_done_ratio ],
:redirect_to => { :action => :list }
def index def index
respond_to do |format| list
format.html { render :action => 'list' unless request.xhr?
@issue_status_pages, @issue_statuses = paginate IssueStatus.sorted, :per_page => 25 end
render :action => "index", :layout => false if request.xhr?
} def list
format.api { @issue_status_pages, @issue_statuses = paginate :issue_statuses, :per_page => 25, :order => "position"
@issue_statuses = IssueStatus.all(:order => 'position') render :action => "list", :layout => false if request.xhr?
}
end
end end
def new def new
@@ -42,7 +41,7 @@ class IssueStatusesController < ApplicationController
@issue_status = IssueStatus.new(params[:issue_status]) @issue_status = IssueStatus.new(params[:issue_status])
if @issue_status.save if @issue_status.save
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to issue_statuses_path redirect_to :action => 'list'
else else
render :action => 'new' render :action => 'new'
end end
@@ -56,7 +55,7 @@ class IssueStatusesController < ApplicationController
@issue_status = IssueStatus.find(params[:id]) @issue_status = IssueStatus.find(params[:id])
if @issue_status.update_attributes(params[:issue_status]) if @issue_status.update_attributes(params[:issue_status])
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to issue_statuses_path redirect_to :action => 'list'
else else
render :action => 'edit' render :action => 'edit'
end end
@@ -64,18 +63,18 @@ class IssueStatusesController < ApplicationController
def destroy def destroy
IssueStatus.find(params[:id]).destroy IssueStatus.find(params[:id]).destroy
redirect_to issue_statuses_path redirect_to :action => 'list'
rescue rescue
flash[:error] = l(:error_unable_delete_issue_status) flash[:error] = "Unable to delete issue status"
redirect_to issue_statuses_path redirect_to :action => 'list'
end end
def update_issue_done_ratio def update_issue_done_ratio
if request.post? && IssueStatus.update_issue_done_ratios if IssueStatus.update_issue_done_ratios
flash[:notice] = l(:notice_issue_done_ratios_updated) flash[:notice] = l(:notice_issue_done_ratios_updated)
else else
flash[:error] = l(:error_issue_done_ratios_not_updated) flash[:error] = l(:error_issue_done_ratios_not_updated)
end end
redirect_to issue_statuses_path redirect_to :action => 'list'
end end
end end
+388 -324
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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,18 +16,15 @@
# 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 IssuesController < ApplicationController class IssuesController < ApplicationController
menu_item :new_issue, :only => [:new, :create] menu_item :new_issue, :only => :new
default_search_scope :issues default_search_scope :issues
before_filter :find_issue, :only => [:show, :edit, :update] before_filter :find_issue, :only => [:show, :edit, :reply]
before_filter :find_issues, :only => [:bulk_edit, :bulk_update, :destroy] before_filter :find_issues, :only => [:bulk_edit, :move, :destroy]
before_filter :find_project, :only => [:new, :create, :update_form] before_filter :find_project, :only => [:new, :update_form, :preview]
before_filter :authorize, :except => [:index] before_filter :authorize, :except => [:index, :changes, :gantt, :calendar, :preview, :context_menu]
before_filter :find_optional_project, :only => [:index] before_filter :find_optional_project, :only => [:index, :changes, :gantt, :calendar]
before_filter :check_for_default_issue_status, :only => [:new, :create] accept_key_auth :index, :show, :changes
before_filter :build_new_issue_from_params, :only => [:new, :create, :update_form]
accept_rss_auth :index, :show
accept_api_auth :index, :show, :create, :update, :destroy
rescue_from Query::StatementInvalid, :with => :query_statement_invalid rescue_from Query::StatementInvalid, :with => :query_statement_invalid
@@ -44,267 +41,294 @@ class IssuesController < ApplicationController
include AttachmentsHelper include AttachmentsHelper
helper :queries helper :queries
include QueriesHelper include QueriesHelper
helper :repositories
include RepositoriesHelper
helper :sort helper :sort
include SortHelper include SortHelper
include IssuesHelper include IssuesHelper
helper :timelog helper :timelog
include Redmine::Export::PDF include Redmine::Export::PDF
verify :method => :post,
:only => :destroy,
: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({'id' => "#{Issue.table_name}.id"}.merge(@query.available_columns.inject({}) {|h, c| h[c.name.to_s] = c.sortable; h}))
@query.sort_criteria = sort_criteria.to_a
if @query.valid? if @query.valid?
case params[:format] limit = case params[:format]
when 'csv', 'pdf' when 'csv', 'pdf'
@limit = Setting.issues_export_limit.to_i Setting.issues_export_limit.to_i
when 'atom' when 'atom'
@limit = Setting.feeds_limit.to_i Setting.feeds_limit.to_i
when 'xml', 'json'
@offset, @limit = api_offset_and_limit
else else
@limit = per_page_option per_page_option
end end
@issue_count = @query.issue_count @issue_count = @query.issue_count
@issue_pages = Paginator.new @issue_count, @limit, params['page'] @issue_pages = Paginator.new self, @issue_count, limit, params['page']
@offset ||= @issue_pages.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 => @issue_pages.current.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', :layout => !request.xhr? } format.html { render :template => 'issues/index.rhtml', :layout => !request.xhr? }
format.api {
Issue.load_visible_relations(@issues) if include_in_api_response?('relations')
}
format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") } format.atom { render_feed(@issues, :title => "#{@project || Setting.app_title}: #{l(:label_issue_plural)}") }
format.csv { send_data(query_to_csv(@issues, @query, params), :type => 'text/csv; header=present', :filename => 'issues.csv') } format.csv { send_data(issues_to_csv(@issues, @project), :type => 'text/csv; header=present', :filename => 'export.csv') }
format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'issues.pdf') } format.pdf { send_data(issues_to_pdf(@issues, @project, @query), :type => 'application/pdf', :filename => 'export.pdf') }
end end
else else
respond_to do |format| # Send html if the query is not valid
format.html { render(:template => 'issues/index', :layout => !request.xhr?) } render(:template => 'issues/index.rhtml', :layout => !request.xhr?)
format.any(:atom, :csv, :pdf) { render(:nothing => true) }
format.api { render_validation_errors(@query) }
end
end end
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
def show def changes
@journals = @issue.journals.includes(:user, :details).reorder("#{Journal.table_name}.id ASC").all retrieve_query
@journals.each_with_index {|j,i| j.indice = i+1} sort_init 'id', 'desc'
@journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project) sort_update({'id' => "#{Issue.table_name}.id"}.merge(@query.available_columns.inject({}) {|h, c| h[c.name.to_s] = c.sortable; h}))
Journal.preload_journals_details_custom_fields(@journals)
# TODO: use #select! when ruby1.8 support is dropped
@journals.reject! {|journal| !journal.notes? && journal.visible_details.empty?}
@journals.reverse! if User.current.wants_comments_in_reverse_order?
if @query.valid?
@journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC",
:limit => 25)
end
@title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
render :layout => false, :content_type => 'application/atom+xml'
rescue ActiveRecord::RecordNotFound
render_404
end
def show
@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.reverse! if User.current.wants_comments_in_reverse_order?
@changesets = @issue.changesets.visible.all @changesets = @issue.changesets.visible.all
@changesets.reverse! if User.current.wants_comments_in_reverse_order? @changesets.reverse! if User.current.wants_comments_in_reverse_order?
@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.active @priorities = IssuePriority.all
@time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project) @time_entry = TimeEntry.new
@relation = IssueRelation.new
respond_to do |format| respond_to do |format|
format.html { format.html { render :template => 'issues/show.rhtml' }
retrieve_previous_and_next_issue_ids format.atom { render :action => 'changes', :layout => false, :content_type => 'application/atom+xml' }
render :template => 'issues/show' format.pdf { send_data(issue_to_pdf(@issue), :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf") }
}
format.api
format.atom { render :template => 'journals/index', :layout => false, :content_type => 'application/atom+xml' }
format.pdf {
pdf = issue_to_pdf(@issue, :journals => @journals)
send_data(pdf, :type => 'application/pdf', :filename => "#{@project.identifier}-#{@issue.id}.pdf")
}
end end
end end
# Add a new issue # Add a new issue
# The new issue will be created from an existing one if copy_from parameter is given # The new issue will be created from an existing one if copy_from parameter is given
def new def new
respond_to do |format| @issue = Issue.new
format.html { render :action => 'new', :layout => !request.xhr? } @issue.copy_from(params[:copy_from]) if params[:copy_from]
@issue.project = @project
# Tracker must be set before custom field values
@issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
if @issue.tracker.nil?
render_error l(:error_no_tracker_in_project)
return
end end
if params[:issue].is_a?(Hash)
@issue.attributes = params[:issue]
@issue.watcher_user_ids = params[:issue]['watcher_user_ids'] if User.current.allowed_to?(:add_issue_watchers, @project)
end
@issue.author = User.current
default_status = IssueStatus.default
unless default_status
render_error l(:error_no_default_issue_status)
return
end
@issue.status = default_status
@allowed_statuses = ([default_status] + default_status.find_new_statuses_allowed_to(User.current.roles_for_project(@project), @issue.tracker)).uniq
if request.get? || request.xhr?
@issue.start_date ||= Date.today
else
requested_status = IssueStatus.find_by_id(params[:issue][:status_id]) if params[:issue]
# Check that the user is allowed to apply the requested status
@issue.status = (@allowed_statuses.include? requested_status) ? requested_status : default_status
call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })
if @issue.save
attach_files(@issue, params[:attachments])
flash[:notice] = l(:notice_successful_create)
call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
redirect_to(params[:continue] ? { :action => 'new', :tracker_id => @issue.tracker } :
{ :action => 'show', :id => @issue })
return
end
end
@priorities = IssuePriority.all
render :layout => !request.xhr?
end end
def create # Attributes that can be updated on workflow transition (without :edit permission)
call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue }) # TODO: make it configurable (at least per role)
@issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads])) UPDATABLE_ATTRS_ON_TRANSITION = %w(status_id assigned_to_id fixed_version_id done_ratio) unless const_defined?(:UPDATABLE_ATTRS_ON_TRANSITION)
if @issue.save
call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})
respond_to do |format|
format.html {
render_attachment_warning_if_needed(@issue)
flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("##{@issue.id}", issue_path(@issue), :title => @issue.subject))
if params[:continue]
attrs = {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?}
redirect_to new_project_issue_path(@issue.project, :issue => attrs)
else
redirect_to issue_path(@issue)
end
}
format.api { render :action => 'show', :status => :created, :location => issue_url(@issue) }
end
return
else
respond_to do |format|
format.html { render :action => 'new' }
format.api { render_validation_errors(@issue) }
end
end
end
def edit def edit
return unless update_issue_from_params @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
@priorities = IssuePriority.all
@edit_allowed = User.current.allowed_to?(:edit_issues, @project)
@time_entry = TimeEntry.new
respond_to do |format|
format.html { }
format.xml { }
end
end
def update
return unless update_issue_from_params
@issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))
saved = false
begin
saved = save_issue_with_child_records
rescue ActiveRecord::StaleObjectError
@conflict = true
if params[:last_journal_id]
@conflict_journals = @issue.journals_after(params[:last_journal_id]).all
@conflict_journals.reject!(&:private_notes?) unless User.current.allowed_to?(:view_private_notes, @issue.project)
end
end
if saved
render_attachment_warning_if_needed(@issue)
flash[:notice] = l(:notice_successful_update) unless @issue.current_journal.new_record?
respond_to do |format|
format.html { redirect_back_or_default issue_path(@issue) }
format.api { render_api_ok }
end
else
respond_to do |format|
format.html { render :action => 'edit' }
format.api { render_validation_errors(@issue) }
end
end
end
# Updates the issue form when changing the project, status or tracker
# on issue creation/update
def update_form
end
# Bulk edit/copy a set of issues
def bulk_edit
@issues.sort!
@copy = params[:copy].present?
@notes = params[:notes] @notes = params[:notes]
journal = @issue.init_journal(User.current, @notes)
# User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
if (@edit_allowed || !@allowed_statuses.empty?) && params[:issue]
attrs = params[:issue].dup
attrs.delete_if {|k,v| !UPDATABLE_ATTRS_ON_TRANSITION.include?(k) } unless @edit_allowed
attrs.delete(:status_id) unless @allowed_statuses.detect {|s| s.id.to_s == attrs[:status_id].to_s}
@issue.attributes = attrs
end
if User.current.allowed_to?(:move_issues, @projects) if request.post?
@allowed_projects = Issue.allowed_target_projects_on_move @time_entry = TimeEntry.new(:project => @project, :issue => @issue, :user => User.current, :spent_on => Date.today)
if params[:issue] @time_entry.attributes = params[:time_entry]
@target_project = @allowed_projects.detect {|p| p.id.to_s == params[:issue][:project_id].to_s} if (@time_entry.hours.nil? || @time_entry.valid?) && @issue.valid?
if @target_project attachments = attach_files(@issue, params[:attachments])
target_projects = [@target_project] attachments.each {|a| journal.details << JournalDetail.new(:property => 'attachment', :prop_key => a.id, :value => a.filename)}
call_hook(:controller_issues_edit_before_save, { :params => params, :issue => @issue, :time_entry => @time_entry, :journal => journal})
if @issue.save
# Log spend time
if User.current.allowed_to?(:log_time, @project)
@time_entry.save
end
if !journal.new_record?
# Only send notification if something was actually changed
flash[:notice] = l(:notice_successful_update)
end
call_hook(:controller_issues_edit_after_save, { :params => params, :issue => @issue, :time_entry => @time_entry, :journal => journal})
redirect_back_or_default({:action => 'show', :id => @issue})
end end
end end
end end
target_projects ||= @projects rescue ActiveRecord::StaleObjectError
# Optimistic locking exception
if @copy flash.now[:error] = l(:notice_locking_conflict)
@available_statuses = [IssueStatus.default] # Remove the previously added attachments if issue was not updated
else attachments.each(&:destroy)
@available_statuses = @issues.map(&:new_statuses_allowed_to).reduce(:&)
end
@custom_fields = target_projects.map{|p|p.all_issue_custom_fields.visible}.reduce(:&)
@assignables = target_projects.map(&:assignable_users).reduce(:&)
@trackers = target_projects.map(&:trackers).reduce(:&)
@versions = target_projects.map {|p| p.shared_versions.open}.reduce(:&)
@categories = target_projects.map {|p| p.issue_categories}.reduce(:&)
if @copy
@attachments_present = @issues.detect {|i| i.attachments.any?}.present?
@subtasks_present = @issues.detect {|i| !i.leaf?}.present?
end
@safe_attributes = @issues.map(&:safe_attribute_names).reduce(:&)
@issue_params = params[:issue] || {}
@issue_params[:custom_field_values] ||= {}
end end
def bulk_update def reply
@issues.sort! journal = Journal.find(params[:journal_id]) if params[:journal_id]
@copy = params[:copy].present? if journal
attributes = parse_params_for_bulk_issue_attributes(params) user = journal.user
text = journal.notes
unsaved_issues = [] else
saved_issues = [] user = @issue.author
text = @issue.description
if @copy && params[:copy_subtasks].present?
# Descendant issues will be copied with the parent task
# Don't copy them twice
@issues.reject! {|issue| @issues.detect {|other| issue.is_descendant_of?(other)}}
end end
# Replaces pre blocks with [...]
text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n> "
content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
@issues.each do |orig_issue| render(:update) { |page|
orig_issue.reload page.<< "$('notes').value = \"#{escape_javascript content}\";"
if @copy page.show 'update'
issue = orig_issue.copy({}, page << "Form.Element.focus('notes');"
:attachments => params[:copy_attachments].present?, page << "Element.scrollTo('update');"
:subtasks => params[:copy_subtasks].present? page << "$('notes').scrollTop = $('notes').scrollHeight - $('notes').clientHeight;"
) }
else end
issue = orig_issue
# Bulk edit a set of issues
def bulk_edit
if request.post?
tracker = params[:tracker_id].blank? ? nil : @project.trackers.find_by_id(params[:tracker_id])
status = params[:status_id].blank? ? nil : IssueStatus.find_by_id(params[:status_id])
priority = params[:priority_id].blank? ? nil : IssuePriority.find_by_id(params[:priority_id])
assigned_to = (params[:assigned_to_id].blank? || params[:assigned_to_id] == 'none') ? nil : User.find_by_id(params[:assigned_to_id])
category = (params[:category_id].blank? || params[:category_id] == 'none') ? nil : @project.issue_categories.find_by_id(params[:category_id])
fixed_version = (params[:fixed_version_id].blank? || params[:fixed_version_id] == 'none') ? nil : @project.shared_versions.find_by_id(params[:fixed_version_id])
custom_field_values = params[:custom_field_values] ? params[:custom_field_values].reject {|k,v| v.blank?} : nil
unsaved_issue_ids = []
@issues.each do |issue|
journal = issue.init_journal(User.current, params[:notes])
issue.tracker = tracker if tracker
issue.priority = priority if priority
issue.assigned_to = assigned_to if assigned_to || params[:assigned_to_id] == 'none'
issue.category = category if category || params[:category_id] == 'none'
issue.fixed_version = fixed_version if fixed_version || params[:fixed_version_id] == 'none'
issue.start_date = params[:start_date] unless params[:start_date].blank?
issue.due_date = params[:due_date] unless params[:due_date].blank?
issue.done_ratio = params[:done_ratio] unless params[:done_ratio].blank?
issue.custom_field_values = custom_field_values if custom_field_values && !custom_field_values.empty?
call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
# Don't save any change to the issue if the user is not authorized to apply the requested status
unless (status.nil? || (issue.new_statuses_allowed_to(User.current).include?(status) && issue.status = status)) && issue.save
# Keep unsaved issue ids to display them in flash error
unsaved_issue_ids << issue.id
end
end end
journal = issue.init_journal(User.current, params[:notes]) if unsaved_issue_ids.empty?
issue.safe_attributes = attributes flash[:notice] = l(:notice_successful_update) unless @issues.empty?
call_hook(:controller_issues_bulk_edit_before_save, { :params => params, :issue => issue })
if issue.save
saved_issues << issue
else else
unsaved_issues << orig_issue flash[:error] = l(:notice_failed_to_save_issues, :count => unsaved_issue_ids.size,
:total => @issues.size,
:ids => '#' + unsaved_issue_ids.join(', #'))
end end
redirect_back_or_default({:controller => 'issues', :action => 'index', :project_id => @project})
return
end end
@available_statuses = Workflow.available_statuses(@project)
@custom_fields = @project.all_issue_custom_fields
end
if unsaved_issues.empty? def move
flash[:notice] = l(:notice_successful_update) unless saved_issues.empty? @copy = params[:copy_options] && params[:copy_options][:copy]
@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 ||= @project
@trackers = @target_project.trackers
@available_statuses = Workflow.available_statuses(@project)
if request.post?
new_tracker = params[:new_tracker_id].blank? ? nil : @target_project.trackers.find_by_id(params[:new_tracker_id])
unsaved_issue_ids = []
moved_issues = []
@issues.each do |issue|
changed_attributes = {}
[:assigned_to_id, :status_id, :start_date, :due_date].each do |valid_attribute|
unless params[valid_attribute].blank?
changed_attributes[valid_attribute] = (params[valid_attribute] == 'none' ? nil : params[valid_attribute])
end
end
issue.init_journal(User.current)
if r = issue.move_to(@target_project, new_tracker, {:copy => @copy, :attributes => changed_attributes})
moved_issues << r
else
unsaved_issue_ids << issue.id
end
end
if unsaved_issue_ids.empty?
flash[:notice] = l(:notice_successful_update) unless @issues.empty?
else
flash[:error] = l(:notice_failed_to_save_issues, :count => unsaved_issue_ids.size,
:total => @issues.size,
:ids => '#' + unsaved_issue_ids.join(', #'))
end
if params[:follow] if params[:follow]
if @issues.size == 1 && saved_issues.size == 1 if @issues.size == 1 && moved_issues.size == 1
redirect_to issue_path(saved_issues.first) redirect_to :controller => 'issues', :action => 'show', :id => moved_issues.first
elsif saved_issues.map(&:project).uniq.size == 1 else
redirect_to project_issues_path(saved_issues.map(&:project).first) redirect_to :controller => 'issues', :action => 'index', :project_id => (@target_project || @project)
end end
else else
redirect_back_or_default _project_issues_path(@project) redirect_to :controller => 'issues', :action => 'index', :project_id => @project
end end
else return
@saved_issues = @issues
@unsaved_issues = unsaved_issues
@issues = Issue.visible.find_all_by_id(@unsaved_issues.map(&:id))
bulk_edit
render :action => 'bulk_edit'
end end
render :layout => false if request.xhr?
end end
def destroy def destroy
@hours = TimeEntry.where(:issue_id => @issues.map(&:id)).sum(:hours).to_f @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
if @hours > 0 if @hours > 0
case params[:todo] case params[:todo]
when 'destroy' when 'destroy'
@@ -320,158 +344,198 @@ class IssuesController < ApplicationController
TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues]) TimeEntry.update_all("issue_id = #{reassign_to.id}", ['issue_id IN (?)', @issues])
end end
else else
# display the destroy form if it's a user request # display the destroy form
return unless api_request? return
end end
end end
@issues.each do |issue| @issues.each(&:destroy)
begin redirect_to :action => 'index', :project_id => @project
issue.reload.destroy end
rescue ::ActiveRecord::RecordNotFound # raised by #reload if issue no longer exists
# nothing to do, issue was already deleted (eg. by a parent) def gantt
end @gantt = Redmine::Helpers::Gantt.new(params)
retrieve_query
@query.group_by = nil
if @query.valid?
events = []
# Issues that have start and due dates
events += @query.issues(:include => [:tracker, :assigned_to, :priority],
:order => "start_date, due_date",
:conditions => ["(((start_date>=? and start_date<=?) or (due_date>=? and due_date<=?) or (start_date<? and due_date>?)) and start_date is not null and due_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
)
# Issues that don't have a due date but that are assigned to a version with a date
events += @query.issues(:include => [:tracker, :assigned_to, :priority, :fixed_version],
:order => "start_date, effective_date",
:conditions => ["(((start_date>=? and start_date<=?) or (effective_date>=? and effective_date<=?) or (start_date<? and effective_date>?)) and start_date is not null and due_date is null and effective_date is not null)", @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to, @gantt.date_from, @gantt.date_to]
)
# Versions
events += @query.versions(:conditions => ["effective_date BETWEEN ? AND ?", @gantt.date_from, @gantt.date_to])
@gantt.events = events
end end
basename = (@project ? "#{@project.identifier}-" : '') + 'gantt'
respond_to do |format| respond_to do |format|
format.html { redirect_back_or_default _project_issues_path(@project) } format.html { render :template => "issues/gantt.rhtml", :layout => !request.xhr? }
format.api { render_api_ok } format.png { send_data(@gantt.to_image, :disposition => 'inline', :type => 'image/png', :filename => "#{basename}.png") } if @gantt.respond_to?('to_image')
format.pdf { send_data(gantt_to_pdf(@gantt, @project), :type => 'application/pdf', :filename => "#{basename}.pdf") }
end end
end end
private def calendar
if params[:year] and params[:year].to_i > 1900
def find_project @year = params[:year].to_i
project_id = params[:project_id] || (params[:issue] && params[:issue][:project_id]) if params[:month] and params[:month].to_i > 0 and params[:month].to_i < 13
@project = Project.find(project_id) @month = params[:month].to_i
rescue ActiveRecord::RecordNotFound
render_404
end
def retrieve_previous_and_next_issue_ids
retrieve_query_from_session
if @query
sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)
sort_update(@query.sortable_columns, 'issues_index_sort')
limit = 500
issue_ids = @query.issue_ids(:order => sort_clause, :limit => (limit + 1), :include => [:assigned_to, :tracker, :priority, :category, :fixed_version])
if (idx = issue_ids.index(@issue.id)) && idx < limit
if issue_ids.size < 500
@issue_position = idx + 1
@issue_count = issue_ids.size
end
@prev_issue_id = issue_ids[idx - 1] if idx > 0
@next_issue_id = issue_ids[idx + 1] if idx < (issue_ids.size - 1)
end end
end end
end @year ||= Date.today.year
@month ||= Date.today.month
# Used by #edit and #update to set some common instance variables @calendar = Redmine::Helpers::Calendar.new(Date.civil(@year, @month, 1), current_language, :month)
# from the params retrieve_query
# TODO: Refactor, not everything in here is needed by #edit @query.group_by = nil
def update_issue_from_params if @query.valid?
@edit_allowed = User.current.allowed_to?(:edit_issues, @project) events = []
@time_entry = TimeEntry.new(:issue => @issue, :project => @issue.project) events += @query.issues(:include => [:tracker, :assigned_to, :priority],
@time_entry.attributes = params[:time_entry] :conditions => ["((start_date BETWEEN ? AND ?) OR (due_date BETWEEN ? AND ?))", @calendar.startdt, @calendar.enddt, @calendar.startdt, @calendar.enddt]
)
events += @query.versions(:conditions => ["effective_date BETWEEN ? AND ?", @calendar.startdt, @calendar.enddt])
@issue.init_journal(User.current) @calendar.events = events
issue_attributes = params[:issue]
if issue_attributes && params[:conflict_resolution]
case params[:conflict_resolution]
when 'overwrite'
issue_attributes = issue_attributes.dup
issue_attributes.delete(:lock_version)
when 'add_notes'
issue_attributes = issue_attributes.slice(:notes)
when 'cancel'
redirect_to issue_path(@issue)
return false
end
end end
@issue.safe_attributes = issue_attributes
@priorities = IssuePriority.active render :layout => false if request.xhr?
@allowed_statuses = @issue.new_statuses_allowed_to(User.current)
true
end end
# TODO: Refactor, lots of extra code in here def context_menu
# TODO: Changing tracker on an existing issue should not trigger this @issues = Issue.find_all_by_id(params[:ids], :include => :project)
def build_new_issue_from_params if (@issues.size == 1)
@issue = @issues.first
@allowed_statuses = @issue.new_statuses_allowed_to(User.current)
end
projects = @issues.collect(&:project).compact.uniq
@project = projects.first if projects.size == 1
@can = {:edit => (@project && User.current.allowed_to?(:edit_issues, @project)),
:log_time => (@project && User.current.allowed_to?(:log_time, @project)),
:update => (@project && (User.current.allowed_to?(:edit_issues, @project) || (User.current.allowed_to?(:change_status, @project) && @allowed_statuses && !@allowed_statuses.empty?))),
:move => (@project && User.current.allowed_to?(:move_issues, @project)),
:copy => (@issue && @project.trackers.include?(@issue.tracker) && User.current.allowed_to?(:add_issues, @project)),
:delete => (@project && User.current.allowed_to?(:delete_issues, @project))
}
if @project
@assignables = @project.assignable_users
@assignables << @issue.assigned_to if @issue && @issue.assigned_to && !@assignables.include?(@issue.assigned_to)
@trackers = @project.trackers
end
@priorities = IssuePriority.all.reverse
@statuses = IssueStatus.find(:all, :order => 'position')
@back = params[:back_url] || request.env['HTTP_REFERER']
render :layout => false
end
def update_form
if params[:id].blank? if params[:id].blank?
@issue = Issue.new @issue = Issue.new
if params[:copy_from]
begin
@copy_from = Issue.visible.find(params[:copy_from])
@copy_attachments = params[:copy_attachments].present? || request.get?
@copy_subtasks = params[:copy_subtasks].present? || request.get?
@issue.copy_from(@copy_from, :attachments => @copy_attachments, :subtasks => @copy_subtasks)
rescue ActiveRecord::RecordNotFound
render_404
return
end
end
@issue.project = @project @issue.project = @project
else else
@issue = @project.issues.visible.find(params[:id]) @issue = @project.issues.visible.find(params[:id])
end end
@issue.attributes = params[:issue]
@allowed_statuses = ([@issue.status] + @issue.status.find_new_statuses_allowed_to(User.current.roles_for_project(@project), @issue.tracker)).uniq
@priorities = IssuePriority.all
@issue.project = @project render :partial => 'attributes'
@issue.author ||= User.current
# Tracker must be set before custom field values
@issue.tracker ||= @project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
if @issue.tracker.nil?
render_error l(:error_no_tracker_in_project)
return false
end
@issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
@issue.safe_attributes = params[:issue]
@priorities = IssuePriority.active
@allowed_statuses = @issue.new_statuses_allowed_to(User.current, true)
@available_watchers = (@issue.project.users.sort + @issue.watcher_users).uniq
end end
def check_for_default_issue_status def preview
if IssueStatus.default.nil? @issue = @project.issues.find_by_id(params[:id]) unless params[:id].blank?
render_error l(:error_no_default_issue_status) @attachements = @issue.attachments if @issue
return false @text = params[:notes] || (params[:issue] ? params[:issue][:description] : nil)
end render :partial => 'common/preview'
end end
def parse_params_for_bulk_issue_attributes(params) private
attributes = (params[:issue] || {}).reject {|k,v| v.blank?} def find_issue
attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'} @issue = Issue.find(params[:id], :include => [:project, :tracker, :status, :author, :priority, :category])
if custom = attributes[:custom_field_values] @project = @issue.project
custom.reject! {|k,v| v.blank?} rescue ActiveRecord::RecordNotFound
custom.keys.each do |k| render_404
if custom[k].is_a?(Array) end
custom[k] << '' if custom[k].delete('__none__')
# Filter for bulk operations
def find_issues
@issues = Issue.find_all_by_id(params[:id] || params[:ids])
raise ActiveRecord::RecordNotFound if @issues.empty?
projects = @issues.collect(&:project).compact.uniq
if projects.size == 1
@project = projects.first
else
# TODO: let users bulk edit/move/destroy issues from different projects
render_error 'Can not bulk edit/move/destroy issues from different projects'
return false
end
rescue ActiveRecord::RecordNotFound
render_404
end
def find_project
@project = Project.find(params[:project_id])
rescue ActiveRecord::RecordNotFound
render_404
end
def find_optional_project
@project = Project.find(params[:project_id]) unless params[:project_id].blank?
allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
allowed ? true : deny_access
rescue ActiveRecord::RecordNotFound
render_404
end
# Retrieve query from session or build a new query
def retrieve_query
if !params[:query_id].blank?
cond = "project_id IS NULL"
cond << " OR project_id = #{@project.id}" if @project
@query = Query.find(params[:query_id], :conditions => cond)
@query.project = @project
session[:query] = {:id => @query.id, :project_id => @query.project_id}
sort_clear
else
if params[:set_filter] || session[:query].nil? || session[:query][:project_id] != (@project ? @project.id : nil)
# Give it a name, required to be valid
@query = Query.new(:name => "_")
@query.project = @project
if params[:fields] and params[:fields].is_a? Array
params[:fields].each do |field|
@query.add_filter(field, params[:operators][field], params[:values][field])
end
else else
custom[k] = '' if custom[k] == '__none__' @query.available_filters.keys.each do |field|
@query.add_short_filter(field, params[field]) if params[field]
end
end end
@query.group_by = params[:group_by]
@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}
else
@query = Query.find_by_id(session[:query][:id]) if session[:query][:id]
@query ||= Query.new(:name => "_", :project => @project, :filters => session[:query][:filters], :group_by => session[:query][:group_by], :column_names => session[:query][:column_names])
@query.project = @project
end end
end end
attributes
end end
# Saves @issue and a time_entry from the parameters # Rescues an invalid query statement. Just in case...
def save_issue_with_child_records def query_statement_invalid(exception)
Issue.transaction do logger.error "Query::StatementInvalid: #{exception.message}" if logger
if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, @issue.project) session.delete(:query)
time_entry = @time_entry || TimeEntry.new sort_clear
time_entry.project = @issue.project render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
time_entry.issue = @issue
time_entry.user = User.current
time_entry.spent_on = User.current.today
time_entry.attributes = params[:time_entry]
@issue.time_entries << time_entry
end
call_hook(:controller_issues_edit_before_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
if @issue.save
call_hook(:controller_issues_edit_after_save, { :params => params, :issue => @issue, :time_entry => time_entry, :journal => @issue.current_journal})
else
raise ActiveRecord::Rollback
end
end
end end
end end
+7 -71
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,88 +16,24 @@
# 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
before_filter :find_issue, :only => [:new]
before_filter :find_optional_project, :only => [:index]
before_filter :authorize, :only => [:new, :edit, :diff]
accept_rss_auth :index
menu_item :issues
helper :issues
helper :custom_fields
helper :queries
include QueriesHelper
helper :sort
include SortHelper
def index
retrieve_query
sort_init 'id', 'desc'
sort_update(@query.sortable_columns)
if @query.valid?
@journals = @query.journals(:order => "#{Journal.table_name}.created_on DESC",
:limit => 25)
end
@title = (@project ? @project.name : Setting.app_title) + ": " + (@query.new_record? ? l(:label_changes_details) : @query.name)
render :layout => false, :content_type => 'application/atom+xml'
rescue ActiveRecord::RecordNotFound
render_404
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
@journal = Journal.visible.find(params[:journal_id]) if params[:journal_id]
if @journal
user = @journal.user
text = @journal.notes
else
user = @issue.author
text = @issue.description
end
# Replaces pre blocks with [...]
text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
@content = "#{ll(Setting.default_language, :text_user_wrote, user)}\n> "
@content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
rescue ActiveRecord::RecordNotFound
render_404
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?
call_hook(:controller_journals_edit_post, { :journal => @journal, :params => params}) call_hook(:controller_journals_edit_post, { :journal => @journal, :params => params})
respond_to do |format| respond_to do |format|
format.html { redirect_to issue_path(@journal.journalized) } format.html { redirect_to :controller => 'issues', :action => 'show', :id => @journal.journalized_id }
format.js { render :action => 'update' } format.js { render :action => 'update' }
end end
else
respond_to do |format|
format.html {
# TODO: implement non-JS journal update
render :nothing => true
}
format.js
end
end end
end end
private private
def find_journal def find_journal
@journal = Journal.visible.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
+6 -2
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -18,6 +18,10 @@
class MailHandlerController < ActionController::Base class MailHandlerController < ActionController::Base
before_filter :check_credential before_filter :check_credential
verify :method => :post,
:only => :index,
: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
+49 -79
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -16,110 +16,80 @@
# 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 MembersController < ApplicationController class MembersController < ApplicationController
model_object Member before_filter :find_member, :except => [:new, :autocomplete_for_member]
before_filter :find_model_object, :except => [:index, :create, :autocomplete] before_filter :find_project, :only => [:new, :autocomplete_for_member]
before_filter :find_project_from_association, :except => [:index, :create, :autocomplete]
before_filter :find_project_by_project_id, :only => [:index, :create, :autocomplete]
before_filter :authorize before_filter :authorize
accept_api_auth :index, :show, :create, :update, :destroy
def index def new
@offset, @limit = api_offset_and_limit
@member_count = @project.member_principals.count
@member_pages = Paginator.new @member_count, @limit, params['page']
@offset ||= @member_pages.offset
@members = @project.member_principals.all(
:order => "#{Member.table_name}.id",
:limit => @limit,
:offset => @offset
)
respond_to do |format|
format.html { head 406 }
format.api
end
end
def show
respond_to do |format|
format.html { head 406 }
format.api
end
end
def create
members = [] members = []
if params[:membership] if params[:member] && request.post?
if params[:membership][:user_ids] attrs = params[:member].dup
attrs = params[:membership].dup if (user_ids = attrs.delete(:user_ids))
user_ids = attrs.delete(:user_ids)
user_ids.each do |user_id| user_ids.each do |user_id|
members << Member.new(:role_ids => params[:membership][:role_ids], :user_id => user_id) members << Member.new(attrs.merge(:user_id => user_id))
end end
else else
members << Member.new(:role_ids => params[:membership][:role_ids], :user_id => params[:membership][:user_id]) members << Member.new(attrs)
end end
@project.members << members @project.members << members
end end
respond_to do |format| respond_to do |format|
format.html { redirect_to_settings_in_projects } format.html { redirect_to :controller => 'projects', :action => 'settings', :tab => 'members', :id => @project }
format.js { @members = members } format.js {
format.api { render(:update) {|page|
@member = members.first page.replace_html "tab-content-members", :partial => 'projects/settings/members'
if @member.valid? page << 'hideOnLoad()'
render :action => 'show', :status => :created, :location => membership_url(@member) members.each {|member| page.visual_effect(:highlight, "member-#{member.id}") }
else }
render_validation_errors(@member)
end
} }
end end
end end
def update def edit
if params[:membership] if request.post? and @member.update_attributes(params[:member])
@member.role_ids = params[:membership][:role_ids] respond_to do |format|
end format.html { redirect_to :controller => 'projects', :action => 'settings', :tab => 'members', :id => @project }
saved = @member.save format.js {
respond_to do |format| render(:update) {|page|
format.html { redirect_to_settings_in_projects } page.replace_html "tab-content-members", :partial => 'projects/settings/members'
format.js page << 'hideOnLoad()'
format.api { page.visual_effect(:highlight, "member-#{@member.id}")
if saved }
render_api_ok }
else end
render_validation_errors(@member)
end
}
end end
end end
def destroy def destroy
if request.delete? && @member.deletable? if request.post? && @member.deletable?
@member.destroy @member.destroy
end end
respond_to do |format| respond_to do |format|
format.html { redirect_to_settings_in_projects } format.html { redirect_to :controller => 'projects', :action => 'settings', :tab => 'members', :id => @project }
format.js format.js { render(:update) {|page|
format.api { page.replace_html "tab-content-members", :partial => 'projects/settings/members'
if @member.destroyed? page << 'hideOnLoad()'
render_api_ok }
else
head :unprocessable_entity
end
} }
end end
end end
def autocomplete def autocomplete_for_member
respond_to do |format| @principals = Principal.active.like(params[:q]).find(:all, :limit => 100) - @project.principals
format.js render :layout => false
end
end end
private private
def find_project
@project = Project.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
def redirect_to_settings_in_projects def find_member
redirect_to settings_project_path(@project, :tab => 'members') @member = Member.find(params[:id])
@project = @member.project
rescue ActiveRecord::RecordNotFound
render_404
end end
end end
+45 -55
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -19,113 +19,104 @@ class MessagesController < ApplicationController
menu_item :boards menu_item :boards
default_search_scope :messages default_search_scope :messages
before_filter :find_board, :only => [:new, :preview] before_filter :find_board, :only => [:new, :preview]
before_filter :find_attachments, :only => [:preview]
before_filter :find_message, :except => [:new, :preview] before_filter :find_message, :except => [:new, :preview]
before_filter :authorize, :except => [:preview, :edit, :destroy] before_filter :authorize, :except => [:preview, :edit, :destroy]
helper :boards verify :method => :post, :only => [ :reply, :destroy ], :redirect_to => { :action => :show }
verify :xhr => true, :only => :quote
helper :watchers helper :watchers
helper :attachments helper :attachments
include AttachmentsHelper include AttachmentsHelper
REPLIES_PER_PAGE = 25 unless const_defined?(:REPLIES_PER_PAGE)
# Show a topic and its replies # Show a topic and its replies
def show def show
page = params[:page] @replies = @topic.children.find(:all, :include => [:author, :attachments, {:board => :project}])
# Find the page of the requested reply @replies.reverse! if User.current.wants_comments_in_reverse_order?
if params[:r] && page.nil?
offset = @topic.children.where("#{Message.table_name}.id < ?", params[:r].to_i).count
page = 1 + offset / REPLIES_PER_PAGE
end
@reply_count = @topic.children.count
@reply_pages = Paginator.new @reply_count, REPLIES_PER_PAGE, page
@replies = @topic.children.
includes(:author, :attachments, {:board => :project}).
reorder("#{Message.table_name}.created_on ASC").
limit(@reply_pages.per_page).
offset(@reply_pages.offset).
all
@reply = Message.new(:subject => "RE: #{@message.subject}") @reply = Message.new(:subject => "RE: #{@message.subject}")
render :action => "show", :layout => false if request.xhr? render :action => "show", :layout => false if request.xhr?
end end
# Create a new topic # Create a new topic
def new def new
@message = Message.new @message = Message.new(params[:message])
@message.author = User.current @message.author = User.current
@message.board = @board @message.board = @board
@message.safe_attributes = params[:message] if params[:message] && User.current.allowed_to?(:edit_messages, @project)
if request.post? @message.locked = params[:message]['locked']
@message.save_attachments(params[:attachments]) @message.sticky = params[:message]['sticky']
if @message.save end
call_hook(:controller_messages_new_after_save, { :params => params, :message => @message}) if request.post? && @message.save
render_attachment_warning_if_needed(@message) call_hook(:controller_messages_new_after_save, { :params => params, :message => @message})
redirect_to board_message_path(@board, @message) attach_files(@message, params[:attachments])
end redirect_to :action => 'show', :id => @message
end end
end end
# Reply to a topic # Reply to a topic
def reply def reply
@reply = Message.new @reply = Message.new(params[:reply])
@reply.author = User.current @reply.author = User.current
@reply.board = @board @reply.board = @board
@reply.safe_attributes = params[:reply]
@topic.children << @reply @topic.children << @reply
if !@reply.new_record? if !@reply.new_record?
call_hook(:controller_messages_reply_after_save, { :params => params, :message => @reply}) call_hook(:controller_messages_reply_after_save, { :params => params, :message => @reply})
attachments = Attachment.attach_files(@reply, params[:attachments]) attach_files(@reply, params[:attachments])
render_attachment_warning_if_needed(@reply)
end end
redirect_to board_message_path(@board, @topic, :r => @reply) redirect_to :action => 'show', :id => @topic
end end
# Edit a message # Edit a message
def edit def edit
(render_403; return false) unless @message.editable_by?(User.current) (render_403; return false) unless @message.editable_by?(User.current)
@message.safe_attributes = params[:message] if params[:message]
if request.post? && @message.save @message.locked = params[:message]['locked']
attachments = Attachment.attach_files(@message, params[:attachments]) @message.sticky = params[:message]['sticky']
render_attachment_warning_if_needed(@message) end
if request.post? && @message.update_attributes(params[:message])
attach_files(@message, params[:attachments])
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
@message.reload @message.reload
redirect_to board_message_path(@message.board, @message.root, :r => (@message.parent_id && @message.id)) redirect_to :action => 'show', :board_id => @message.board, :id => @message.root
end end
end end
# Delete a messages # Delete a messages
def destroy def destroy
(render_403; return false) unless @message.destroyable_by?(User.current) (render_403; return false) unless @message.destroyable_by?(User.current)
r = @message.to_param
@message.destroy @message.destroy
if @message.parent redirect_to @message.parent.nil? ?
redirect_to board_message_path(@board, @message.parent, :r => r) { :controller => 'boards', :action => 'show', :project_id => @project, :id => @board } :
else { :action => 'show', :id => @message.parent }
redirect_to project_board_path(@project, @board)
end
end end
def quote def quote
@subject = @message.subject user = @message.author
@subject = "RE: #{@subject}" unless @subject.starts_with?('RE:') text = @message.content
subject = @message.subject.gsub('"', '\"')
@content = "#{ll(Setting.default_language, :text_user_wrote, @message.author)}\n> " subject = "RE: #{subject}" unless subject.starts_with?('RE:')
@content << @message.content.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]').gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n" content = "#{ll(Setting.default_language, :text_user_wrote, user)}\\n> "
content << text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]').gsub('"', '\"').gsub(/(\r?\n|\r\n?)/, "\\n> ") + "\\n\\n"
render(:update) { |page|
page << "$('reply_subject').value = \"#{subject}\";"
page.<< "$('message_content').value = \"#{content}\";"
page.show 'reply'
page << "Form.Element.focus('message_content');"
page << "Element.scrollTo('reply');"
page << "$('message_content').scrollTop = $('message_content').scrollHeight - $('message_content').clientHeight;"
}
end end
def preview def preview
message = @board.messages.find_by_id(params[:id]) message = @board.messages.find_by_id(params[:id])
@attachements = message.attachments if message
@text = (params[:message] || params[:reply])[:content] @text = (params[:message] || params[:reply])[:content]
@previewed = message
render :partial => 'common/preview' render :partial => 'common/preview'
end end
private private
def find_message def find_message
return unless find_board find_board
@message = @board.messages.find(params[:id], :include => :parent) @message = @board.messages.find(params[:id], :include => :parent)
@topic = @message.root @topic = @message.root
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
@@ -137,6 +128,5 @@ private
@project = @board.project @project = @board.project
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
nil
end end
end end
+36 -54
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -17,11 +17,8 @@
class MyController < ApplicationController class MyController < ApplicationController
before_filter :require_login before_filter :require_login
# let user change user's password when user has to
skip_before_filter :check_password_change, :only => :password
helper :issues helper :issues
helper :users
helper :custom_fields helper :custom_fields
BLOCKS = { 'issuesassignedtome' => :label_assigned_to_me_issues, BLOCKS = { 'issuesassignedtome' => :label_assigned_to_me_issues,
@@ -37,6 +34,9 @@ class MyController < ApplicationController
'right' => ['issuesreportedbyme'] 'right' => ['issuesreportedbyme']
}.freeze }.freeze
verify :xhr => true,
:only => [:add_block, :remove_block, :order_blocks]
def index def index
page page
render :action => 'page' render :action => 'page'
@@ -53,56 +53,44 @@ class MyController < ApplicationController
@user = User.current @user = User.current
@pref = @user.pref @pref = @user.pref
if request.post? if request.post?
@user.safe_attributes = params[:user] @user.attributes = params[:user]
@user.mail_notification = (params[:notification_option] == 'all')
@user.pref.attributes = params[:pref] @user.pref.attributes = params[:pref]
@user.pref[:no_self_notified] = (params[:no_self_notified] == '1')
if @user.save if @user.save
@user.pref.save @user.pref.save
@user.notified_project_ids = (params[:notification_option] == 'selected' ? params[:notified_project_ids] : [])
set_language_if_valid @user.language set_language_if_valid @user.language
flash[:notice] = l(:notice_account_updated) flash[:notice] = l(:notice_account_updated)
redirect_to my_account_path redirect_to :action => 'account'
return return
end end
end end
end @notification_options = [[l(:label_user_mail_option_all), 'all'],
[l(:label_user_mail_option_none), 'none']]
# Destroys user's account # Only users that belong to more than 1 project can select projects for which they are notified
def destroy # Note that @user.membership.size would fail since AR ignores :include association option when doing a count
@user = User.current @notification_options.insert 1, [l(:label_user_mail_option_selected), 'selected'] if @user.memberships.length > 1
unless @user.own_account_deletable? @notification_option = @user.mail_notification? ? 'all' : (@user.notified_projects_ids.empty? ? 'none' : 'selected')
redirect_to my_account_path
return
end
if request.post? && params[:confirm]
@user.destroy
if @user.destroyed?
logout_user
flash[:notice] = l(:notice_account_deleted)
end
redirect_to home_path
end
end end
# Manage user's password # Manage user's password
def password def password
@user = User.current @user = User.current
unless @user.change_password_allowed? if @user.auth_source_id
flash[:error] = l(:notice_can_t_change_password) flash[:error] = l(:notice_can_t_change_password)
redirect_to my_account_path redirect_to :action => 'account'
return return
end end
if request.post? if request.post?
if !@user.check_password?(params[:password]) if @user.check_password?(params[:password])
flash.now[:error] = l(:notice_account_wrong_password)
elsif params[:password] == params[:new_password]
flash.now[:error] = l(:notice_new_password_must_be_different)
else
@user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation] @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
@user.must_change_passwd = false
if @user.save if @user.save
flash[:notice] = l(:notice_account_password_updated) flash[:notice] = l(:notice_account_password_updated)
redirect_to my_account_path redirect_to :action => 'account'
end end
else
flash[:error] = l(:notice_account_wrong_password)
end end
end end
end end
@@ -117,7 +105,7 @@ class MyController < ApplicationController
User.current.rss_key User.current.rss_key
flash[:notice] = l(:notice_feeds_access_key_reseted) flash[:notice] = l(:notice_feeds_access_key_reseted)
end end
redirect_to my_account_path redirect_to :action => 'account'
end end
# Create a new API key # Create a new API key
@@ -130,7 +118,7 @@ class MyController < ApplicationController
User.current.api_key User.current.api_key
flash[:notice] = l(:notice_api_access_key_reseted) flash[:notice] = l(:notice_api_access_key_reseted)
end end
redirect_to my_account_path redirect_to :action => 'account'
end end
# User's page layout configuration # User's page layout configuration
@@ -138,11 +126,7 @@ class MyController < ApplicationController
@user = User.current @user = User.current
@blocks = @user.pref[:my_page_layout] || DEFAULT_LAYOUT.dup @blocks = @user.pref[:my_page_layout] || DEFAULT_LAYOUT.dup
@block_options = [] @block_options = []
BLOCKS.each do |k, v| BLOCKS.each {|k, v| @block_options << [l("my.blocks.#{v}", :default => [v, v.to_s.humanize]), k.dasherize]}
unless %w(top left right).detect {|f| (@blocks[f] ||= []).include?(k)}
@block_options << [l("my.blocks.#{v}", :default => [v, v.to_s.humanize]), k.dasherize]
end
end
end end
# Add a block to user's page # Add a block to user's page
@@ -150,17 +134,16 @@ class MyController < ApplicationController
# params[:block] : id of the block to add # params[:block] : id of the block to add
def add_block def add_block
block = params[:block].to_s.underscore block = params[:block].to_s.underscore
if block.present? && BLOCKS.key?(block) (render :nothing => true; return) unless block && (BLOCKS.keys.include? block)
@user = User.current @user = User.current
layout = @user.pref[:my_page_layout] || {} layout = @user.pref[:my_page_layout] || {}
# remove if already present in a group # remove if already present in a group
%w(top left right).each {|f| (layout[f] ||= []).delete block } %w(top left right).each {|f| (layout[f] ||= []).delete block }
# add it on top # add it on top
layout['top'].unshift block layout['top'].unshift block
@user.pref[:my_page_layout] = layout @user.pref[:my_page_layout] = layout
@user.pref.save @user.pref.save
end render :partial => "block", :locals => {:user => @user, :block_name => block}
redirect_to my_page_layout_path
end end
# Remove a block to user's page # Remove a block to user's page
@@ -173,7 +156,7 @@ class MyController < ApplicationController
%w(top left right).each {|f| (layout[f] ||= []).delete block } %w(top left right).each {|f| (layout[f] ||= []).delete block }
@user.pref[:my_page_layout] = layout @user.pref[:my_page_layout] = layout
@user.pref.save @user.pref.save
redirect_to my_page_layout_path render :nothing => true
end end
# Change blocks order on user's page # Change blocks order on user's page
@@ -183,8 +166,7 @@ class MyController < ApplicationController
group = params[:group] group = params[:group]
@user = User.current @user = User.current
if group.is_a?(String) if group.is_a?(String)
group_items = (params["blocks"] || []).collect(&:underscore) group_items = (params["list-#{group}"] || []).collect(&:underscore)
group_items.each {|s| s.sub!(/^block_/, '')}
if group_items and group_items.is_a? Array if group_items and group_items.is_a? Array
layout = @user.pref[:my_page_layout] || {} layout = @user.pref[:my_page_layout] || {}
# remove group blocks if they are presents in other groups # remove group blocks if they are presents in other groups
+56 -56
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,42 +17,22 @@
class NewsController < ApplicationController class NewsController < ApplicationController
default_search_scope :news default_search_scope :news
model_object News before_filter :find_news, :except => [:new, :index, :preview]
before_filter :find_model_object, :except => [:new, :create, :index] before_filter :find_project, :only => [:new, :preview]
before_filter :find_project_from_association, :except => [:new, :create, :index] before_filter :authorize, :except => [:index, :preview]
before_filter :find_project_by_project_id, :only => [:new, :create]
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
helper :attachments
def index def index
case params[:format] @news_pages, @newss = paginate :news,
when 'xml', 'json' :per_page => 10,
@offset, @limit = api_offset_and_limit :conditions => Project.allowed_to_condition(User.current, :view_news, :project => @project),
else :include => [:author, :project],
@limit = 10 :order => "#{News.table_name}.created_on DESC"
end
scope = @project ? @project.news.visible : News.visible
@news_count = scope.count
@news_pages = Paginator.new @news_count, @limit, params['page']
@offset ||= @news_pages.offset
@newss = scope.all(:include => [:author, :project],
:order => "#{News.table_name}.created_on DESC",
:offset => @offset,
:limit => @limit)
respond_to do |format| respond_to do |format|
format.html { format.html { render :layout => false if request.xhr? }
@news = News.new # for adding news inline format.xml { render :xml => @newss.to_xml }
render :layout => false if request.xhr? format.json { render :json => @newss.to_json }
}
format.api
format.atom { render_feed(@newss, :title => (@project ? @project.name : Setting.app_title) + ": #{l(:label_news_plural)}") } format.atom { render_feed(@newss, :title => (@project ? @project.name : Setting.app_title) + ": #{l(:label_news_plural)}") }
end end
end end
@@ -64,42 +44,62 @@ class NewsController < ApplicationController
def new def new
@news = News.new(:project => @project, :author => User.current) @news = News.new(:project => @project, :author => User.current)
end if request.post?
@news.attributes = params[:news]
def create if @news.save
@news = News.new(:project => @project, :author => User.current) flash[:notice] = l(:notice_successful_create)
@news.safe_attributes = params[:news] redirect_to :controller => 'news', :action => 'index', :project_id => @project
@news.save_attachments(params[:attachments]) end
if @news.save
render_attachment_warning_if_needed(@news)
flash[:notice] = l(:notice_successful_create)
redirect_to project_news_index_path(@project)
else
render :action => 'new'
end end
end end
def edit def edit
if request.post? and @news.update_attributes(params[:news])
flash[:notice] = l(:notice_successful_update)
redirect_to :action => 'show', :id => @news
end
end end
def update def add_comment
@news.safe_attributes = params[:news] @comment = Comment.new(params[:comment])
@news.save_attachments(params[:attachments]) @comment.author = User.current
if @news.save if @news.comments << @comment
render_attachment_warning_if_needed(@news) flash[:notice] = l(:label_comment_added)
flash[:notice] = l(:notice_successful_update) redirect_to :action => 'show', :id => @news
redirect_to news_path(@news)
else else
render :action => 'edit' show
render :action => 'show'
end end
end end
def destroy_comment
@news.comments.find(params[:comment_id]).destroy
redirect_to :action => 'show', :id => @news
end
def destroy def destroy
@news.destroy @news.destroy
redirect_to project_news_index_path(@project) redirect_to :action => 'index', :project_id => @project
end end
private def preview
@text = (params[:news] ? params[:news][:description] : nil)
render :partial => 'common/preview'
end
private
def find_news
@news = News.find(params[:id])
@project = @news.project
rescue ActiveRecord::RecordNotFound
render_404
end
def find_project
@project = Project.find(params[:project_id])
rescue ActiveRecord::RecordNotFound
render_404
end
def find_optional_project def find_optional_project
return true unless params[:project_id] return true unless params[:project_id]
-53
View File
@@ -1,53 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2013 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
before_filter :find_project, :find_attachments
def issue
@issue = @project.issues.find_by_id(params[:id]) unless params[:id].blank?
if @issue
@description = params[:issue] && params[:issue][:description]
if @description && @description.gsub(/(\r?\n|\n\r?)/, "\n") == @issue.description.to_s.gsub(/(\r?\n|\n\r?)/, "\n")
@description = nil
end
# params[:notes] is useful for preview of notes in issue history
@notes = params[:notes] || (params[:issue] ? params[:issue][:notes] : nil)
else
@description = (params[:issue] ? params[:issue][:description] : nil)
end
render :layout => false
end
def news
if params[:id].present? && news = News.visible.find_by_id(params[:id])
@previewed = news
end
@text = (params[:news] ? params[:news][:description] : nil)
render :partial => 'common/preview'
end
private
def find_project
project_id = (params[:issue] && params[:issue][:project_id]) || params[:project_id]
@project = Project.find(project_id)
rescue ActiveRecord::RecordNotFound
render_404
end
end
@@ -1,42 +0,0 @@
# Redmine - project management software
# Copyright (C) 2006-2013 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 ProjectEnumerationsController < ApplicationController
before_filter :find_project_by_project_id
before_filter :authorize
def update
if request.put? && params[:enumerations]
Project.transaction do
params[:enumerations].each do |id, activity|
@project.update_or_create_time_entry_activity(id, activity)
end
end
flash[:notice] = l(:notice_successful_update)
end
redirect_to settings_project_path(@project, :tab => 'activities')
end
def destroy
@project.time_entry_activities.each do |time_entry_activity|
time_entry_activity.destroy(time_entry_activity.parent)
end
flash[:notice] = l(:notice_successful_update)
redirect_to settings_project_path(@project, :tab => 'activities')
end
end
+278 -123
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -17,19 +17,21 @@
class ProjectsController < ApplicationController class ProjectsController < ApplicationController
menu_item :overview menu_item :overview
menu_item :activity, :only => :activity
menu_item :roadmap, :only => :roadmap menu_item :roadmap, :only => :roadmap
menu_item :files, :only => [:list_files, :add_file]
menu_item :settings, :only => :settings menu_item :settings, :only => :settings
before_filter :find_project, :except => [ :index, :list, :new, :create, :copy ] before_filter :find_project, :except => [ :index, :list, :add, :copy, :activity ]
before_filter :authorize, :except => [ :index, :list, :new, :create, :copy, :archive, :unarchive, :destroy] before_filter :find_optional_project, :only => :activity
before_filter :authorize_global, :only => [:new, :create] before_filter :authorize, :except => [ :index, :list, :add, :copy, :archive, :unarchive, :destroy, :activity ]
before_filter :authorize_global, :only => :add
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 :activity, :index
accept_api_auth :index, :show, :create, :update, :destroy
after_filter :only => [:create, :edit, :update, :archive, :unarchive, :destroy] do |controller| after_filter :only => [:add, :edit, :archive, :unarchive, :destroy] do |controller|
if controller.request.post? if controller.request.post?
controller.send :expire_action, :controller => 'welcome', :action => 'robots' controller.send :expire_action, :controller => 'welcome', :action => 'robots.txt'
end end
end end
@@ -38,171 +40,144 @@ class ProjectsController < ApplicationController
helper :custom_fields helper :custom_fields
include CustomFieldsHelper include CustomFieldsHelper
helper :issues helper :issues
helper IssuesHelper
helper :queries helper :queries
include QueriesHelper include QueriesHelper
helper :repositories helper :repositories
include RepositoriesHelper include RepositoriesHelper
include ProjectsHelper include ProjectsHelper
helper :members
# Lists visible projects # Lists visible projects
def index def index
respond_to do |format| respond_to do |format|
format.html { format.html {
scope = Project @projects = Project.visible.find(:all, :order => 'lft')
unless params[:closed]
scope = scope.active
end
@projects = scope.visible.order('lft').all
}
format.api {
@offset, @limit = api_offset_and_limit
@project_count = Project.visible.count
@projects = Project.visible.offset(@offset).limit(@limit).order('lft').all
} }
format.atom { format.atom {
projects = Project.visible.order('created_on DESC').limit(Setting.feeds_limit.to_i).all projects = Project.visible.find(:all, :order => 'created_on DESC',
:limit => Setting.feeds_limit.to_i)
render_feed(projects, :title => "#{Setting.app_title}: #{l(:label_project_latest)}") render_feed(projects, :title => "#{Setting.app_title}: #{l(:label_project_latest)}")
} }
end end
end end
def new # Add a new project
@issue_custom_fields = IssueCustomField.sorted.all def add
@trackers = Tracker.sorted.all @issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
@project = Project.new @trackers = Tracker.all
@project.safe_attributes = params[:project] @project = Project.new(params[:project])
end if request.get?
@project.identifier = Project.next_identifier if Setting.sequential_project_identifiers?
def create @project.trackers = Tracker.all
@issue_custom_fields = IssueCustomField.sorted.all @project.is_public = Setting.default_projects_public?
@trackers = Tracker.sorted.all @project.enabled_module_names = Setting.default_projects_modules
@project = Project.new
@project.safe_attributes = params[:project]
if validate_parent_id && @project.save
@project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id')
# Add current user as a project member if current user is not admin
unless User.current.admin?
r = Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first
m = Member.new(:user => User.current, :roles => [r])
@project.members << m
end
respond_to do |format|
format.html {
flash[:notice] = l(:notice_successful_create)
if params[:continue]
attrs = {:parent_id => @project.parent_id}.reject {|k,v| v.nil?}
redirect_to new_project_path(attrs)
else
redirect_to settings_project_path(@project)
end
}
format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'projects', :action => 'show', :id => @project.id) }
end
else else
respond_to do |format| @project.enabled_module_names = params[:enabled_modules]
format.html { render :action => 'new' } if validate_parent_id && @project.save
format.api { render_validation_errors(@project) } @project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id')
# Add current user as a project member if he is not admin
unless User.current.admin?
r = Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first
m = Member.new(:user => User.current, :roles => [r])
@project.members << m
end
flash[:notice] = l(:notice_successful_create)
redirect_to :controller => 'projects', :action => 'settings', :id => @project
end end
end end
end end
def copy def copy
@issue_custom_fields = IssueCustomField.sorted.all @issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
@trackers = Tracker.sorted.all @trackers = Tracker.all
@root_projects = Project.find(:all,
:conditions => "parent_id IS NULL AND status = #{Project::STATUS_ACTIVE}",
:order => 'name')
@source_project = Project.find(params[:id]) @source_project = Project.find(params[:id])
if request.get? if request.get?
@project = Project.copy_from(@source_project) @project = Project.copy_from(@source_project)
@project.identifier = Project.next_identifier if Setting.sequential_project_identifiers? if @project
@project.identifier = Project.next_identifier if Setting.sequential_project_identifiers?
else
redirect_to :controller => 'admin', :action => 'projects'
end
else else
Mailer.with_deliveries(params[:notifications] == '1') do Mailer.with_deliveries(params[:notifications] == '1') do
@project = Project.new @project = Project.new(params[:project])
@project.safe_attributes = params[:project] @project.enabled_module_names = params[:enabled_modules]
if validate_parent_id && @project.copy(@source_project, :only => params[:only]) if validate_parent_id && @project.copy(@source_project, :only => params[:only])
@project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id') @project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id')
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to settings_project_path(@project) redirect_to :controller => 'admin', :action => 'projects'
elsif !@project.new_record? elsif !@project.new_record?
# Project was created # Project was created
# But some objects were not copied due to validation failures # But some objects were not copied due to validation failures
# (eg. issues from disabled trackers) # (eg. issues from disabled trackers)
# TODO: inform about that # TODO: inform about that
redirect_to settings_project_path(@project) redirect_to :controller => 'admin', :action => 'projects'
end end
end end
end end
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
# source_project not found redirect_to :controller => 'admin', :action => 'projects'
render_404
end end
# Show @project # Show @project
def show def show
# try to redirect to the requested menu item if params[:jump]
if params[:jump] && redirect_to_project_menu_item(@project, params[:jump]) # try to redirect to the requested menu item
return redirect_to_project_menu_item(@project, params[:jump]) && return
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.limit(5).includes(:author, :project).reorder("#{News.table_name}.created_on DESC").all @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
cond = @project.project_condition(Setting.display_subprojects_issues?) cond = @project.project_condition(Setting.display_subprojects_issues?)
@open_issues_by_tracker = Issue.visible.open.where(cond).count(:group => :tracker) @open_issues_by_tracker = Issue.visible.count(:group => :tracker,
@total_issues_by_tracker = Issue.visible.where(cond).count(:group => :tracker) :include => [:project, :status, :tracker],
:conditions => ["(#{cond}) AND #{IssueStatus.table_name}.is_closed=?", false])
@total_issues_by_tracker = Issue.visible.count(:group => :tracker,
:include => [:project, :status, :tracker],
:conditions => cond)
if User.current.allowed_to?(:view_time_entries, @project) TimeEntry.visible_by(User.current) do
@total_hours = TimeEntry.visible.where(cond).sum(:hours).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|
format.html
format.api
end
end end
def settings def settings
@issue_custom_fields = IssueCustomField.sorted.all @issue_custom_fields = IssueCustomField.find(:all, :order => "#{CustomField.table_name}.position")
@issue_category ||= IssueCategory.new @issue_category ||= IssueCategory.new
@member ||= @project.members.new @member ||= @project.members.new
@trackers = Tracker.sorted.all @trackers = Tracker.all
@repository ||= @project.repository
@wiki ||= @project.wiki @wiki ||= @project.wiki
end end
# Edit @project
def edit def edit
end if request.post?
@project.attributes = params[:project]
def update if validate_parent_id && @project.save
@project.safe_attributes = params[:project] @project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id')
if validate_parent_id && @project.save flash[:notice] = l(:notice_successful_update)
@project.set_allowed_parent!(params[:project]['parent_id']) if params[:project].has_key?('parent_id') redirect_to :action => 'settings', :id => @project
respond_to do |format| else
format.html { settings
flash[:notice] = l(:notice_successful_update) render :action => 'settings'
redirect_to settings_project_path(@project)
}
format.api { render_api_ok }
end
else
respond_to do |format|
format.html {
settings
render :action => 'settings'
}
format.api { render_validation_errors(@project) }
end end
end end
end end
def modules def modules
@project.enabled_module_names = params[:enabled_module_names] @project.enabled_module_names = params[:enabled_modules]
flash[:notice] = l(:notice_successful_update) redirect_to :action => 'settings', :id => @project, :tab => 'modules'
redirect_to settings_project_path(@project, :tab => 'modules')
end end
def archive def archive
@@ -211,39 +186,219 @@ class ProjectsController < ApplicationController
flash[:error] = l(:error_can_not_archive_project) flash[:error] = l(:error_can_not_archive_project)
end end
end end
redirect_to admin_projects_path(:status => params[:status]) redirect_to(url_for(:controller => 'admin', :action => 'projects', :status => params[:status]))
end end
def unarchive def unarchive
@project.unarchive if request.post? && !@project.active? @project.unarchive if request.post? && !@project.active?
redirect_to admin_projects_path(:status => params[:status]) redirect_to(url_for(:controller => 'admin', :action => 'projects', :status => params[:status]))
end
def close
@project.close
redirect_to project_path(@project)
end
def reopen
@project.reopen
redirect_to project_path(@project)
end end
# Delete @project # Delete @project
def destroy def destroy
@project_to_destroy = @project @project_to_destroy = @project
if api_request? || params[:confirm] if request.post? and params[:confirm]
@project_to_destroy.destroy @project_to_destroy.destroy
respond_to do |format| redirect_to :controller => 'admin', :action => 'projects'
format.html { redirect_to admin_projects_path }
format.api { render_api_ok }
end
end end
# hide project in layout # hide project in layout
@project = nil @project = nil
end end
private # Add a new issue category to @project
def add_issue_category
@category = @project.issue_categories.build(params[:category])
if request.post?
if @category.save
respond_to do |format|
format.html do
flash[:notice] = l(:notice_successful_create)
redirect_to :action => 'settings', :tab => 'categories', :id => @project
end
format.js do
# IE doesn't support the replace_html rjs method for select box options
render(:update) {|page| page.replace "issue_category_id",
content_tag('select', '<option></option>' + options_from_collection_for_select(@project.issue_categories, 'id', 'name', @category.id), :id => 'issue_category_id', :name => 'issue[category_id]')
}
end
end
else
respond_to do |format|
format.html
format.js do
render(:update) {|page| page.alert(@category.errors.full_messages.join('\n')) }
end
end
end
end
end
# Add a new version to @project
def add_version
@version = @project.versions.build
if params[:version]
attributes = params[:version].dup
attributes.delete('sharing') unless attributes.nil? || @version.allowed_sharings.include?(attributes['sharing'])
@version.attributes = attributes
end
if request.post?
if @version.save
respond_to do |format|
format.html do
flash[:notice] = l(:notice_successful_create)
redirect_to :action => 'settings', :tab => 'versions', :id => @project
end
format.js do
# IE doesn't support the replace_html rjs method for select box options
render(:update) {|page| page.replace "issue_fixed_version_id",
content_tag('select', '<option></option>' + version_options_for_select(@project.shared_versions.open, @version), :id => 'issue_fixed_version_id', :name => 'issue[fixed_version_id]')
}
end
end
else
respond_to do |format|
format.html
format.js do
render(:update) {|page| page.alert(@version.errors.full_messages.join('\n')) }
end
end
end
end
end
def add_file
if request.post?
container = (params[:version_id].blank? ? @project : @project.versions.find_by_id(params[:version_id]))
attachments = attach_files(container, params[:attachments])
if !attachments.empty? && Setting.notified_events.include?('file_added')
Mailer.deliver_attachments_added(attachments)
end
redirect_to :controller => 'projects', :action => 'list_files', :id => @project
return
end
@versions = @project.versions.sort
end
def save_activities
if request.post? && params[:enumerations]
Project.transaction do
params[:enumerations].each do |id, activity|
@project.update_or_create_time_entry_activity(id, activity)
end
end
end
redirect_to :controller => 'projects', :action => 'settings', :tab => 'activities', :id => @project
end
def reset_activities
@project.time_entry_activities.each do |time_entry_activity|
time_entry_activity.destroy(time_entry_activity.parent)
end
redirect_to :controller => 'projects', :action => 'settings', :tab => 'activities', :id => @project
end
def list_files
sort_init 'filename', 'asc'
sort_update 'filename' => "#{Attachment.table_name}.filename",
'created_on' => "#{Attachment.table_name}.created_on",
'size' => "#{Attachment.table_name}.filesize",
'downloads' => "#{Attachment.table_name}.downloads"
@containers = [ Project.find(@project.id, :include => :attachments, :order => sort_clause)]
@containers += @project.versions.find(:all, :include => :attachments, :order => sort_clause).sort.reverse
render :layout => !request.xhr?
end
def roadmap
@trackers = @project.trackers.find(:all, :order => 'position')
retrieve_selected_tracker_ids(@trackers, @trackers.select {|t| t.is_in_roadmap?})
@with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1')
project_ids = @with_subprojects ? @project.self_and_descendants.collect(&:id) : [@project.id]
@versions = @project.shared_versions.sort
@versions.reject! {|version| version.closed? || version.completed? } unless params[:completed]
@issues_by_version = {}
unless @selected_tracker_ids.empty?
@versions.each do |version|
issues = version.fixed_issues.visible.find(:all,
:include => [:project, :status, :tracker, :priority],
:conditions => {:tracker_id => @selected_tracker_ids, :project_id => project_ids},
:order => "#{Project.table_name}.lft, #{Tracker.table_name}.position, #{Issue.table_name}.id")
@issues_by_version[version] = issues
end
end
@versions.reject! {|version| !project_ids.include?(version.project_id) && @issues_by_version[version].empty?}
end
def activity
@days = Setting.activity_days_default.to_i
if params[:from]
begin; @date_to = params[:from].to_date + 1; rescue; end
end
@date_to ||= Date.today + 1
@date_from = @date_to - @days
@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]))
@activity = Redmine::Activity::Fetcher.new(User.current, :project => @project,
:with_subprojects => @with_subprojects,
:author => @author)
@activity.scope_select {|t| !params["show_#{t}"].nil?}
@activity.scope = (@author.nil? ? :default : :all) if @activity.scope.empty?
events = @activity.events(@date_from, @date_to)
if events.empty? || stale?(:etag => [events.first, User.current])
respond_to do |format|
format.html {
@events_by_day = events.group_by(&:event_date)
render :layout => false if request.xhr?
}
format.atom {
title = l(:label_activity)
if @author
title = @author.name
elsif @activity.scope.size == 1
title = l("label_#{@activity.scope.first.singularize}_plural")
end
render_feed(events, :title => "#{@project || Setting.app_title}: #{title}")
}
end
end
rescue ActiveRecord::RecordNotFound
render_404
end
private
# Find project of id params[:id]
# if not found, redirect to project list
# Used as a before_filter
def find_project
@project = Project.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
def find_optional_project
return true unless params[:id]
@project = Project.find(params[:id])
authorize
rescue ActiveRecord::RecordNotFound
render_404
end
def retrieve_selected_tracker_ids(selectable_trackers, default_trackers=nil)
if ids = params[:tracker_ids]
@selected_tracker_ids = (ids.is_a? Array) ? ids.collect { |id| id.to_i.to_s } : ids.split('/').collect { |id| id.to_i.to_s }
else
@selected_tracker_ids = (default_trackers || selectable_trackers).collect {|t| t.id.to_s }
end
end
# Validates parent_id param according to user's permissions # Validates parent_id param according to user's permissions
# TODO: move it to Project model in a validation that depends on User.current # TODO: move it to Project model in a validation that depends on User.current
+32 -69
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,80 +17,55 @@
class QueriesController < ApplicationController class QueriesController < ApplicationController
menu_item :issues menu_item :issues
before_filter :find_query, :except => [:new, :create, :index] before_filter :find_query, :except => :new
before_filter :find_optional_project, :only => [:new, :create] before_filter :find_optional_project, :only => :new
accept_api_auth :index
include QueriesHelper
def index
case params[:format]
when 'xml', 'json'
@offset, @limit = api_offset_and_limit
else
@limit = per_page_option
end
@query_count = IssueQuery.visible.count
@query_pages = Paginator.new @query_count, @limit, params['page']
@queries = IssueQuery.visible.all(:limit => @limit, :offset => @offset, :order => "#{Query.table_name}.name")
respond_to do |format|
format.api
end
end
def new def new
@query = IssueQuery.new @query = Query.new(params[:query])
@query.user = User.current
@query.project = @project
@query.visibility = IssueQuery::VISIBILITY_PRIVATE unless User.current.allowed_to?(:manage_public_queries, @project) || User.current.admin?
@query.build_from_params(params)
end
def create
@query = IssueQuery.new(params[:query])
@query.user = User.current
@query.project = params[:query_is_for_all] ? nil : @project @query.project = params[:query_is_for_all] ? nil : @project
@query.visibility = IssueQuery::VISIBILITY_PRIVATE unless User.current.allowed_to?(:manage_public_queries, @project) || User.current.admin? @query.user = User.current
@query.build_from_params(params) @query.is_public = false unless User.current.allowed_to?(:manage_public_queries, @project) || User.current.admin?
@query.column_names = nil if params[:default_columns] @query.column_names = nil if params[:default_columns]
if @query.save params[:fields].each do |field|
@query.add_filter(field, params[:operators][field], params[:values][field])
end if params[:fields]
@query.group_by ||= params[:group_by]
if request.post? && params[:confirm] && @query.save
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to_issues(:query_id => @query) redirect_to :controller => 'issues', :action => 'index', :project_id => @project, :query_id => @query
else return
render :action => 'new', :layout => !request.xhr?
end end
render :layout => false if request.xhr?
end end
def edit def edit
end if request.post?
@query.filters = {}
params[:fields].each do |field|
@query.add_filter(field, params[:operators][field], params[:values][field])
end if params[:fields]
@query.attributes = params[:query]
@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.column_names = nil if params[:default_columns]
def update if @query.save
@query.attributes = params[:query] flash[:notice] = l(:notice_successful_update)
@query.project = nil if params[:query_is_for_all] redirect_to :controller => 'issues', :action => 'index', :project_id => @project, :query_id => @query
@query.visibility = IssueQuery::VISIBILITY_PRIVATE unless User.current.allowed_to?(:manage_public_queries, @project) || User.current.admin? end
@query.build_from_params(params)
@query.column_names = nil if params[:default_columns]
if @query.save
flash[:notice] = l(:notice_successful_update)
redirect_to_issues(:query_id => @query)
else
render :action => 'edit'
end end
end end
def destroy def destroy
@query.destroy @query.destroy if request.post?
redirect_to_issues(:set_filter => 1) redirect_to :controller => 'issues', :action => 'index', :project_id => @project, :set_filter => 1
end end
private private
def find_query def find_query
@query = IssueQuery.find(params[:id]) @query = Query.find(params[:id])
@project = @query.project @project = @query.project
render_403 unless @query.editable_by?(User.current) render_403 unless @query.editable_by?(User.current)
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
@@ -103,16 +78,4 @@ private
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
def redirect_to_issues(options)
if params[:gantt]
if @project
redirect_to project_gantt_path(@project, options)
else
redirect_to issues_gantt_path(options)
end
else
redirect_to _project_issues_path(@project, options)
end
end
end end
+147 -42
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,79 +17,184 @@
class ReportsController < ApplicationController class ReportsController < ApplicationController
menu_item :issues menu_item :issues
before_filter :find_project, :authorize, :find_issue_statuses before_filter :find_project, :authorize
def issue_report def issue_report
@trackers = @project.trackers @statuses = IssueStatus.find(:all, :order => 'position')
@versions = @project.shared_versions.sort
@priorities = IssuePriority.all.reverse
@categories = @project.issue_categories
@assignees = (Setting.issue_group_assignment? ? @project.principals : @project.users).sort
@authors = @project.users.sort
@subprojects = @project.descendants.visible
@issues_by_tracker = Issue.by_tracker(@project)
@issues_by_version = Issue.by_version(@project)
@issues_by_priority = Issue.by_priority(@project)
@issues_by_category = Issue.by_category(@project)
@issues_by_assigned_to = Issue.by_assigned_to(@project)
@issues_by_author = Issue.by_author(@project)
@issues_by_subproject = Issue.by_subproject(@project) || []
render :template => "reports/issue_report"
end
def issue_report_details
case params[:detail] case params[:detail]
when "tracker" when "tracker"
@field = "tracker_id" @field = "tracker_id"
@rows = @project.trackers @rows = @project.trackers
@data = Issue.by_tracker(@project) @data = issues_by_tracker
@report_title = l(:field_tracker) @report_title = l(:field_tracker)
render :template => "reports/issue_report_details"
when "version" when "version"
@field = "fixed_version_id" @field = "fixed_version_id"
@rows = @project.shared_versions.sort @rows = @project.shared_versions.sort
@data = Issue.by_version(@project) @data = issues_by_version
@report_title = l(:field_version) @report_title = l(:field_version)
render :template => "reports/issue_report_details"
when "priority" when "priority"
@field = "priority_id" @field = "priority_id"
@rows = IssuePriority.all.reverse @rows = IssuePriority.all
@data = Issue.by_priority(@project) @data = issues_by_priority
@report_title = l(:field_priority) @report_title = l(:field_priority)
render :template => "reports/issue_report_details"
when "category" when "category"
@field = "category_id" @field = "category_id"
@rows = @project.issue_categories @rows = @project.issue_categories
@data = Issue.by_category(@project) @data = issues_by_category
@report_title = l(:field_category) @report_title = l(:field_category)
render :template => "reports/issue_report_details"
when "assigned_to" when "assigned_to"
@field = "assigned_to_id" @field = "assigned_to_id"
@rows = (Setting.issue_group_assignment? ? @project.principals : @project.users).sort @rows = @project.members.collect { |m| m.user }.sort
@data = Issue.by_assigned_to(@project) @data = issues_by_assigned_to
@report_title = l(:field_assigned_to) @report_title = l(:field_assigned_to)
render :template => "reports/issue_report_details"
when "author" when "author"
@field = "author_id" @field = "author_id"
@rows = @project.users.sort @rows = @project.members.collect { |m| m.user }.sort
@data = Issue.by_author(@project) @data = issues_by_author
@report_title = l(:field_author) @report_title = l(:field_author)
render :template => "reports/issue_report_details"
when "subproject" when "subproject"
@field = "project_id" @field = "project_id"
@rows = @project.descendants.visible @rows = @project.descendants.visible
@data = Issue.by_subproject(@project) || [] @data = issues_by_subproject
@report_title = l(:field_subproject) @report_title = l(:field_subproject)
end render :template => "reports/issue_report_details"
else
@trackers = @project.trackers
@versions = @project.shared_versions.sort
@priorities = IssuePriority.all
@categories = @project.issue_categories
@assignees = @project.members.collect { |m| m.user }.sort
@authors = @project.members.collect { |m| m.user }.sort
@subprojects = @project.descendants.visible
issues_by_tracker
issues_by_version
issues_by_priority
issues_by_category
issues_by_assigned_to
issues_by_author
issues_by_subproject
respond_to do |format| render :template => "reports/issue_report"
if @field
format.html {}
else
format.html { redirect_to :action => 'issue_report', :id => @project }
end
end end
end end
private private
# Find project of id params[:id]
def find_project
@project = Project.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
def find_issue_statuses def issues_by_tracker
@statuses = IssueStatus.sorted.all @issues_by_tracker ||=
ActiveRecord::Base.connection.select_all("select s.id as status_id,
s.is_closed as closed,
t.id as tracker_id,
count(i.id) as total
from
#{Issue.table_name} i, #{IssueStatus.table_name} s, #{Tracker.table_name} t
where
i.status_id=s.id
and i.tracker_id=t.id
and i.project_id=#{@project.id}
group by s.id, s.is_closed, t.id")
end
def issues_by_version
@issues_by_version ||=
ActiveRecord::Base.connection.select_all("select s.id as status_id,
s.is_closed as closed,
v.id as fixed_version_id,
count(i.id) as total
from
#{Issue.table_name} i, #{IssueStatus.table_name} s, #{Version.table_name} v
where
i.status_id=s.id
and i.fixed_version_id=v.id
and i.project_id=#{@project.id}
group by s.id, s.is_closed, v.id")
end
def issues_by_priority
@issues_by_priority ||=
ActiveRecord::Base.connection.select_all("select s.id as status_id,
s.is_closed as closed,
p.id as priority_id,
count(i.id) as total
from
#{Issue.table_name} i, #{IssueStatus.table_name} s, #{IssuePriority.table_name} p
where
i.status_id=s.id
and i.priority_id=p.id
and i.project_id=#{@project.id}
group by s.id, s.is_closed, p.id")
end
def issues_by_category
@issues_by_category ||=
ActiveRecord::Base.connection.select_all("select s.id as status_id,
s.is_closed as closed,
c.id as category_id,
count(i.id) as total
from
#{Issue.table_name} i, #{IssueStatus.table_name} s, #{IssueCategory.table_name} c
where
i.status_id=s.id
and i.category_id=c.id
and i.project_id=#{@project.id}
group by s.id, s.is_closed, c.id")
end
def issues_by_assigned_to
@issues_by_assigned_to ||=
ActiveRecord::Base.connection.select_all("select s.id as status_id,
s.is_closed as closed,
a.id as assigned_to_id,
count(i.id) as total
from
#{Issue.table_name} i, #{IssueStatus.table_name} s, #{User.table_name} a
where
i.status_id=s.id
and i.assigned_to_id=a.id
and i.project_id=#{@project.id}
group by s.id, s.is_closed, a.id")
end
def issues_by_author
@issues_by_author ||=
ActiveRecord::Base.connection.select_all("select s.id as status_id,
s.is_closed as closed,
a.id as author_id,
count(i.id) as total
from
#{Issue.table_name} i, #{IssueStatus.table_name} s, #{User.table_name} a
where
i.status_id=s.id
and i.author_id=a.id
and i.project_id=#{@project.id}
group by s.id, s.is_closed, a.id")
end
def issues_by_subproject
@issues_by_subproject ||=
ActiveRecord::Base.connection.select_all("select s.id as status_id,
s.is_closed as closed,
i.project_id as project_id,
count(i.id) as total
from
#{Issue.table_name} i, #{IssueStatus.table_name} s
where
i.status_id=s.id
and i.project_id IN (#{@project.descendants.active.collect{|p| p.id}.join(',')})
group by s.id, s.is_closed, i.project_id") if @project.descendants.active.any?
@issues_by_subproject ||= []
end end
end end
+70 -186
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -18,78 +18,34 @@
require 'SVG/Graph/Bar' require 'SVG/Graph/Bar'
require 'SVG/Graph/BarHorizontal' require 'SVG/Graph/BarHorizontal'
require 'digest/sha1' require 'digest/sha1'
require 'redmine/scm/adapters/abstract_adapter'
class ChangesetNotFound < Exception; end class ChangesetNotFound < Exception; end
class InvalidRevisionParam < Exception; end class InvalidRevisionParam < Exception; end
class RepositoriesController < ApplicationController class RepositoriesController < ApplicationController
menu_item :repository menu_item :repository
menu_item :settings, :only => [:new, :create, :edit, :update, :destroy, :committers]
default_search_scope :changesets default_search_scope :changesets
before_filter :find_project_by_project_id, :only => [:new, :create] before_filter :find_repository, :except => :edit
before_filter :find_repository, :only => [:edit, :update, :destroy, :committers] before_filter :find_project, :only => :edit
before_filter :find_project_repository, :except => [:new, :create, :edit, :update, :destroy, :committers]
before_filter :find_changeset, :only => [:revision, :add_related_issue, :remove_related_issue]
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 new
scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first
@repository = Repository.factory(scm)
@repository.is_default = @project.repository.nil?
@repository.project = @project
end
def create
attrs = pickup_extra_info
@repository = Repository.factory(params[:repository_scm])
@repository.safe_attributes = params[:repository]
if attrs[:attrs_extra].keys.any?
@repository.merge_extra_info(attrs[:attrs_extra])
end
@repository.project = @project
if request.post? && @repository.save
redirect_to settings_project_path(@project, :tab => 'repositories')
else
render :action => 'new'
end
end
def edit def edit
end @repository = @project.repository
if !@repository
def update @repository = Repository.factory(params[:repository_scm])
attrs = pickup_extra_info @repository.project = @project if @repository
@repository.safe_attributes = attrs[:attrs]
if attrs[:attrs_extra].keys.any?
@repository.merge_extra_info(attrs[:attrs_extra])
end end
@repository.project = @project if request.post? && @repository
if request.put? && @repository.save @repository.attributes = params[:repository]
redirect_to settings_project_path(@project, :tab => 'repositories') @repository.save
else
render :action => 'edit'
end end
render(:update) {|page| page.replace_html "tab-content-repository", :partial => 'projects/settings/repository'}
end end
def pickup_extra_info
p = {}
p_extra = {}
params[:repository].each do |k, v|
if k =~ /^extra_/
p_extra[k] = v
else
p[k] = v
end
end
{:attrs => p, :attrs_extra => p_extra}
end
private :pickup_extra_info
def committers def committers
@committers = @repository.committers @committers = @repository.committers
@users = @project.users @users = @project.users
@@ -101,27 +57,25 @@ class RepositoriesController < ApplicationController
# Build a hash with repository usernames as keys and corresponding user ids as values # Build a hash with repository usernames as keys and corresponding user ids as values
@repository.committer_ids = params[:committers].values.inject({}) {|h, c| h[c.first] = c.last; h} @repository.committer_ids = params[:committers].values.inject({}) {|h, c| h[c.first] = c.last; h}
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to settings_project_path(@project, :tab => 'repositories') redirect_to :action => 'committers', :id => @project
end end
end end
def destroy def destroy
@repository.destroy if request.delete? @repository.destroy
redirect_to settings_project_path(@project, :tab => 'repositories') redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'repository'
end end
def show def show
@repository.fetch_changesets if @project.active? && 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
(show_error_not_found; return) unless @entries (show_error_not_found; return) unless @entries
@changesets = @repository.latest_changesets(@path, @rev) @changesets = @repository.latest_changesets(@path, @rev)
@properties = @repository.properties(@path, @rev) @properties = @repository.properties(@path, @rev)
@repositories = @project.repositories
render :action => 'show' render :action => 'show'
end end
end end
@@ -133,19 +87,17 @@ class RepositoriesController < ApplicationController
(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 @changeset_count, @changeset_pages = Paginator.new self, @changeset_count,
per_page_option, per_page_option,
params['page'] params['page']
@changesets = @repository.changesets. @changesets = @repository.changesets.find(:all,
limit(@changeset_pages.per_page). :limit => @changeset_pages.items_per_page,
offset(@changeset_pages.offset). :offset => @changeset_pages.current.offset,
includes(:user, :repository, :parents). :include => [:user, :repository])
all
respond_to do |format| respond_to do |format|
format.html { render :layout => false if request.xhr? } format.html { render :layout => false if request.xhr? }
@@ -153,15 +105,7 @@ class RepositoriesController < ApplicationController
end end
end end
def raw
entry_and_raw(true)
end
def entry def entry
entry_and_raw(false)
end
def entry_and_raw(is_raw)
@entry = @repository.entry(@path, @rev) @entry = @repository.entry(@path, @rev)
(show_error_not_found; return) unless @entry (show_error_not_found; return) unless @entry
@@ -170,82 +114,33 @@ 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 is_raw || 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 => @path.split('/').last
send_type = Redmine::MimeType.of(@path)
send_opt[:type] = send_type.to_s if send_type
send_opt[:disposition] = (Redmine::MimeType.is_type?('image', @path) && !is_raw ? 'inline' : 'attachment')
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
private :entry_and_raw
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)
if @annotate.nil? || @annotate.empty? (render_error l(:error_scm_annotate); return) if @annotate.nil? || @annotate.empty?
(render_error l(:error_scm_annotate); return)
end
ann_buf_size = 0
@annotate.lines.each do |buf|
ann_buf_size += buf.size
end
if ann_buf_size > Setting.file_max_size_displayed.to_i.kilobyte
(render_error l(:error_scm_annotate_big_text_file); return)
end
@changeset = @repository.find_changeset_by_name(@rev)
end end
def revision def revision
@changeset = @repository.find_changeset_by_name(@rev)
raise ChangesetNotFound unless @changeset
respond_to do |format| respond_to do |format|
format.html format.html
format.js {render :layout => false} format.js {render :layout => false}
end end
end rescue ChangesetNotFound
show_error_not_found
# Adds a related issue to a changeset
# POST /projects/:project_id/repository/(:repository_id/)revisions/:rev/issues
def add_related_issue
@issue = @changeset.find_referenced_issue_by_id(params[:issue_id])
if @issue && (!@issue.visible? || @changeset.issues.include?(@issue))
@issue = nil
end
if @issue
@changeset.issues << @issue
end
end
# Removes a related issue from a changeset
# DELETE /projects/:project_id/repository/(:repository_id/)revisions/:rev/issues/:issue_id
def remove_related_issue
@issue = Issue.visible.find_by_id(params[:issue_id])
if @issue
@changeset.issues.delete(@issue)
end
end end
def diff def diff
@@ -266,16 +161,12 @@ class RepositoriesController < ApplicationController
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
end end
@changeset = @repository.find_changeset_by_name(@rev)
@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
@@ -298,49 +189,29 @@ class RepositoriesController < ApplicationController
end end
end end
private private
def find_project
def find_repository @project = Project.find(params[:id])
@repository = Repository.find(params[:id])
@project = @repository.project
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
REV_PARAM_RE = %r{\A[a-f0-9]*\Z}i def find_repository
def find_project_repository
@project = Project.find(params[:id]) @project = Project.find(params[:id])
if params[:repository_id].present? @repository = @project.repository
@repository = @project.repositories.find_by_identifier_param(params[:repository_id])
else
@repository = @project.repository
end
(render_404; return false) unless @repository (render_404; return false) unless @repository
@path = params[:path].is_a?(Array) ? params[:path].join('/') : params[:path].to_s @path = params[:path].join('/') unless params[:path].nil?
@rev = params[:rev].blank? ? @repository.default_branch : params[:rev].to_s.strip @path ||= ''
@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)
if @repository.branches.blank?
raise InvalidRevisionParam
end
end
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
rescue InvalidRevisionParam rescue InvalidRevisionParam
show_error_not_found show_error_not_found
end end
def find_changeset
if @rev.present?
@changeset = @repository.find_changeset_by_name(@rev)
end
show_error_not_found unless @changeset
end
def show_error_not_found def show_error_not_found
render_error :message => l(:error_scm_not_found), :status => 404 render_error l(:error_scm_not_found)
end end
# Handler for Redmine::Scm::Adapters::CommandFailed exception # Handler for Redmine::Scm::Adapters::CommandFailed exception
@@ -352,20 +223,13 @@ class RepositoriesController < ApplicationController
@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 = Changeset. commits_by_day = repository.changesets.count(:all, :group => :commit_date, :conditions => ["commit_date BETWEEN ? AND ?", @date_from, @date_to])
where("repository_id = ? AND commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to).
group(:commit_date).
count
commits_by_month = [0] * 12 commits_by_month = [0] * 12
commits_by_day.each {|c| commits_by_month[(@date_to.month - c.first.to_date.month) % 12] += c.last } commits_by_day.each {|c| commits_by_month[c.first.to_date.months_ago] += c.last }
changes_by_day = Change. changes_by_day = repository.changes.count(:all, :group => :commit_date, :conditions => ["commit_date BETWEEN ? AND ?", @date_from, @date_to])
joins(:changeset).
where("#{Changeset.table_name}.repository_id = ? AND #{Changeset.table_name}.commit_date BETWEEN ? AND ?", repository.id, @date_from, @date_to).
group(:commit_date).
count
changes_by_month = [0] * 12 changes_by_month = [0] * 12
changes_by_day.each {|c| changes_by_month[(@date_to.month - c.first.to_date.month) % 12] += 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)}
@@ -396,10 +260,10 @@ class RepositoriesController < ApplicationController
end end
def graph_commits_per_author(repository) def graph_commits_per_author(repository)
commits_by_author = Changeset.where("repository_id = ?", repository.id).group(:committer).count commits_by_author = repository.changesets.count(:all, :group => :committer)
commits_by_author.to_a.sort! {|x, y| x.last <=> y.last} commits_by_author.to_a.sort! {|x, y| x.last <=> y.last}
changes_by_author = Change.joins(:changeset).where("#{Changeset.table_name}.repository_id = ?", repository.id).group(:committer).count 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}
@@ -414,7 +278,7 @@ class RepositoriesController < ApplicationController
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 => 30 * commits_data.length, :height => 400,
:width => 800, :width => 800,
:fields => fields, :fields => fields,
:stack => :side, :stack => :side,
@@ -424,14 +288,34 @@ 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
class Date
def months_ago(date = Date.today)
(date.year - self.year)*12 + (date.month - self.month)
end
def weeks_ago(date = Date.today)
(date.year - self.year)*52 + (date.cweek - self.cweek)
end
end
class String
def with_leading_slash
starts_with?('/') ? self : "/#{self}"
end
end end
+27 -54
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -18,75 +18,56 @@
class RolesController < ApplicationController class RolesController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin, :except => [:index, :show] before_filter :require_admin
before_filter :require_admin_or_api_request, :only => [:index, :show]
before_filter :find_role, :only => [:show, :edit, :update, :destroy] verify :method => :post, :only => [ :destroy, :move ],
accept_api_auth :index, :show :redirect_to => { :action => :list }
def index def index
respond_to do |format| list
format.html { render :action => 'list' unless request.xhr?
@role_pages, @roles = paginate Role.sorted, :per_page => 25
render :action => "index", :layout => false if request.xhr?
}
format.api {
@roles = Role.givable.all
}
end
end end
def show def list
respond_to do |format| @role_pages, @roles = paginate :roles, :per_page => 25, :order => 'builtin, position'
format.api render :action => "list", :layout => false if request.xhr?
end
end end
def new def new
# Prefills the form with 'Non member' role permissions by default # Prefills the form with 'Non member' role permissions
@role = Role.new(params[:role] || {:permissions => Role.non_member.permissions}) @role = Role.new(params[:role] || {:permissions => Role.non_member.permissions})
if params[:copy].present? && @copy_from = Role.find_by_id(params[:copy])
@role.copy_from(@copy_from)
end
@roles = Role.sorted.all
end
def create
@role = Role.new(params[:role])
if request.post? && @role.save if request.post? && @role.save
# workflow copy # workflow copy
if !params[:copy_workflow_from].blank? && (copy_from = Role.find_by_id(params[:copy_workflow_from])) if !params[:copy_workflow_from].blank? && (copy_from = Role.find_by_id(params[:copy_workflow_from]))
@role.workflow_rules.copy(copy_from) @role.workflows.copy(copy_from)
end end
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to roles_path redirect_to :action => 'index'
else
@roles = Role.sorted.all
render :action => 'new'
end end
@permissions = @role.setable_permissions
@roles = Role.find :all, :order => 'builtin, position'
end end
def edit def edit
end @role = Role.find(params[:id])
if request.post? and @role.update_attributes(params[:role])
def update
if request.put? and @role.update_attributes(params[:role])
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to roles_path redirect_to :action => 'index'
else
render :action => 'edit'
end end
@permissions = @role.setable_permissions
end end
def destroy def destroy
@role = Role.find(params[:id])
@role.destroy @role.destroy
redirect_to roles_path redirect_to :action => 'index'
rescue rescue
flash[:error] = l(:error_can_not_remove_role) flash[:error] = 'This role is in use and can not be deleted.'
redirect_to roles_path redirect_to :action => 'index'
end end
def permissions def report
@roles = Role.sorted.all @roles = Role.find(:all, :order => 'builtin, position')
@permissions = Redmine::AccessControl.permissions.select { |p| !p.public? } @permissions = Redmine::AccessControl.permissions.select { |p| !p.public? }
if request.post? if request.post?
@roles.each do |role| @roles.each do |role|
@@ -94,15 +75,7 @@ class RolesController < ApplicationController
role.save role.save
end end
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to roles_path redirect_to :action => 'index'
end end
end end
private
def find_role
@role = Role.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
end end
+14 -9
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -18,11 +18,14 @@
class SearchController < ApplicationController class SearchController < ApplicationController
before_filter :find_optional_project before_filter :find_optional_project
helper :messages
include MessagesHelper
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]
@@ -31,7 +34,7 @@ class SearchController < ApplicationController
when 'my_projects' when 'my_projects'
User.current.memberships.collect(&:project) User.current.memberships.collect(&:project)
when 'subprojects' when 'subprojects'
@project ? (@project.self_and_descendants.active.all) : nil @project ? (@project.self_and_descendants.active) : nil
else else
@project @project
end end
@@ -40,12 +43,12 @@ class SearchController < ApplicationController
begin; offset = params[:offset].to_time if params[:offset]; rescue; end begin; offset = params[:offset].to_time if params[:offset]; rescue; end
# quick jump to an issue # quick jump to an issue
if (m = @question.match(/^#?(\d+)$/)) && (issue = Issue.visible.find_by_id(m[1].to_i)) if @question.match(/^#?(\d+)$/) && Issue.visible.find_by_id($1)
redirect_to issue_path(issue) redirect_to :controller => "issues", :action => "show", :id => $1
return return
end end
@object_types = Redmine::Search.available_search_types.dup @object_types = %w(issues news documents changesets wiki_pages messages projects)
if projects_to_search.is_a? Project if projects_to_search.is_a? Project
# don't search projects # don't search projects
@object_types.delete('projects') @object_types.delete('projects')
@@ -65,13 +68,15 @@ class SearchController < ApplicationController
if !@tokens.empty? if !@tokens.empty?
# no more than 5 tokens to search for # no more than 5 tokens to search for
@tokens.slice! 5..-1 if @tokens.size > 5 @tokens.slice! 5..-1 if @tokens.size > 5
# strings used in sql like statement
like_tokens = @tokens.collect {|w| "%#{w.downcase}%"}
@results = [] @results = []
@results_by_type = Hash.new {|h,k| h[k] = 0} @results_by_type = Hash.new {|h,k| h[k] = 0}
limit = 10 limit = 10
@scope.each do |s| @scope.each do |s|
r, c = s.singularize.camelcase.constantize.search(@tokens, projects_to_search, r, c = s.singularize.camelcase.constantize.search(like_tokens, projects_to_search,
:all_words => @all_words, :all_words => @all_words,
:titles_only => @titles_only, :titles_only => @titles_only,
:limit => (limit+1), :limit => (limit+1),
+18 -31
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,9 +17,6 @@
class SettingsController < ApplicationController class SettingsController < ApplicationController
layout 'admin' layout 'admin'
menu_item :plugins, :only => :plugin
helper :queries
before_filter :require_admin before_filter :require_admin
@@ -29,45 +26,35 @@ class SettingsController < ApplicationController
end end
def edit def edit
@notifiables = Redmine::Notifiable.all @notifiables = %w(issue_added issue_updated news_added document_added file_added message_posted wiki_content_added wiki_content_updated)
if request.post? && params[:settings] && params[:settings].is_a?(Hash) if request.post? && params[:settings] && params[:settings].is_a?(Hash)
settings = (params[:settings] || {}).dup.symbolize_keys settings = (params[:settings] || {}).dup.symbolize_keys
settings.each do |name, value| settings.each do |name, value|
Setting.set_from_params name, value # remove blank values in array settings
value.delete_if {|v| v.blank? } if value.is_a?(Array)
Setting[name] = value
end end
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to settings_path(:tab => params[:tab]) redirect_to :action => 'edit', :tab => params[:tab]
else return
@options = {}
user_format = User::USER_FORMATS.collect{|key, value| [key, value[:setting_order]]}.sort{|a, b| a[1] <=> b[1]}
@options[:user_format] = user_format.collect{|f| [User.current.name(f[0]), f[0].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?
@commit_update_keywords = Setting.commit_update_keywords.dup
@commit_update_keywords = [{}] unless @commit_update_keywords.is_a?(Array) && @commit_update_keywords.any?
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?
end end
def plugin def plugin
@plugin = Redmine::Plugin.find(params[:id]) @plugin = Redmine::Plugin.find(params[:id])
unless @plugin.configurable?
render_404
return
end
if request.post? if request.post?
Setting.send "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 plugin_settings_path(@plugin) redirect_to :action => 'plugin', :id => @plugin.id
else
@partial = @plugin.settings[:partial]
@settings = Setting.send "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
+10 -23
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -19,12 +19,8 @@ class SysController < ActionController::Base
before_filter :check_enabled before_filter :check_enabled
def projects def projects
p = Project.active.has_module(:repository).order("#{Project.table_name}.identifier").preload(:repository).all p = Project.active.has_module(:repository).find(:all, :include => :repository, :order => 'identifier')
# extra_info attribute from repository breaks activeresource client render :xml => p.to_xml(:include => :repository)
render :xml => p.to_xml(
:only => [:id, :identifier, :name, :is_public, :status],
:include => {:repository => {:only => [:id, :url]}}
)
end end
def create_project_repository def create_project_repository
@@ -33,10 +29,9 @@ class SysController < ActionController::Base
render :nothing => true, :status => 409 render :nothing => true, :status => 409
else else
logger.info "Repository for #{project.name} was reported to be created by #{request.remote_ip}." logger.info "Repository for #{project.name} was reported to be created by #{request.remote_ip}."
repository = Repository.factory(params[:vendor], params[:repository]) project.repository = Repository.factory(params[:vendor], params[:repository])
repository.project = project if project.repository && project.repository.save
if repository.save render :xml => project.repository, :status => 201
render :xml => {repository.class.name.underscore.gsub('/', '-') => {:id => repository.id, :url => repository.url}}, :status => 201
else else
render :nothing => true, :status => 422 render :nothing => true, :status => 422
end end
@@ -45,22 +40,14 @@ class SysController < ActionController::Base
def fetch_changesets def fetch_changesets
projects = [] projects = []
scope = Project.active.has_module(:repository)
if params[:id] if params[:id]
project = nil projects << Project.active.has_module(:repository).find(params[:id])
if params[:id].to_s =~ /^\d*$/
project = scope.find(params[:id])
else
project = scope.find_by_identifier(params[:id])
end
raise ActiveRecord::RecordNotFound unless project
projects << project
else else
projects = scope.all projects = Project.active.has_module(:repository).find(:all, :include => :repository)
end end
projects.each do |project| projects.each do |project|
project.repositories.each do |repository| if project.repository
repository.fetch_changesets project.repository.fetch_changesets
end end
end end
render :nothing => true, :status => 200 render :nothing => true, :status => 200
+234 -223
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,20 +17,10 @@
class TimelogController < ApplicationController class TimelogController < ApplicationController
menu_item :issues menu_item :issues
before_filter :find_project, :authorize, :only => [:edit, :destroy]
before_filter :find_optional_project, :only => [:report, :details]
before_filter :find_project_for_new_time_entry, :only => [:create] verify :method => :post, :only => :destroy, :redirect_to => { :action => :details }
before_filter :find_time_entry, :only => [:show, :edit, :update]
before_filter :find_time_entries, :only => [:bulk_edit, :bulk_update, :destroy]
before_filter :authorize, :except => [:new, :index, :report]
before_filter :find_optional_project, :only => [:index, :report]
before_filter :find_optional_project_for_new_time_entry, :only => [:new]
before_filter :authorize_global, :only => [:new, :index, :report]
accept_rss_auth :index
accept_api_auth :index, :show, :create, :update, :destroy
rescue_from Query::StatementInvalid, :with => :query_statement_invalid
helper :sort helper :sort
include SortHelper include SortHelper
@@ -38,238 +28,228 @@ class TimelogController < ApplicationController
include TimelogHelper include TimelogHelper
helper :custom_fields helper :custom_fields
include CustomFieldsHelper include CustomFieldsHelper
helper :queries
include QueriesHelper
def index
@query = TimeEntryQuery.build_from_params(params, :project => @project, :name => '_')
sort_init(@query.sort_criteria.empty? ? [['spent_on', 'desc']] : @query.sort_criteria)
sort_update(@query.sortable_columns)
scope = time_entry_scope(:order => sort_clause).
includes(:project, :activity, :user, :issue).
preload(:issue => [:project, :tracker, :status, :assigned_to, :priority])
respond_to do |format|
format.html {
@entry_count = scope.count
@entry_pages = Paginator.new @entry_count, per_page_option, params['page']
@entries = scope.offset(@entry_pages.offset).limit(@entry_pages.per_page).all
@total_hours = scope.sum(:hours).to_f
render :layout => !request.xhr?
}
format.api {
@entry_count = scope.count
@offset, @limit = api_offset_and_limit
@entries = scope.offset(@offset).limit(@limit).preload(:custom_values => :custom_field).all
}
format.atom {
entries = scope.limit(Setting.feeds_limit.to_i).reorder("#{TimeEntry.table_name}.created_on DESC").all
render_feed(entries, :title => l(:label_spent_time))
}
format.csv {
# Export all entries
@entries = scope.all
send_data(query_to_csv(@entries, @query, params), :type => 'text/csv; header=present', :filename => 'timelog.csv')
}
end
end
def report def report
@query = TimeEntryQuery.build_from_params(params, :project => @project, :name => '_') @available_criterias = { 'project' => {:sql => "#{TimeEntry.table_name}.project_id",
scope = time_entry_scope :klass => Project,
:label => :label_project},
'version' => {:sql => "#{Issue.table_name}.fixed_version_id",
:klass => Version,
:label => :label_version},
'category' => {:sql => "#{Issue.table_name}.category_id",
:klass => IssueCategory,
:label => :field_category},
'member' => {:sql => "#{TimeEntry.table_name}.user_id",
:klass => User,
:label => :label_member},
'tracker' => {:sql => "#{Issue.table_name}.tracker_id",
:klass => Tracker,
:label => :label_tracker},
'activity' => {:sql => "#{TimeEntry.table_name}.activity_id",
:klass => TimeEntryActivity,
:label => :label_activity},
'issue' => {:sql => "#{TimeEntry.table_name}.issue_id",
:klass => Issue,
:label => :label_issue}
}
@report = Redmine::Helpers::TimeReport.new(@project, @issue, params[:criteria], params[:columns], scope) # Add list and boolean custom fields as available criterias
custom_fields = (@project.nil? ? IssueCustomField.for_all : @project.all_issue_custom_fields)
custom_fields.select {|cf| %w(list bool).include? cf.field_format }.each do |cf|
@available_criterias["cf_#{cf.id}"] = {:sql => "(SELECT c.value FROM #{CustomValue.table_name} c WHERE c.custom_field_id = #{cf.id} AND c.customized_type = 'Issue' AND c.customized_id = #{Issue.table_name}.id)",
:format => cf.field_format,
:label => cf.name}
end if @project
# Add list and boolean time entry custom fields
TimeEntryCustomField.find(:all).select {|cf| %w(list bool).include? cf.field_format }.each do |cf|
@available_criterias["cf_#{cf.id}"] = {:sql => "(SELECT c.value FROM #{CustomValue.table_name} c WHERE c.custom_field_id = #{cf.id} AND c.customized_type = 'TimeEntry' AND c.customized_id = #{TimeEntry.table_name}.id)",
:format => cf.field_format,
:label => cf.name}
end
# Add list and boolean time entry activity custom fields
TimeEntryActivityCustomField.find(:all).select {|cf| %w(list bool).include? cf.field_format }.each do |cf|
@available_criterias["cf_#{cf.id}"] = {:sql => "(SELECT c.value FROM #{CustomValue.table_name} c WHERE c.custom_field_id = #{cf.id} AND c.customized_type = 'Enumeration' AND c.customized_id = #{TimeEntry.table_name}.activity_id)",
:format => cf.field_format,
:label => cf.name}
end
@criterias = params[:criterias] || []
@criterias = @criterias.select{|criteria| @available_criterias.has_key? criteria}
@criterias.uniq!
@criterias = @criterias[0,3]
@columns = (params[:columns] && %w(year month week day).include?(params[:columns])) ? params[:columns] : 'month'
retrieve_date_range
unless @criterias.empty?
sql_select = @criterias.collect{|criteria| @available_criterias[criteria][:sql] + " AS " + criteria}.join(', ')
sql_group_by = @criterias.collect{|criteria| @available_criterias[criteria][:sql]}.join(', ')
sql_condition = ''
if @project.nil?
sql_condition = Project.allowed_to_condition(User.current, :view_time_entries)
elsif @issue.nil?
sql_condition = @project.project_condition(Setting.display_subprojects_issues?)
else
sql_condition = "#{TimeEntry.table_name}.issue_id = #{@issue.id}"
end
sql = "SELECT #{sql_select}, tyear, tmonth, tweek, spent_on, SUM(hours) AS hours"
sql << " FROM #{TimeEntry.table_name}"
sql << " LEFT JOIN #{Issue.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id"
sql << " LEFT JOIN #{Project.table_name} ON #{TimeEntry.table_name}.project_id = #{Project.table_name}.id"
sql << " WHERE"
sql << " (%s) AND" % sql_condition
sql << " (spent_on BETWEEN '%s' AND '%s')" % [ActiveRecord::Base.connection.quoted_date(@from), ActiveRecord::Base.connection.quoted_date(@to)]
sql << " GROUP BY #{sql_group_by}, tyear, tmonth, tweek, spent_on"
@hours = ActiveRecord::Base.connection.select_all(sql)
@hours.each do |row|
case @columns
when 'year'
row['year'] = row['tyear']
when 'month'
row['month'] = "#{row['tyear']}-#{row['tmonth']}"
when 'week'
row['week'] = "#{row['tyear']}-#{row['tweek']}"
when 'day'
row['day'] = "#{row['spent_on']}"
end
end
@total_hours = @hours.inject(0) {|s,k| s = s + k['hours'].to_f}
@periods = []
# Date#at_beginning_of_ not supported in Rails 1.2.x
date_from = @from.to_time
# 100 columns max
while date_from <= @to.to_time && @periods.length < 100
case @columns
when 'year'
@periods << "#{date_from.year}"
date_from = (date_from + 1.year).at_beginning_of_year
when 'month'
@periods << "#{date_from.year}-#{date_from.month}"
date_from = (date_from + 1.month).at_beginning_of_month
when 'week'
@periods << "#{date_from.year}-#{date_from.to_date.cweek}"
date_from = (date_from + 7.day).at_beginning_of_week
when 'day'
@periods << "#{date_from.to_date}"
date_from = date_from + 1.day
end
end
end
respond_to do |format| respond_to do |format|
format.html { render :layout => !request.xhr? } format.html { render :layout => !request.xhr? }
format.csv { send_data(report_to_csv(@report), :type => 'text/csv; header=present', :filename => 'timelog.csv') } format.csv { send_data(report_to_csv(@criterias, @periods, @hours), :type => 'text/csv; header=present', :filename => 'timelog.csv') }
end end
end end
def show def details
respond_to do |format| sort_init 'spent_on', 'desc'
# TODO: Implement html response sort_update 'spent_on' => 'spent_on',
format.html { render :nothing => true, :status => 406 } 'user' => 'user_id',
format.api 'activity' => 'activity_id',
'project' => "#{Project.table_name}.name",
'issue' => 'issue_id',
'hours' => 'hours'
cond = ARCondition.new
if @project.nil?
cond << Project.allowed_to_condition(User.current, :view_time_entries)
elsif @issue.nil?
cond << @project.project_condition(Setting.display_subprojects_issues?)
else
cond << ["#{TimeEntry.table_name}.issue_id = ?", @issue.id]
end end
end
def new retrieve_date_range
@time_entry ||= TimeEntry.new(:project => @project, :issue => @issue, :user => User.current, :spent_on => User.current.today) cond << ['spent_on BETWEEN ? AND ?', @from, @to]
@time_entry.safe_attributes = params[:time_entry]
end
def create TimeEntry.visible_by(User.current) do
@time_entry ||= TimeEntry.new(:project => @project, :issue => @issue, :user => User.current, :spent_on => User.current.today)
@time_entry.safe_attributes = params[:time_entry]
call_hook(:controller_timelog_edit_before_save, { :params => params, :time_entry => @time_entry })
if @time_entry.save
respond_to do |format| respond_to do |format|
format.html { format.html {
flash[:notice] = l(:notice_successful_create) # Paginate results
if params[:continue] @entry_count = TimeEntry.count(:include => :project, :conditions => cond.conditions)
if params[:project_id] @entry_pages = Paginator.new self, @entry_count, per_page_option, params['page']
options = { @entries = TimeEntry.find(:all,
:time_entry => {:issue_id => @time_entry.issue_id, :activity_id => @time_entry.activity_id}, :include => [:project, :activity, :user, {:issue => :tracker}],
:back_url => params[:back_url] :conditions => cond.conditions,
} :order => sort_clause,
if @time_entry.issue :limit => @entry_pages.items_per_page,
redirect_to new_project_issue_time_entry_path(@time_entry.project, @time_entry.issue, options) :offset => @entry_pages.current.offset)
else @total_hours = TimeEntry.sum(:hours, :include => :project, :conditions => cond.conditions).to_f
redirect_to new_project_time_entry_path(@time_entry.project, options)
end render :layout => !request.xhr?
else }
options = { format.atom {
:time_entry => {:project_id => @time_entry.project_id, :issue_id => @time_entry.issue_id, :activity_id => @time_entry.activity_id}, entries = TimeEntry.find(:all,
:back_url => params[:back_url] :include => [:project, :activity, :user, {:issue => :tracker}],
} :conditions => cond.conditions,
redirect_to new_time_entry_path(options) :order => "#{TimeEntry.table_name}.created_on DESC",
end :limit => Setting.feeds_limit.to_i)
else render_feed(entries, :title => l(:label_spent_time))
redirect_back_or_default project_time_entries_path(@time_entry.project) }
end format.csv {
# Export all entries
@entries = TimeEntry.find(:all,
:include => [:project, :activity, :user, {:issue => [:tracker, :assigned_to, :priority]}],
:conditions => cond.conditions,
:order => sort_clause)
send_data(entries_to_csv(@entries), :type => 'text/csv; header=present', :filename => 'timelog.csv')
} }
format.api { render :action => 'show', :status => :created, :location => time_entry_url(@time_entry) }
end
else
respond_to do |format|
format.html { render :action => 'new' }
format.api { render_validation_errors(@time_entry) }
end end
end end
end end
def edit def edit
@time_entry.safe_attributes = params[:time_entry] (render_403; return) if @time_entry && !@time_entry.editable_by?(User.current)
end @time_entry ||= TimeEntry.new(:project => @project, :issue => @issue, :user => User.current, :spent_on => User.current.today)
@time_entry.attributes = params[:time_entry]
def update
@time_entry.safe_attributes = params[:time_entry]
call_hook(:controller_timelog_edit_before_save, { :params => params, :time_entry => @time_entry }) call_hook(:controller_timelog_edit_before_save, { :params => params, :time_entry => @time_entry })
if @time_entry.save if request.post? and @time_entry.save
respond_to do |format| flash[:notice] = l(:notice_successful_update)
format.html { redirect_back_or_default :action => 'details', :project_id => @time_entry.project
flash[:notice] = l(:notice_successful_update) return
redirect_back_or_default project_time_entries_path(@time_entry.project)
}
format.api { render_api_ok }
end
else
respond_to do |format|
format.html { render :action => 'edit' }
format.api { render_validation_errors(@time_entry) }
end
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.safe_attributes = attributes
call_hook(:controller_time_entries_bulk_edit_before_save, { :params => params, :time_entry => time_entry })
unless time_entry.save
logger.info "time entry could not be updated: #{time_entry.errors.full_messages}" if logger && logger.info
# 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 project_time_entries_path(@projects.first)
end
def destroy def destroy
destroyed = TimeEntry.transaction do (render_404; return) unless @time_entry
@time_entries.each do |t| (render_403; return) unless @time_entry.editable_by?(User.current)
unless t.destroy && t.destroyed? @time_entry.destroy
raise ActiveRecord::Rollback flash[:notice] = l(:notice_successful_delete)
end redirect_to :back
end rescue ::ActionController::RedirectBackError
end redirect_to :action => 'details', :project_id => @time_entry.project
respond_to do |format|
format.html {
if destroyed
flash[:notice] = l(:notice_successful_delete)
else
flash[:error] = l(:notice_unable_delete_time_entry)
end
redirect_back_or_default project_time_entries_path(@projects.first)
}
format.api {
if destroyed
render_api_ok
else
render_validation_errors(@time_entries)
end
}
end
end end
private private
def find_time_entry def find_project
@time_entry = TimeEntry.find(params[:id]) if params[:id]
unless @time_entry.editable_by?(User.current) @time_entry = TimeEntry.find(params[:id])
render_403 @project = @time_entry.project
elsif params[:issue_id]
@issue = Issue.find(params[:issue_id])
@project = @issue.project
elsif params[:project_id]
@project = Project.find(params[:project_id])
else
render_404
return false return false
end end
@project = @time_entry.project
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
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_optional_project_for_new_time_entry
if (project_id = (params[:project_id] || params[:time_entry] && params[:time_entry][:project_id])).present?
@project = Project.find(project_id)
end
if (issue_id = (params[:issue_id] || params[:time_entry] && params[:time_entry][:issue_id])).present?
@issue = Issue.find(issue_id)
@project ||= @issue.project
end
rescue ActiveRecord::RecordNotFound
render_404
end
def find_project_for_new_time_entry
find_optional_project_for_new_time_entry
if @project.nil?
render_404
end
end
def find_optional_project def find_optional_project
if !params[:issue_id].blank? if !params[:issue_id].blank?
@issue = Issue.find(params[:issue_id]) @issue = Issue.find(params[:issue_id])
@@ -277,21 +257,52 @@ private
elsif !params[:project_id].blank? elsif !params[:project_id].blank?
@project = Project.find(params[:project_id]) @project = Project.find(params[:project_id])
end end
deny_access unless User.current.allowed_to?(:view_time_entries, @project, :global => true)
end end
# Returns the TimeEntry scope for index and report actions # Retrieves the date range based on predefined ranges or specific from/to param dates
def time_entry_scope(options={}) def retrieve_date_range
scope = @query.results_scope(options) @free_period = false
if @issue @from, @to = nil, nil
scope = scope.on_issue(@issue)
if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)
case params[:period].to_s
when 'today'
@from = @to = Date.today
when 'yesterday'
@from = @to = Date.today - 1
when 'current_week'
@from = Date.today - (Date.today.cwday - 1)%7
@to = @from + 6
when 'last_week'
@from = Date.today - 7 - (Date.today.cwday - 1)%7
@to = @from + 6
when '7_days'
@from = Date.today - 7
@to = Date.today
when 'current_month'
@from = Date.civil(Date.today.year, Date.today.month, 1)
@to = (@from >> 1) - 1
when 'last_month'
@from = Date.civil(Date.today.year, Date.today.month, 1) << 1
@to = (@from >> 1) - 1
when '30_days'
@from = Date.today - 30
@to = Date.today
when 'current_year'
@from = Date.civil(Date.today.year, 1, 1)
@to = Date.civil(Date.today.year, 12, 31)
end
elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))
begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end
begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end
@free_period = true
else
# default
end end
scope
end
def parse_params_for_bulk_time_entry_attributes(params) @from, @to = @to, @from if @from && @to && @from > @to
attributes = (params[:time_entry] || {}).reject {|k,v| v.blank?} @from ||= (TimeEntry.minimum(:spent_on, :include => :project, :conditions => Project.allowed_to_condition(User.current, :view_time_entries)) || Date.today) - 1
attributes.keys.each {|k| attributes[k] = '' if attributes[k] == 'none'} @to ||= (TimeEntry.maximum(:spent_on, :include => :project, :conditions => Project.allowed_to_condition(User.current, :view_time_entries)) || Date.today)
attributes[:custom_field_values].reject! {|k,v| v.blank?} if attributes[:custom_field_values]
attributes
end end
end end
+21 -53
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -18,84 +18,52 @@
class TrackersController < ApplicationController class TrackersController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin, :except => :index before_filter :require_admin
before_filter :require_admin_or_api_request, :only => :index
accept_api_auth :index
def index def index
respond_to do |format| list
format.html { render :action => 'list' unless request.xhr?
@tracker_pages, @trackers = paginate Tracker.sorted, :per_page => 25 end
render :action => "index", :layout => false if request.xhr?
} verify :method => :post, :only => :destroy, :redirect_to => { :action => :list }
format.api {
@trackers = Tracker.sorted.all def list
} @tracker_pages, @trackers = paginate :trackers, :per_page => 10, :order => 'position'
end render :action => "list", :layout => false if request.xhr?
end end
def new def new
@tracker ||= Tracker.new(params[:tracker])
@trackers = Tracker.sorted.all
@projects = Project.all
end
def create
@tracker = Tracker.new(params[:tracker]) @tracker = Tracker.new(params[:tracker])
if @tracker.save if request.post? and @tracker.save
# workflow copy # workflow copy
if !params[:copy_workflow_from].blank? && (copy_from = Tracker.find_by_id(params[:copy_workflow_from])) if !params[:copy_workflow_from].blank? && (copy_from = Tracker.find_by_id(params[:copy_workflow_from]))
@tracker.workflow_rules.copy(copy_from) @tracker.workflows.copy(copy_from)
end end
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
redirect_to trackers_path redirect_to :action => 'list'
return return
end end
new @trackers = Tracker.find :all, :order => 'position'
render :action => 'new' @projects = Project.find(:all)
end end
def edit def edit
@tracker ||= Tracker.find(params[:id])
@projects = Project.all
end
def update
@tracker = Tracker.find(params[:id]) @tracker = Tracker.find(params[:id])
if @tracker.update_attributes(params[:tracker]) if request.post? and @tracker.update_attributes(params[:tracker])
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to trackers_path redirect_to :action => 'list'
return return
end end
edit @projects = Project.find(:all)
render :action => 'edit'
end end
def destroy def destroy
@tracker = Tracker.find(params[:id]) @tracker = Tracker.find(params[:id])
unless @tracker.issues.empty? unless @tracker.issues.empty?
flash[:error] = l(:error_can_not_delete_tracker) flash[:error] = "This tracker contains issues and can\'t be deleted."
else else
@tracker.destroy @tracker.destroy
end end
redirect_to trackers_path redirect_to :action => 'list'
end
def fields
if request.post? && params[:trackers]
params[:trackers].each do |tracker_id, tracker_params|
tracker = Tracker.find_by_id(tracker_id)
if tracker
tracker.core_fields = tracker_params[:core_fields]
tracker.custom_field_ids = tracker_params[:custom_field_ids]
tracker.save
end
end
flash[:notice] = l(:notice_successful_update)
redirect_to fields_trackers_path
return
end
@trackers = Tracker.sorted.all
@custom_fields = IssueCustomField.all.sort
end end
end end
+100 -164
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -19,8 +19,6 @@ 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]
accept_api_auth :index, :show, :create, :update, :destroy
helper :sort helper :sort
include SortHelper include SortHelper
@@ -31,180 +29,118 @@ class UsersController < ApplicationController
sort_init 'login', 'asc' sort_init 'login', 'asc'
sort_update %w(login firstname lastname mail admin created_on last_login_on) sort_update %w(login firstname lastname mail admin created_on last_login_on)
case params[:format] @status = params[:status] ? params[:status].to_i : 1
when 'xml', 'json' c = ARCondition.new(@status == 0 ? "status <> 0" : ["status = ?", @status])
@offset, @limit = api_offset_and_limit
else unless params[:name].blank?
@limit = per_page_option name = "%#{params[:name].strip.downcase}%"
c << ["LOWER(login) LIKE ? OR LOWER(firstname) LIKE ? OR LOWER(lastname) LIKE ? OR LOWER(mail) LIKE ?", name, name, name, name]
end end
@status = params[:status] || 1 @user_count = User.count(:conditions => c.conditions)
@user_pages = Paginator.new self, @user_count,
per_page_option,
params['page']
@users = User.find :all,:order => sort_clause,
:conditions => c.conditions,
:limit => @user_pages.items_per_page,
:offset => @user_pages.current.offset
scope = User.logged.status(@status) render :layout => !request.xhr?
scope = scope.like(params[:name]) if params[:name].present?
scope = scope.in_group(params[:group_id]) if params[:group_id].present?
@user_count = scope.count
@user_pages = Paginator.new @user_count, @limit, params['page']
@offset ||= @user_pages.offset
@users = scope.order(sort_clause).limit(@limit).offset(@offset).all
respond_to do |format|
format.html {
@groups = Group.all.sort
render :layout => !request.xhr?
}
format.api
end
end end
def show def show
# show projects based on current user visibility @user = User.active.find(params[:id])
@memberships = @user.memberships.where(Project.visible_condition(User.current)).all @custom_values = @user.custom_values
# show only public projects and private projects that the logged in user is also a member of
@memberships = @user.memberships.select do |membership|
membership.project.is_public? || (User.current.member_of?(membership.project))
end
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)
unless User.current.admin? if @user != User.current && !User.current.admin? && @memberships.empty? && events.empty?
if !@user.active? || (@user != User.current && @memberships.empty? && events.empty?) render_404
render_404 return
return
end
end end
render :layout => 'base'
respond_to do |format|
format.html { render :layout => 'base' }
format.api
end
end
def new
@user = User.new(:language => Setting.default_language, :mail_notification => Setting.default_notification_option)
@user.safe_attributes = params[:user]
@auth_sources = AuthSource.all
end
def create
@user = User.new(:language => Setting.default_language, :mail_notification => Setting.default_notification_option)
@user.safe_attributes = params[:user]
@user.admin = params[:user][:admin] || false
@user.login = params[:user][:login]
@user.password, @user.password_confirmation = params[:user][:password], params[:user][:password_confirmation] unless @user.auth_source_id
if @user.save
@user.pref.attributes = params[:pref]
@user.pref.save
Mailer.account_information(@user, @user.password).deliver if params[:send_information]
respond_to do |format|
format.html {
flash[:notice] = l(:notice_user_successful_create, :id => view_context.link_to(@user.login, user_path(@user)))
if params[:continue]
attrs = params[:user].slice(:generate_password)
redirect_to new_user_path(:user => attrs)
else
redirect_to edit_user_path(@user)
end
}
format.api { render :action => 'show', :status => :created, :location => user_url(@user) }
end
else
@auth_sources = AuthSource.all
# Clear password input
@user.password = @user.password_confirmation = nil
respond_to do |format|
format.html { render :action => 'new' }
format.api { render_validation_errors(@user) }
end
end
end
def edit
@auth_sources = AuthSource.all
@membership ||= Member.new
end
def update
@user.admin = params[:user][:admin] if params[:user][:admin]
@user.login = params[:user][:login] if params[:user][:login]
if params[:user][:password].present? && (@user.auth_source_id.nil? || params[:user][:auth_source_id].blank?)
@user.password, @user.password_confirmation = params[:user][:password], params[:user][:password_confirmation]
end
@user.safe_attributes = params[:user]
# Was the account actived ? (do it before User#save clears the change)
was_activated = (@user.status_change == [User::STATUS_REGISTERED, User::STATUS_ACTIVE])
# TODO: Similar to My#account
@user.pref.attributes = params[:pref]
if @user.save
@user.pref.save
if was_activated
Mailer.account_activated(@user).deliver
elsif @user.active? && params[:send_information] && @user.password.present? && @user.auth_source_id.nil?
Mailer.account_information(@user, @user.password).deliver
end
respond_to do |format|
format.html {
flash[:notice] = l(:notice_successful_update)
redirect_to_referer_or edit_user_path(@user)
}
format.api { render_api_ok }
end
else
@auth_sources = AuthSource.all
@membership ||= Member.new
# Clear password input
@user.password = @user.password_confirmation = nil
respond_to do |format|
format.html { render :action => :edit }
format.api { render_validation_errors(@user) }
end
end
end
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_back_or_default(users_path) }
format.api { render_api_ok }
end
end
def edit_membership
@membership = Member.edit_membership(params[:membership_id], params[:membership], @user)
@membership.save
respond_to do |format|
format.html { redirect_to edit_user_path(@user, :tab => 'memberships') }
format.js
end
end
def destroy_membership
@membership = Member.find(params[:membership_id])
if @membership.deletable?
@membership.destroy
end
respond_to do |format|
format.html { redirect_to edit_user_path(@user, :tab => 'memberships') }
format.js
end
end
private
def find_user
if params[:id] == 'current'
require_login || return
@user = User.current
else
@user = User.find(params[:id])
end
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
render_404 render_404
end end
def add
if request.get?
@user = User.new(:language => Setting.default_language)
else
@user = User.new(params[:user])
@user.admin = params[:user][:admin] || false
@user.login = params[:user][:login]
@user.password, @user.password_confirmation = params[:password], params[:password_confirmation] unless @user.auth_source_id
if @user.save
Mailer.deliver_account_information(@user, params[:password]) if params[:send_information]
flash[:notice] = l(:notice_successful_create)
redirect_to(params[:continue] ? {:controller => 'users', :action => 'add'} :
{:controller => 'users', :action => 'edit', :id => @user})
return
end
end
@auth_sources = AuthSource.find(:all)
end
def edit
@user = User.find(params[:id])
if request.post?
@user.admin = params[:user][:admin] if params[:user][:admin]
@user.login = params[:user][:login] if params[:user][:login]
@user.password, @user.password_confirmation = params[:password], params[:password_confirmation] unless params[:password].nil? or params[:password].empty? or @user.auth_source_id
@user.group_ids = params[:user][:group_ids] if params[:user][:group_ids]
@user.attributes = params[:user]
# Was the account actived ? (do it before User#save clears the change)
was_activated = (@user.status_change == [User::STATUS_REGISTERED, User::STATUS_ACTIVE])
if @user.save
if was_activated
Mailer.deliver_account_activated(@user)
elsif @user.active? && params[:send_information] && !params[:password].blank? && @user.auth_source_id.nil?
Mailer.deliver_account_information(@user, params[:password])
end
flash[:notice] = l(:notice_successful_update)
redirect_to :back
end
end
@auth_sources = AuthSource.find(:all)
@membership ||= Member.new
rescue ::ActionController::RedirectBackError
redirect_to :controller => 'users', :action => 'edit', :id => @user
end
def edit_membership
@user = User.find(params[:id])
@membership = params[:membership_id] ? Member.find(params[:membership_id]) : Member.new(:principal => @user)
@membership.attributes = params[:membership]
@membership.save if request.post?
respond_to do |format|
format.html { redirect_to :controller => 'users', :action => 'edit', :id => @user, :tab => 'memberships' }
format.js {
render(:update) {|page|
page.replace_html "tab-content-memberships", :partial => 'users/memberships'
page.visual_effect(:highlight, "member-#{@membership.id}")
}
}
end
end
def destroy_membership
@user = User.find(params[:id])
@membership = Member.find(params[:membership_id])
if request.post? && @membership.deletable?
@membership.destroy
end
respond_to do |format|
format.html { redirect_to :controller => 'users', :action => 'edit', :id => @user, :tab => 'memberships' }
format.js { render(:update) {|page| page.replace_html "tab-content-memberships", :partial => 'users/memberships'} }
end
end
end end
+28 -129
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,166 +17,65 @@
class VersionsController < ApplicationController class VersionsController < ApplicationController
menu_item :roadmap menu_item :roadmap
model_object Version before_filter :find_version, :except => :close_completed
before_filter :find_model_object, :except => [:index, :new, :create, :close_completed] before_filter :find_project, :only => :close_completed
before_filter :find_project_from_association, :except => [:index, :new, :create, :close_completed]
before_filter :find_project_by_project_id, :only => [:index, :new, :create, :close_completed]
before_filter :authorize before_filter :authorize
accept_api_auth :index, :show, :create, :update, :destroy
helper :custom_fields helper :custom_fields
helper :projects helper :projects
def index
respond_to do |format|
format.html {
@trackers = @project.trackers.sorted.all
retrieve_selected_tracker_ids(@trackers, @trackers.select {|t| t.is_in_roadmap?})
@with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1')
project_ids = @with_subprojects ? @project.self_and_descendants.collect(&:id) : [@project.id]
@versions = @project.shared_versions || []
@versions += @project.rolled_up_versions.visible if @with_subprojects
@versions = @versions.uniq.sort
unless params[:completed]
@completed_versions = @versions.select {|version| version.closed? || version.completed? }
@versions -= @completed_versions
end
@issues_by_version = {}
if @selected_tracker_ids.any? && @versions.any?
issues = Issue.visible.
includes(:project, :tracker).
preload(:status, :priority, :fixed_version).
where(:tracker_id => @selected_tracker_ids, :project_id => project_ids, :fixed_version_id => @versions.map(&:id)).
order("#{Project.table_name}.lft, #{Tracker.table_name}.position, #{Issue.table_name}.id")
@issues_by_version = issues.group_by(&:fixed_version)
end
@versions.reject! {|version| !project_ids.include?(version.project_id) && @issues_by_version[version].blank?}
}
format.api {
@versions = @project.shared_versions.all
}
end
end
def show def show
respond_to do |format| @issues = @version.fixed_issues.visible.find(:all,
format.html { :include => [:status, :tracker, :priority],
@issues = @version.fixed_issues.visible. :order => "#{Tracker.table_name}.position, #{Issue.table_name}.id")
includes(:status, :tracker, :priority).
reorder("#{Tracker.table_name}.position, #{Issue.table_name}.id").
all
}
format.api
end
end
def new
@version = @project.versions.build
@version.safe_attributes = params[:version]
respond_to do |format|
format.html
format.js
end
end
def create
@version = @project.versions.build
if params[:version]
attributes = params[:version].dup
attributes.delete('sharing') unless attributes.nil? || @version.allowed_sharings.include?(attributes['sharing'])
@version.safe_attributes = attributes
end
if request.post?
if @version.save
respond_to do |format|
format.html do
flash[:notice] = l(:notice_successful_create)
redirect_back_or_default settings_project_path(@project, :tab => 'versions')
end
format.js
format.api do
render :action => 'show', :status => :created, :location => version_url(@version)
end
end
else
respond_to do |format|
format.html { render :action => 'new' }
format.js { render :action => 'new' }
format.api { render_validation_errors(@version) }
end
end
end
end end
def edit def edit
end if request.post? && params[:version]
def update
if request.put? && params[:version]
attributes = params[:version].dup attributes = params[:version].dup
attributes.delete('sharing') unless @version.allowed_sharings.include?(attributes['sharing']) attributes.delete('sharing') unless @version.allowed_sharings.include?(attributes['sharing'])
@version.safe_attributes = attributes if @version.update_attributes(attributes)
if @version.save flash[:notice] = l(:notice_successful_update)
respond_to do |format| redirect_to :controller => 'projects', :action => 'settings', :tab => 'versions', :id => @project
format.html {
flash[:notice] = l(:notice_successful_update)
redirect_back_or_default settings_project_path(@project, :tab => 'versions')
}
format.api { render_api_ok }
end
else
respond_to do |format|
format.html { render :action => 'edit' }
format.api { render_validation_errors(@version) }
end
end end
end end
end end
def close_completed def close_completed
if request.put? if request.post?
@project.close_completed_versions @project.close_completed_versions
end end
redirect_to settings_project_path(@project, :tab => 'versions') redirect_to :controller => 'projects', :action => 'settings', :tab => 'versions', :id => @project
end end
def destroy def destroy
if @version.fixed_issues.empty? if @version.fixed_issues.empty?
@version.destroy @version.destroy
respond_to do |format| redirect_to :controller => 'projects', :action => 'settings', :tab => 'versions', :id => @project
format.html { redirect_back_or_default settings_project_path(@project, :tab => 'versions') }
format.api { render_api_ok }
end
else else
respond_to do |format| flash[:error] = l(:notice_unable_delete_version)
format.html { redirect_to :controller => 'projects', :action => 'settings', :tab => 'versions', :id => @project
flash[:error] = l(:notice_unable_delete_version)
redirect_to settings_project_path(@project, :tab => 'versions')
}
format.api { head :unprocessable_entity }
end
end end
end end
def status_by def status_by
respond_to do |format| respond_to do |format|
format.html { render :action => 'show' } format.html { render :action => 'show' }
format.js format.js { render(:update) {|page| page.replace_html 'status_by', render_issue_status_by(@version, params[:status_by])} }
end end
end end
private private
def find_version
@version = Version.find(params[:id])
@project = @version.project
rescue ActiveRecord::RecordNotFound
render_404
end
def retrieve_selected_tracker_ids(selectable_trackers, default_trackers=nil) def find_project
if ids = params[:tracker_ids] @project = Project.find(params[:project_id])
@selected_tracker_ids = (ids.is_a? Array) ? ids.collect { |id| id.to_i.to_s } : ids.split('/').collect { |id| id.to_i.to_s } rescue ActiveRecord::RecordNotFound
else render_404
@selected_tracker_ids = (default_trackers || selectable_trackers).collect {|t| t.id.to_s }
end
end end
end end
+57 -65
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,94 +16,86 @@
# 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 WatchersController < ApplicationController class WatchersController < ApplicationController
before_filter :require_login, :find_watchables, :only => [:watch, :unwatch] before_filter :find_project
before_filter :require_login, :check_project_privacy, :only => [:watch, :unwatch]
before_filter :authorize, :only => [:new, :destroy]
verify :method => :post,
:only => [ :watch, :unwatch ],
:render => { :nothing => true, :status => :method_not_allowed }
def watch def watch
set_watcher(@watchables, User.current, true) if @watched.respond_to?(:visible?) && !@watched.visible?(User.current)
render_403
else
set_watcher(User.current, true)
end
end end
def unwatch def unwatch
set_watcher(@watchables, User.current, false) set_watcher(User.current, false)
end end
before_filter :find_project, :authorize, :only => [:new, :create, :append, :destroy, :autocomplete_for_user]
accept_api_auth :create, :destroy
def new def new
end @watcher = Watcher.new(params[:watcher])
@watcher.watchable = @watched
def create @watcher.save if request.post?
user_ids = []
if params[:watcher].is_a?(Hash)
user_ids << (params[:watcher][:user_ids] || params[:watcher][:user_id])
else
user_ids << params[:user_id]
end
user_ids.flatten.compact.uniq.each do |user_id|
Watcher.create(:watchable => @watched, :user_id => user_id)
end
respond_to do |format| respond_to do |format|
format.html { redirect_to_referer_or {render :text => 'Watcher added.', :layout => true}} format.html { redirect_to :back }
format.js format.js do
format.api { render_api_ok } render :update do |page|
end page.replace_html 'watchers', :partial => 'watchers/watchers', :locals => {:watched => @watched}
end end
end
def append
if params[:watcher].is_a?(Hash)
user_ids = params[:watcher][:user_ids] || [params[:watcher][:user_id]]
@users = User.active.find_all_by_id(user_ids)
end end
rescue ::ActionController::RedirectBackError
render :text => 'Watcher added.', :layout => true
end end
def destroy def destroy
@watched.set_watcher(User.find(params[:user_id]), false) @watched.set_watcher(User.find(params[:user_id]), false) if request.post?
respond_to do |format| respond_to do |format|
format.html { redirect_to :back } format.html { redirect_to :back }
format.js format.js do
format.api { render_api_ok } render :update do |page|
page.replace_html 'watchers', :partial => 'watchers/watchers', :locals => {:watched => @watched}
end
end
end end
end end
def autocomplete_for_user private
@users = User.active.sorted.like(params[:q]).limit(100).all
if @watched
@users -= @watched.watcher_users
end
render :layout => false
end
private
def find_project def find_project
if params[:object_type] && params[:object_id] klass = Object.const_get(params[:object_type].camelcase)
klass = Object.const_get(params[:object_type].camelcase) return false unless klass.respond_to?('watched_by')
return false unless klass.respond_to?('watched_by') @watched = klass.find(params[:object_id])
@watched = klass.find(params[:object_id]) @project = @watched.project
@project = @watched.project
elsif params[:project_id]
@project = Project.visible.find_by_param(params[:project_id])
end
rescue rescue
render_404 render_404
end end
def find_watchables def set_watcher(user, watching)
klass = Object.const_get(params[:object_type].camelcase) rescue nil @watched.set_watcher(user, watching)
if klass && klass.respond_to?('watched_by') if params[:replace].present?
@watchables = klass.find_all_by_id(Array.wrap(params[:object_id])) if params[:replace].is_a? Array
raise Unauthorized if @watchables.any? {|w| w.respond_to?(:visible?) && !w.visible?} replace_ids = params[:replace]
end else
render_404 unless @watchables.present? replace_ids = [params[:replace]]
end end
else
def set_watcher(watchables, user, watching) replace_ids = 'watcher'
watchables.each do |watchable|
watchable.set_watcher(user, watching)
end end
respond_to do |format| respond_to do |format|
format.html { redirect_to_referer_or {render :text => (watching ? 'Watcher added.' : 'Watcher removed.'), :layout => true}} format.html { redirect_to :back }
format.js { render :partial => 'set_watcher', :locals => {:user => user, :watched => watchables} } format.js do
render(:update) do |page|
replace_ids.each do |replace_id|
page.replace_html replace_id, watcher_link(@watched, user, :replace => replace_ids)
end
end
end
end end
rescue ::ActionController::RedirectBackError
render :text => (watching ? 'Watcher added.' : 'Watcher removed.'), :layout => true
end end
end end
+2 -2
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
+85 -204
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -15,60 +15,25 @@
# 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.
# The WikiController follows the Rails REST controller pattern but with require 'diff'
# a few differences
#
# * index - shows a list of WikiPages grouped by page or date
# * new - not used
# * create - not used
# * show - will also show the form for creating a new wiki page
# * edit - used to edit an existing or new page
# * update - used to save a wiki page update to the database, including new pages
# * destroy - normal
#
# Other member and collection methods are also used
#
# TODO: still being worked on
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, :destroy_version]
accept_api_auth :index, :show, :update, :destroy verify :method => :post, :only => [:destroy, :protect], :redirect_to => { :action => :index }
before_filter :find_attachments, :only => [:preview]
helper :attachments helper :attachments
include AttachmentsHelper include AttachmentsHelper
helper :watchers helper :watchers
include Redmine::Export::PDF
# List of pages, sorted alphabetically and by parent (hierarchy)
def index
load_pages_for_index
respond_to do |format|
format.html {
@pages_by_parent_id = @pages.group_by(&:parent_id)
}
format.api
end
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
# 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 index
if params[:version] && !User.current.allowed_to?(:view_wiki_edits, @project) page_title = params[:page]
deny_access @page = @wiki.find_or_new_page(page_title)
return if @page.new_record?
end if User.current.allowed_to?(:edit_wiki_pages, @project)
@content = @page.content_for_version(params[:version])
if @content.nil?
if User.current.allowed_to?(:edit_wiki_pages, @project) && editable? && !api_request?
edit edit
render :action => 'edit' render :action => 'edit'
else else
@@ -76,120 +41,56 @@ class WikiController < ApplicationController
end end
return return
end end
if User.current.allowed_to?(:export_wiki_pages, @project) if params[:version] && !User.current.allowed_to?(:view_wiki_edits, @project)
if params[:format] == 'pdf' # Redirects user to the current version if he's not allowed to view previous versions
send_data(wiki_page_to_pdf(@page, @project), :type => 'application/pdf', :filename => "#{@page.title}.pdf") redirect_to :version => nil
return return
elsif params[:format] == 'html'
export = render_to_string :action => 'export', :layout => false
send_data(export, :type => 'text/html', :filename => "#{@page.title}.html")
return
elsif params[:format] == 'txt'
send_data(@content.text, :type => 'text/plain', :filename => "#{@page.title}.txt")
return
end
end end
@editable = editable? @content = @page.content_for_version(params[:version])
@sections_editable = @editable && User.current.allowed_to?(:edit_wiki_pages, @page.project) && if params[:format] == 'html'
@content.current_version? && export = render_to_string :action => 'export', :layout => false
Redmine::WikiFormatting.supports_section_edit? send_data(export, :type => 'text/html', :filename => "#{@page.title}.html")
return
respond_to do |format| elsif params[:format] == 'txt'
format.html send_data(@content.text, :type => 'text/plain', :filename => "#{@page.title}.txt")
format.api return
end end
@editable = editable?
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[:page])
return render_403 unless editable? return render_403 unless editable?
if @page.new_record? @page.content = WikiContent.new(:page => @page) if @page.new_record?
if params[:parent].present?
@page.parent = @page.wiki.find_page(params[:parent].to_s)
end
end
@content = @page.content_for_version(params[:version]) @content = @page.content_for_version(params[:version])
@content ||= WikiContent.new(:page => @page)
@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
@content.comments = nil @content.comments = nil
if request.get?
# To prevent StaleObjectError exception when reverting to a previous version # To prevent StaleObjectError exception when reverting to a previous version
@content.version = @page.content.version if @page.content @content.version = @page.content.version
@text = @content.text
if params[:section].present? && Redmine::WikiFormatting.supports_section_edit?
@section = params[:section].to_i
@text, @section_hash = Redmine::WikiFormatting.formatter.new(@text).get_section(@section)
render_404 if @text.blank?
end
end
# Creates a new page or updates an existing one
def update
return render_403 unless editable?
was_new_page = @page.new_record?
@page.safe_attributes = params[:wiki_page]
@content = @page.content || WikiContent.new(:page => @page)
content_params = params[:content]
if content_params.nil? && params[:wiki_page].is_a?(Hash)
content_params = params[:wiki_page].slice(:text, :comments, :version)
end
content_params ||= {}
@content.comments = content_params[:comments]
@text = content_params[:text]
if params[:section].present? && Redmine::WikiFormatting.supports_section_edit?
@section = params[:section].to_i
@section_hash = params[:section_hash]
@content.text = Redmine::WikiFormatting.formatter.new(@content.text).update_section(@section, @text, @section_hash)
else else
@content.version = content_params[:version] if content_params[:version] if !@page.new_record? && @content.text == params[:content][:text]
@content.text = @text # don't save if text wasn't changed
end redirect_to :action => 'index', :id => @project, :page => @page.title
@content.author = User.current return
if @page.save_with_content(@content)
attachments = Attachment.attach_files(@page, params[:attachments])
render_attachment_warning_if_needed(@page)
call_hook(:controller_wiki_edit_after_save, { :params => params, :page => @page})
respond_to do |format|
format.html {
anchor = @section ? "section-#{@section}" : nil
redirect_to project_wiki_page_path(@project, @page.title, :anchor => anchor)
}
format.api {
if was_new_page
render :action => 'show', :status => :created, :location => project_wiki_page_path(@project, @page.title)
else
render_api_ok
end
}
end end
else #@content.text = params[:content][:text]
respond_to do |format| #@content.comments = params[:content][:comments]
format.html { render :action => 'edit' } @content.attributes = params[:content]
format.api { render_validation_errors(@content) } @content.author = User.current
# if page is new @page.save will also save content, but not if page isn't a new record
if (@page.new_record? ? @page.save : @content.save)
call_hook(:controller_wiki_edit_after_save, { :params => params, :page => @page})
redirect_to :action => 'index', :id => @project, :page => @page.title
end end
end end
rescue ActiveRecord::StaleObjectError
rescue ActiveRecord::StaleObjectError, Redmine::WikiFormatting::StaleSectionError
# Optimistic locking exception # Optimistic locking exception
respond_to do |format| flash[:error] = l(:notice_locking_conflict)
format.html {
flash.now[:error] = l(:notice_locking_conflict)
render :action => 'edit'
}
format.api { render_api_head :conflict }
end
rescue ActiveRecord::RecordNotSaved
respond_to do |format|
format.html { render :action => 'edit' }
format.api { render_validation_errors(@content) }
end
end end
# rename a page # rename a page
@@ -200,26 +101,25 @@ class WikiController < ApplicationController
@original_title = @page.pretty_title @original_title = @page.pretty_title
if request.post? && @page.update_attributes(params[:wiki_page]) if request.post? && @page.update_attributes(params[:wiki_page])
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to project_wiki_page_path(@project, @page.title) redirect_to :action => 'index', :id => @project, :page => @page.title
end end
end end
def protect def protect
@page.update_attribute :protected, params[:protected] @page.update_attribute :protected, params[:protected]
redirect_to project_wiki_page_path(@project, @page.title) redirect_to :action => 'index', :id => @project, :page => @page.title
end end
# show page history # show page history
def history def history
@version_count = @page.content.versions.count @version_count = @page.content.versions.count
@version_pages = Paginator.new @version_count, per_page_option, params['page'] @version_pages = Paginator.new self, @version_count, per_page_option, params['p']
# don't load text # don't load text
@versions = @page.content.versions. @versions = @page.content.versions.find :all,
select("id, author_id, comments, updated_on, version"). :select => "id, author_id, comments, updated_on, version",
reorder('version DESC'). :order => 'version DESC',
limit(@version_pages.per_page + 1). :limit => @version_pages.items_per_page + 1,
offset(@version_pages.offset). :offset => @version_pages.current.offset
all
render :layout => false if request.xhr? render :layout => false if request.xhr?
end end
@@ -256,45 +156,45 @@ class WikiController < ApplicationController
end end
else else
@reassignable_to = @wiki.pages - @page.self_and_descendants @reassignable_to = @wiki.pages - @page.self_and_descendants
# display the destroy form if it's a user request return
return unless api_request?
end end
end end
@page.destroy @page.destroy
respond_to do |format| redirect_to :action => 'special', :id => @project, :page => 'Page_index'
format.html { redirect_to project_wiki_index_path(@project) }
format.api { render_api_ok }
end
end end
def destroy_version # display special pages
return render_403 unless editable? def special
page_title = params[:page].downcase
@content = @page.content_for_version(params[:version]) case page_title
@content.destroy # show pages index, sorted by title
redirect_to_referer_or history_project_wiki_page_path(@project, @page.title) when 'page_index', 'date_index'
end # eager load information about last updates, without loading text
@pages = @wiki.pages.find :all, :select => "#{WikiPage.table_name}.*, #{WikiContent.table_name}.updated_on",
# Export wiki to a single pdf or html file :joins => "LEFT JOIN #{WikiContent.table_name} ON #{WikiContent.table_name}.page_id = #{WikiPage.table_name}.id",
def export :order => 'title'
@pages = @wiki.pages.all(:order => 'title', :include => [:content, {:attachments => :author}]) @pages_by_date = @pages.group_by {|p| p.updated_on.to_date}
respond_to do |format| @pages_by_parent_id = @pages.group_by(&:parent_id)
format.html { # export wiki to a single html file
export = render_to_string :action => 'export_multiple', :layout => false when 'export'
send_data(export, :type => 'text/html', :filename => "wiki.html") @pages = @wiki.pages.find :all, :order => 'title'
} export = render_to_string :action => 'export_multiple', :layout => false
format.pdf { send_data(export, :type => 'text/html', :filename => "wiki.html")
send_data(wiki_pages_to_pdf(@pages, @project), :type => 'application/pdf', :filename => "#{@project.identifier}.pdf") return
} else
# requested special page doesn't exist, redirect to default page
redirect_to :action => 'index', :id => @project, :page => nil
return
end end
render :action => "special_#{page_title}"
end end
def preview def preview
page = @wiki.find_page(params[:id]) page = @wiki.find_page(params[:page])
# page is nil when previewing a new page # page is nil when previewing a new page
return render_403 unless page.nil? || editable?(page) return render_403 unless page.nil? || editable?(page)
if page if page
@attachments += page.attachments @attachements = page.attachments
@previewed = page.content @previewed = page.content
end end
@text = params[:content][:text] @text = params[:content][:text]
@@ -303,39 +203,24 @@ class WikiController < ApplicationController
def add_attachment def add_attachment
return render_403 unless editable? return render_403 unless editable?
attachments = Attachment.attach_files(@page, params[:attachments]) attach_files(@page, params[:attachments])
render_attachment_warning_if_needed(@page) redirect_to :action => 'index', :page => @page.title
redirect_to :action => 'show', :id => @page.title, :project_id => @project
end end
private private
def find_wiki def find_wiki
@project = Project.find(params[:project_id]) @project = Project.find(params[:id])
@wiki = @project.wiki @wiki = @project.wiki
render_404 unless @wiki render_404 unless @wiki
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[:page])
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
@@ -349,8 +234,4 @@ private
extend helper unless self.instance_of?(helper) extend helper unless self.instance_of?(helper)
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
@pages = @wiki.pages.with_updated_on.reorder("#{WikiPage.table_name}.title").includes(:wiki => :project).includes(:parent).all
end
end end
+12 -4
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -22,15 +22,23 @@ class WikisController < ApplicationController
# Create or update a project's wiki # Create or update a project's wiki
def edit def edit
@wiki = @project.wiki || Wiki.new(:project => @project) @wiki = @project.wiki || Wiki.new(:project => @project)
@wiki.safe_attributes = params[:wiki] @wiki.attributes = params[:wiki]
@wiki.save if request.post? @wiki.save if request.post?
render(:update) {|page| page.replace_html "tab-content-wiki", :partial => 'projects/settings/wiki'}
end end
# Delete a project's wiki # Delete a project's wiki
def destroy def destroy
if request.post? && params[:confirm] && @project.wiki if request.post? && params[:confirm] && @project.wiki
@project.wiki.destroy @project.wiki.destroy
redirect_to settings_project_path(@project, :tab => 'wiki') redirect_to :controller => 'projects', :action => 'settings', :id => @project, :tab => 'wiki'
end end
end end
private
def find_project
@project = Project.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
end end
+19 -64
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -18,76 +18,41 @@
class WorkflowsController < ApplicationController class WorkflowsController < ApplicationController
layout 'admin' layout 'admin'
before_filter :require_admin, :find_roles, :find_trackers before_filter :require_admin
def index def index
@workflow_counts = WorkflowTransition.count_by_tracker_and_role @workflow_counts = Workflow.count_by_tracker_and_role
end end
def edit def edit
@role = Role.find_by_id(params[:role_id]) if params[:role_id] @role = Role.find_by_id(params[:role_id])
@tracker = Tracker.find_by_id(params[:tracker_id]) if params[:tracker_id] @tracker = Tracker.find_by_id(params[:tracker_id])
if request.post? if request.post?
WorkflowTransition.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')
WorkflowTransition.create(:role_id => @role.id, :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
redirect_to workflows_edit_path(:role_id => @role, :tracker_id => @tracker, :used_statuses_only => params[:used_statuses_only]) flash[:notice] = l(:notice_successful_update)
return redirect_to :action => 'edit', :role_id => @role, :tracker_id => @tracker
end end
end end
@roles = Role.find(:all, :order => 'builtin, position')
@trackers = Tracker.find(:all, :order => 'position')
@used_statuses_only = (params[:used_statuses_only] == '0' ? false : true) @used_statuses_only = (params[:used_statuses_only] == '0' ? false : true)
if @tracker && @used_statuses_only && @tracker.issue_statuses.any? if @tracker && @used_statuses_only && @tracker.issue_statuses.any?
@statuses = @tracker.issue_statuses @statuses = @tracker.issue_statuses
end end
@statuses ||= IssueStatus.sorted.all @statuses ||= IssueStatus.find(:all, :order => 'position')
if @tracker && @role && @statuses.any?
workflows = WorkflowTransition.where(:role_id => @role.id, :tracker_id => @tracker.id).all
@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
def permissions
@role = Role.find_by_id(params[:role_id]) if params[:role_id]
@tracker = Tracker.find_by_id(params[:tracker_id]) if params[:tracker_id]
if request.post? && @role && @tracker
WorkflowPermission.replace_permissions(@tracker, @role, params[:permissions] || {})
redirect_to workflows_permissions_path(:role_id => @role, :tracker_id => @tracker, :used_statuses_only => params[:used_statuses_only])
return
end
@used_statuses_only = (params[:used_statuses_only] == '0' ? false : true)
if @tracker && @used_statuses_only && @tracker.issue_statuses.any?
@statuses = @tracker.issue_statuses
end
@statuses ||= IssueStatus.sorted.all
if @role && @tracker
@fields = (Tracker::CORE_FIELDS_ALL - @tracker.disabled_core_fields).map {|field| [field, l("field_"+field.sub(/_id$/, ''))]}
@custom_fields = @tracker.custom_fields
@permissions = WorkflowPermission.where(:tracker_id => @tracker.id, :role_id => @role.id).all.inject({}) do |h, w|
h[w.old_status_id] ||= {}
h[w.old_status_id][w.field_name] = w.rule
h
end
@statuses.each {|status| @permissions[status.id] ||= {}}
end
end end
def copy def copy
@trackers = Tracker.find(:all, :order => 'position')
@roles = Role.find(:all, :order => 'builtin, position')
if params[:source_tracker_id].blank? || params[:source_tracker_id] == 'any' if params[:source_tracker_id].blank? || params[:source_tracker_id] == 'any'
@source_tracker = nil @source_tracker = nil
@@ -106,23 +71,13 @@ class WorkflowsController < ApplicationController
if request.post? if request.post?
if params[:source_tracker_id].blank? || params[:source_role_id].blank? || (@source_tracker.nil? && @source_role.nil?) if params[:source_tracker_id].blank? || params[:source_role_id].blank? || (@source_tracker.nil? && @source_role.nil?)
flash.now[:error] = l(:error_workflow_copy_source) flash.now[:error] = l(:error_workflow_copy_source)
elsif @target_trackers.blank? || @target_roles.blank? elsif @target_trackers.nil? || @target_roles.nil?
flash.now[:error] = l(:error_workflow_copy_target) flash.now[:error] = l(:error_workflow_copy_target)
else else
WorkflowRule.copy(@source_tracker, @source_role, @target_trackers, @target_roles) Workflow.copy(@source_tracker, @source_role, @target_trackers, @target_roles)
flash[:notice] = l(:notice_successful_update) flash[:notice] = l(:notice_successful_update)
redirect_to workflows_copy_path(:source_tracker_id => @source_tracker, :source_role_id => @source_role) redirect_to :action => 'copy', :source_tracker_id => @source_tracker, :source_role_id => @source_role
end end
end end
end end
private
def find_roles
@roles = Role.sorted.all
end
def find_trackers
@trackers = Tracker.sorted.all
end
end end
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
-33
View File
@@ -1,33 +0,0 @@
# encoding: utf-8
#
# Redmine - project management software
# Copyright (C) 2006-2013 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.
module ActivitiesHelper
def sort_activity_events(events)
events_by_group = events.group_by(&:event_group)
sorted_events = []
events.sort {|x, y| y.event_datetime <=> x.event_datetime}.each do |event|
if group_events = events_by_group.delete(event.event_group)
group_events.sort {|x, y| y.event_datetime <=> x.event_datetime}.each_with_index do |e, i|
sorted_events << [e, i > 0]
end
end
end
sorted_events
end
end
+11 -7
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -20,8 +18,14 @@
module AdminHelper module AdminHelper
def project_status_options_for_select(selected) def project_status_options_for_select(selected)
options_for_select([[l(:label_all), ''], options_for_select([[l(:label_all), ''],
[l(:project_status_active), '1'], [l(:status_active), 1]], selected)
[l(:project_status_closed), '5'], end
[l(:project_status_archived), '9']], selected.to_s)
def css_project_classes(project)
s = 'project'
s << ' root' if project.root?
s << ' child' if project.child?
s << (project.leaf? ? ' leaf' : ' parent')
s
end end
end end
File diff suppressed because it is too large Load Diff
+6 -19
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2007 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,27 +19,16 @@ module AttachmentsHelper
# Displays view/delete links to the attachments of the given object # Displays view/delete links to the attachments of the given object
# Options: # Options:
# :author -- author names are not displayed if set to false # :author -- author names are not displayed if set to false
# :thumbails -- display thumbnails if enabled in settings
def link_to_attachments(container, options = {}) def link_to_attachments(container, options = {})
options.assert_valid_keys(:author, :thumbnails) 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', render :partial => 'attachments/links', :locals => {:attachments => container.attachments, :options => options}
:locals => {:attachments => container.attachments, :options => options, :thumbnails => (options[:thumbnails] && Setting.thumbnails_enabled?)}
end end
end end
def render_api_attachment(attachment, api) def to_utf8(str)
api.attachment do str
api.id attachment.id
api.filename attachment.filename
api.filesize attachment.filesize
api.content_type attachment.content_type
api.description attachment.description
api.content_url url_for(:controller => 'attachments', :action => 'download', :id => attachment, :filename => attachment.filename, :only_path => false)
api.author(:id => attachment.author.id, :name => attachment.author.name) if attachment.author
api.created_on attachment.created_on
end
end end
end end
+2 -7
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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 +16,4 @@
# 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 AuthSourcesHelper module AuthSourcesHelper
def auth_source_partial_name(auth_source)
"form_#{auth_source.class.name.underscore}"
end
end end
+2 -24
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2007 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,24 +16,4 @@
# 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 BoardsHelper module BoardsHelper
def board_breadcrumb(item)
board = item.is_a?(Message) ? item.board : item
links = [link_to(l(:label_board_plural), project_boards_path(item.project))]
boards = board.ancestors.reverse
if item.is_a?(Message)
boards << board
end
links += boards.map {|ancestor| link_to(h(ancestor.name), project_board_path(ancestor.project, ancestor))}
breadcrumb links
end
def boards_options_for_select(boards)
options = []
Board.board_tree(boards) do |board, level|
label = (level > 0 ? '&nbsp;' * 2 * level + '&#187; ' : '').html_safe
label << board.name
options << [label, board.id]
end
options
end
end end
-58
View File
@@ -1,58 +0,0 @@
# encoding: utf-8
#
# Redmine - project management software
# Copyright (C) 2006-2013 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.
module CalendarsHelper
def link_to_previous_month(year, month, options={})
target_year, target_month = if month == 1
[year - 1, 12]
else
[year, month - 1]
end
name = if target_month == 12
"#{month_name(target_month)} #{target_year}"
else
"#{month_name(target_month)}"
end
# \xc2\xab(utf-8) = &#171;
link_to_month(("\xc2\xab " + name), target_year, target_month, options)
end
def link_to_next_month(year, month, options={})
target_year, target_month = if month == 12
[year + 1, 1]
else
[year, month + 1]
end
name = if target_month == 1
"#{month_name(target_month)} #{target_year}"
else
"#{month_name(target_month)}"
end
# \xc2\xbb(utf-8) = &#187;
link_to_month((name + " \xc2\xbb"), target_year, target_month, options)
end
def link_to_month(link_name, year, month, options={})
link_to_content_update(h(link_name), params.merge(:year => year, :month => month))
end
end
-43
View File
@@ -1,43 +0,0 @@
# encoding: utf-8
#
# Redmine - project management software
# Copyright (C) 2006-2013 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.
module ContextMenusHelper
def context_menu_link(name, url, options={})
options[:class] ||= ''
if options.delete(:selected)
options[:class] << ' icon-checked disabled'
options[:disabled] = true
end
if options.delete(:disabled)
options.delete(:method)
options.delete(:data)
options[:onclick] = 'return false;'
options[:class] << ' disabled'
url = '#'
end
link_to h(name), url, options
end
def bulk_update_custom_field_context_menu_link(field, text, value)
context_menu_link h(text),
bulk_update_issues_path(:ids => @issue_ids, :issue => {'custom_field_values' => {field.id => value}}, :back_url => @back),
:method => :post,
:selected => (@issue && @issue.custom_field_value(field) == value)
end
end
+47 -116
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,123 +17,73 @@
module CustomFieldsHelper module CustomFieldsHelper
CUSTOM_FIELDS_TABS = [
{:name => 'IssueCustomField', :partial => 'custom_fields/index',
:label => :label_issue_plural},
{:name => 'TimeEntryCustomField', :partial => 'custom_fields/index',
:label => :label_spent_time},
{:name => 'ProjectCustomField', :partial => 'custom_fields/index',
:label => :label_project_plural},
{:name => 'VersionCustomField', :partial => 'custom_fields/index',
:label => :label_version_plural},
{:name => 'UserCustomField', :partial => 'custom_fields/index',
:label => :label_user_plural},
{:name => 'GroupCustomField', :partial => 'custom_fields/index',
:label => :label_group_plural},
{:name => 'TimeEntryActivityCustomField', :partial => 'custom_fields/index',
:label => TimeEntryActivity::OptionName},
{:name => 'IssuePriorityCustomField', :partial => 'custom_fields/index',
:label => IssuePriority::OptionName},
{:name => 'DocumentCategoryCustomField', :partial => 'custom_fields/index',
:label => DocumentCategory::OptionName}
]
def custom_fields_tabs def custom_fields_tabs
CUSTOM_FIELDS_TABS tabs = [{:name => 'IssueCustomField', :partial => 'custom_fields/index', :label => :label_issue_plural},
{:name => 'TimeEntryCustomField', :partial => 'custom_fields/index', :label => :label_spent_time},
{:name => 'ProjectCustomField', :partial => 'custom_fields/index', :label => :label_project_plural},
{:name => 'VersionCustomField', :partial => 'custom_fields/index', :label => :label_version_plural},
{:name => 'UserCustomField', :partial => 'custom_fields/index', :label => :label_user_plural},
{:name => 'GroupCustomField', :partial => 'custom_fields/index', :label => :label_group_plural},
{:name => 'TimeEntryActivityCustomField', :partial => 'custom_fields/index', :label => TimeEntryActivity::OptionName},
{:name => 'IssuePriorityCustomField', :partial => 'custom_fields/index', :label => IssuePriority::OptionName},
{:name => 'DocumentCategoryCustomField', :partial => 'custom_fields/index', :label => DocumentCategory::OptionName}
]
end end
# Return custom field html tag corresponding to its format # Return custom field html tag corresponding to its format
def custom_field_tag(name, custom_value) def custom_field_tag(name, custom_value)
custom_field = custom_value.custom_field custom_field = custom_value.custom_field
field_name = "#{name}[custom_field_values][#{custom_field.id}]" field_name = "#{name}[custom_field_values][#{custom_field.id}]"
field_name << "[]" if custom_field.multiple?
field_id = "#{name}_custom_field_values_#{custom_field.id}" field_id = "#{name}_custom_field_values_#{custom_field.id}"
tag_options = {:id => field_id, :class => "#{custom_field.field_format}_cf"} case custom_field.field_format
field_format = Redmine::CustomFieldFormat.find_by_name(custom_field.field_format)
case field_format.try(:edit_as)
when "date" when "date"
text_field_tag(field_name, custom_value.value, tag_options.merge(:size => 10)) + text_field_tag(field_name, custom_value.value, :id => field_id, :size => 10) +
calendar_for(field_id) calendar_for(field_id)
when "text" when "text"
text_area_tag(field_name, custom_value.value, tag_options.merge(:rows => 3)) text_area_tag(field_name, custom_value.value, :id => field_id, :rows => 3, :style => 'width:90%')
when "bool" when "bool"
hidden_field_tag(field_name, '0') + check_box_tag(field_name, '1', custom_value.true?, tag_options) hidden_field_tag(field_name, '0') + check_box_tag(field_name, '1', custom_value.true?, :id => field_id)
when "list" when "list"
blank_option = ''.html_safe blank_option = custom_field.is_required? ?
unless custom_field.multiple? (custom_field.default_value.blank? ? "<option value=\"\">--- #{l(:actionview_instancetag_blank_option)} ---</option>" : '') :
if custom_field.is_required? '<option></option>'
unless custom_field.default_value.present? select_tag(field_name, blank_option + options_for_select(custom_field.possible_values, custom_value.value), :id => field_id)
blank_option = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---", :value => '')
end
else
blank_option = content_tag('option')
end
end
s = select_tag(field_name, blank_option + options_for_select(custom_field.possible_values_options(custom_value.customized), custom_value.value),
tag_options.merge(:multiple => custom_field.multiple?))
if custom_field.multiple?
s << hidden_field_tag(field_name, '')
end
s
else else
text_field_tag(field_name, custom_value.value, tag_options) text_field_tag(field_name, custom_value.value, :id => field_id)
end end
end end
# Return custom field label tag # Return custom field label tag
def custom_field_label_tag(name, custom_value, options={}) def custom_field_label_tag(name, custom_value)
required = options[:required] || custom_value.custom_field.is_required? content_tag "label", custom_value.custom_field.name +
(custom_value.custom_field.is_required? ? " <span class=\"required\">*</span>" : ""),
content_tag "label", h(custom_value.custom_field.name) + :for => "#{name}_custom_field_values_#{custom_value.custom_field.id}",
(required ? " <span class=\"required\">*</span>".html_safe : ""), :class => (custom_value.errors.empty? ? nil : "error" )
:for => "#{name}_custom_field_values_#{custom_value.custom_field.id}"
end end
# Return custom field tag with its label tag # Return custom field tag with its label tag
def custom_field_tag_with_label(name, custom_value, options={}) def custom_field_tag_with_label(name, custom_value)
custom_field_label_tag(name, custom_value, options) + 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, value='') def custom_field_tag_for_bulk_edit(custom_field)
field_name = "#{name}[custom_field_values][#{custom_field.id}]" field_name = "custom_field_values[#{custom_field.id}]"
field_name << "[]" if custom_field.multiple? field_id = "custom_field_values_#{custom_field.id}"
field_id = "#{name}_custom_field_values_#{custom_field.id}" case custom_field.field_format
tag_options = {:id => field_id, :class => "#{custom_field.field_format}_cf"}
unset_tag = ''
unless custom_field.is_required?
unset_tag = content_tag('label',
check_box_tag(field_name, '__none__', (value == '__none__'), :id => nil, :data => {:disables => "##{field_id}"}) + l(:button_clear),
:class => 'inline'
)
end
field_format = Redmine::CustomFieldFormat.find_by_name(custom_field.field_format)
case field_format.try(:edit_as)
when "date" when "date"
text_field_tag(field_name, value, tag_options.merge(:size => 10)) + text_field_tag(field_name, '', :id => field_id, :size => 10) +
calendar_for(field_id) + calendar_for(field_id)
unset_tag
when "text" when "text"
text_area_tag(field_name, value, tag_options.merge(:rows => 3)) + text_area_tag(field_name, '', :id => field_id, :rows => 3, :style => 'width:90%')
'<br />'.html_safe +
unset_tag
when "bool" when "bool"
select_tag(field_name, options_for_select([[l(:label_no_change_option), ''], select_tag(field_name, options_for_select([[l(:label_no_change_option), ''],
[l(:general_text_yes), '1'], [l(:general_text_yes), '1'],
[l(:general_text_no), '0']], value), tag_options) [l(:general_text_no), '0']]), :id => field_id)
when "list" when "list"
options = [] select_tag(field_name, options_for_select([[l(:label_no_change_option), '']] + custom_field.possible_values), :id => field_id)
options << [l(:label_no_change_option), ''] unless custom_field.multiple?
options << [l(:label_none), '__none__'] unless custom_field.is_required?
options += custom_field.possible_values_options(projects)
select_tag(field_name, options_for_select(options, value), tag_options.merge(:multiple => custom_field.multiple?))
else else
text_field_tag(field_name, value, tag_options) + text_field_tag(field_name, '', :id => field_id)
unset_tag
end end
end end
@@ -147,36 +95,19 @@ module CustomFieldsHelper
# Return a string used to display a custom value # Return a string used to display a custom value
def format_value(value, field_format) def format_value(value, field_format)
if value.is_a?(Array) return "" unless value && !value.empty?
value.collect {|v| format_value(v, field_format)}.compact.sort.join(', ') case field_format
when "date"
begin; format_date(value.to_date); rescue; value end
when "bool"
l(value == "1" ? :general_text_Yes : :general_text_No)
else else
Redmine::CustomFieldFormat.format_value(value, field_format) value
end end
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) CustomField::FIELD_FORMATS.sort {|a,b| a[1][:order]<=>b[1][:order]}.collect { |k| [ l(k[1][:name]), k[0] ] }
end
# Renders the custom_values in api views
def render_api_custom_values(custom_values, api)
api.array :custom_fields do
custom_values.each do |custom_value|
attrs = {:id => custom_value.custom_field_id, :name => custom_value.custom_field.name}
attrs.merge!(:multiple => true) if custom_value.custom_field.multiple?
api.custom_field attrs do
if custom_value.value.is_a?(Array)
api.array :value do
custom_value.value.each do |value|
api.value value unless value.blank?
end
end
else
api.value custom_value.value
end
end
end
end unless custom_values.empty?
end end
end end
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
-43
View File
@@ -1,43 +0,0 @@
# encoding: utf-8
#
# Redmine - project management software
# Copyright (C) 2006-2013 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.
module GanttHelper
def gantt_zoom_link(gantt, in_or_out)
case in_or_out
when :in
if gantt.zoom < 4
link_to_content_update l(:text_zoom_in),
params.merge(gantt.params.merge(:zoom => (gantt.zoom + 1))),
:class => 'icon icon-zoom-in'
else
content_tag(:span, l(:text_zoom_in), :class => 'icon icon-zoom-in').html_safe
end
when :out
if gantt.zoom > 1
link_to_content_update l(:text_zoom_out),
params.merge(gantt.params.merge(:zoom => (gantt.zoom - 1))),
:class => 'icon icon-zoom-out'
else
content_tag(:span, l(:text_zoom_out), :class => 'icon icon-zoom-out').html_safe
end
end
end
end
+10 -18
View File
@@ -1,7 +1,5 @@
# encoding: utf-8
#
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -18,25 +16,19 @@
# 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 GroupsHelper module GroupsHelper
# Options for the new membership projects combo-box
def options_for_membership_project_select(user, projects)
options = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---")
options << project_tree_options_for_select(projects) do |p|
{:disabled => (user.projects.include?(p))}
end
options
end
def group_settings_tabs def group_settings_tabs
tabs = [{:name => 'general', :partial => 'groups/general', :label => :label_general}, tabs = [{:name => 'general', :partial => 'groups/general', :label => :label_general},
{:name => 'users', :partial => 'groups/users', :label => :label_user_plural}, {:name => 'users', :partial => 'groups/users', :label => :label_user_plural},
{:name => 'memberships', :partial => 'groups/memberships', :label => :label_project_plural} {:name => 'memberships', :partial => 'groups/memberships', :label => :label_project_plural}
] ]
end end
def render_principals_for_new_group_users(group)
scope = User.active.sorted.not_in_group(group).like(params[:q])
principal_count = scope.count
principal_pages = Redmine::Pagination::Paginator.new principal_count, 100, params['page']
principals = scope.offset(principal_pages.offset).limit(principal_pages.per_page).all
s = content_tag('div', principals_check_box_tags('user_ids[]', principals), :id => 'principals')
links = pagination_links_full(principal_pages, principal_count, :per_page_links => false) {|text, parameters, options|
link_to text, autocomplete_for_user_group_path(group, parameters.merge(:q => params[:q], :format => 'js')), :remote => true
}
s + content_tag('p', links, :class => 'pagination')
end
end end
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2007 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
+107 -336
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -20,153 +18,26 @@
module IssuesHelper module IssuesHelper
include ApplicationHelper include ApplicationHelper
def issue_list(issues, &block)
ancestors = []
issues.each do |issue|
while (ancestors.any? && !issue.is_descendant_of?(ancestors.last))
ancestors.pop
end
yield issue, ancestors.size
ancestors << issue unless issue.leaf?
end
end
# Renders a HTML/CSS tooltip
#
# To use, a trigger div is needed. This is a div with the class of "tooltip"
# that contains this method wrapped in a span with the class of "tip"
#
# <div class="tooltip"><%= link_to_issue(issue) %>
# <span class="tip"><%= render_issue_tooltip(issue) %></span>
# </div>
#
def render_issue_tooltip(issue) def render_issue_tooltip(issue)
@cached_label_status ||= l(:field_status)
@cached_label_start_date ||= l(:field_start_date) @cached_label_start_date ||= l(:field_start_date)
@cached_label_due_date ||= l(:field_due_date) @cached_label_due_date ||= l(:field_due_date)
@cached_label_assigned_to ||= l(:field_assigned_to) @cached_label_assigned_to ||= l(:field_assigned_to)
@cached_label_priority ||= l(:field_priority) @cached_label_priority ||= l(:field_priority)
@cached_label_project ||= l(:field_project)
link_to_issue(issue) + "<br /><br />".html_safe + link_to_issue(issue) + "<br /><br />" +
"<strong>#{@cached_label_project}</strong>: #{link_to_project(issue.project)}<br />".html_safe + "<strong>#{@cached_label_start_date}</strong>: #{format_date(issue.start_date)}<br />" +
"<strong>#{@cached_label_status}</strong>: #{h(issue.status.name)}<br />".html_safe + "<strong>#{@cached_label_due_date}</strong>: #{format_date(issue.due_date)}<br />" +
"<strong>#{@cached_label_start_date}</strong>: #{format_date(issue.start_date)}<br />".html_safe + "<strong>#{@cached_label_assigned_to}</strong>: #{issue.assigned_to}<br />" +
"<strong>#{@cached_label_due_date}</strong>: #{format_date(issue.due_date)}<br />".html_safe + "<strong>#{@cached_label_priority}</strong>: #{issue.priority.name}"
"<strong>#{@cached_label_assigned_to}</strong>: #{h(issue.assigned_to)}<br />".html_safe +
"<strong>#{@cached_label_priority}</strong>: #{h(issue.priority.name)}".html_safe
end
def issue_heading(issue)
h("#{issue.tracker} ##{issue.id}")
end
def render_issue_subject_with_tree(issue)
s = ''
ancestors = issue.root? ? [] : issue.ancestors.visible.all
ancestors.each do |ancestor|
s << '<div>' + content_tag('p', link_to_issue(ancestor, :project => (issue.project_id != ancestor.project_id)))
end
s << '<div>'
subject = h(issue.subject)
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.html_safe
end
def render_descendants_tree(issue)
s = '<form><table class="list issues">'
issue_list(issue.descendants.visible.sort_by(&:lft)) do |child, level|
css = "issue issue-#{child.id} hascontextmenu"
css << " idnt idnt-#{level}" if level > 0
s << content_tag('tr',
content_tag('td', check_box_tag("ids[]", child.id, false, :id => nil), :class => 'checkbox') +
content_tag('td', link_to_issue(child, :truncate => 60, :project => (issue.project_id != child.project_id)), :class => 'subject') +
content_tag('td', h(child.status)) +
content_tag('td', link_to_user(child.assigned_to)) +
content_tag('td', progress_bar(child.done_ratio, :width => '80px')),
:class => css)
end
s << '</table></form>'
s.html_safe
end
# Returns an array of error messages for bulk edited issues
def bulk_edit_error_messages(issues)
messages = {}
issues.each do |issue|
issue.errors.full_messages.each do |message|
messages[message] ||= []
messages[message] << issue
end
end
messages.map { |message, issues|
"#{message}: " + issues.map {|i| "##{i.id}"}.join(', ')
}
end
# Returns a link for adding a new subtask to the given issue
def link_to_new_subtask(issue)
attrs = {
:tracker_id => issue.tracker,
:parent_issue_id => issue
}
link_to(l(:button_add), new_project_issue_path(issue.project, :issue => attrs))
end
class IssueFieldsRows
include ActionView::Helpers::TagHelper
def initialize
@left = []
@right = []
end
def left(*args)
args.any? ? @left << cells(*args) : @left
end
def right(*args)
args.any? ? @right << cells(*args) : @right
end
def size
@left.size > @right.size ? @left.size : @right.size
end
def to_html
html = ''.html_safe
blank = content_tag('th', '') + content_tag('td', '')
size.times do |i|
left = @left[i] || blank
right = @right[i] || blank
html << content_tag('tr', left + right)
end
html
end
def cells(label, text, options={})
content_tag('th', "#{label}:", options) + content_tag('td', text, options)
end
end
def issue_fields_rows
r = IssueFieldsRows.new
yield r
r.to_html
end end
def render_custom_fields_rows(issue) def render_custom_fields_rows(issue)
values = issue.visible_custom_field_values return if issue.custom_field_values.empty?
return if values.empty?
ordered_values = [] ordered_values = []
half = (values.size / 2.0).ceil half = (issue.custom_field_values.size / 2.0).ceil
half.times do |i| half.times do |i|
ordered_values << values[i] ordered_values << issue.custom_field_values[i]
ordered_values << values[i + half] ordered_values << issue.custom_field_values[i + half]
end end
s = "<tr>\n" s = "<tr>\n"
n = 0 n = 0
@@ -176,173 +47,67 @@ module IssuesHelper
n += 1 n += 1
end end
s << "</tr>\n" s << "</tr>\n"
s.html_safe s
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 end
def sidebar_queries def sidebar_queries
unless @sidebar_queries unless @sidebar_queries
@sidebar_queries = IssueQuery.visible. # User can see public queries and his own queries
order("#{Query.table_name}.name ASC"). 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
where(@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])
all @sidebar_queries = Query.find(:all,
:select => 'id, name',
:order => "name ASC",
:conditions => visible.conditions)
end end
@sidebar_queries @sidebar_queries
end end
def query_links(title, queries) def show_detail(detail, no_html=false)
return '' if queries.empty?
# links to #index on issues/show
url_params = controller_name == 'issues' ? {:controller => 'issues', :action => 'index', :project_id => @project} : params
content_tag('h3', title) + "\n" +
content_tag('ul',
queries.collect {|query|
css = 'query'
css << ' selected' if query == @query
content_tag('li', link_to(query.name, url_params.merge(:query_id => query), :class => css))
}.join("\n").html_safe,
:class => 'queries'
) + "\n"
end
def render_sidebar_queries
out = ''.html_safe
out << query_links(l(:label_my_queries), sidebar_queries.select(&:is_private?))
out << query_links(l(:label_query_plural), sidebar_queries.reject(&:is_private?))
out
end
def email_issue_attributes(issue, user)
items = []
%w(author status priority assigned_to category fixed_version).each do |attribute|
unless issue.disabled_core_fields.include?(attribute+"_id")
items << "#{l("field_#{attribute}")}: #{issue.send attribute}"
end
end
issue.visible_custom_field_values(user).each do |value|
items << "#{value.custom_field.name}: #{show_value(value)}"
end
items
end
def render_email_issue_attributes(issue, user, html=false)
items = email_issue_attributes(issue, user)
if html
content_tag('ul', items.map{|s| content_tag('li', s)}.join("\n").html_safe)
else
items.map{|s| "* #{s}"}.join("\n")
end
end
# Returns the textual representation of a journal details
# as an array of strings
def details_to_strings(details, no_html=false, options={})
options[:only_path] = (options[:only_path] == false ? false : true)
strings = []
values_by_field = {}
details.each do |detail|
if detail.property == 'cf'
field = detail.custom_field
if field && field.multiple?
values_by_field[field] ||= {:added => [], :deleted => []}
if detail.old_value
values_by_field[field][:deleted] << detail.old_value
end
if detail.value
values_by_field[field][:added] << detail.value
end
next
end
end
strings << show_detail(detail, no_html, options)
end
values_by_field.each do |field, changes|
detail = JournalDetail.new(:property => 'cf', :prop_key => field.id.to_s)
detail.instance_variable_set "@custom_field", field
if changes[:added].any?
detail.value = changes[:added]
strings << show_detail(detail, no_html, options)
elsif changes[:deleted].any?
detail.old_value = changes[:deleted]
strings << show_detail(detail, no_html, options)
end
end
strings
end
# Returns the textual representation of a single journal detail
def show_detail(detail, no_html=false, options={})
multiple = false
case detail.property case detail.property
when 'attr' when 'attr'
field = detail.prop_key.to_s.gsub(/\_id$/, "") label = l(("field_" + detail.prop_key.to_s.gsub(/\_id$/, "")).to_sym)
label = l(("field_" + field).to_sym)
case detail.prop_key case detail.prop_key
when 'due_date', 'start_date' when 'due_date', 'start_date'
value = format_date(detail.value.to_date) if detail.value value = format_date(detail.value.to_date) if detail.value
old_value = format_date(detail.old_value.to_date) if detail.old_value old_value = format_date(detail.old_value.to_date) if detail.old_value
when 'project_id'
when 'project_id', 'status_id', 'tracker_id', 'assigned_to_id', p = Project.find_by_id(detail.value) and value = p.name if detail.value
'priority_id', 'category_id', 'fixed_version_id' p = Project.find_by_id(detail.old_value) and old_value = p.name if detail.old_value
value = find_name_by_reflection(field, detail.value) when 'status_id'
old_value = find_name_by_reflection(field, detail.old_value) s = IssueStatus.find_by_id(detail.value) and value = s.name if detail.value
s = IssueStatus.find_by_id(detail.old_value) and old_value = s.name if detail.old_value
when 'tracker_id'
t = Tracker.find_by_id(detail.value) and value = t.name if detail.value
t = Tracker.find_by_id(detail.old_value) and old_value = t.name if detail.old_value
when 'assigned_to_id'
u = User.find_by_id(detail.value) and value = u.name if detail.value
u = User.find_by_id(detail.old_value) and old_value = u.name if detail.old_value
when 'priority_id'
e = IssuePriority.find_by_id(detail.value) and value = e.name if detail.value
e = IssuePriority.find_by_id(detail.old_value) and old_value = e.name if detail.old_value
when 'category_id'
c = IssueCategory.find_by_id(detail.value) and value = c.name if detail.value
c = IssueCategory.find_by_id(detail.old_value) and old_value = c.name if detail.old_value
when 'fixed_version_id'
v = Version.find_by_id(detail.value) and value = v.name if detail.value
v = Version.find_by_id(detail.old_value) and old_value = v.name if detail.old_value
when 'estimated_hours' when 'estimated_hours'
value = "%0.02f" % detail.value.to_f unless detail.value.blank? value = "%0.02f" % detail.value.to_f unless detail.value.blank?
old_value = "%0.02f" % detail.old_value.to_f unless detail.old_value.blank? old_value = "%0.02f" % detail.old_value.to_f unless detail.old_value.blank?
when 'parent_id'
label = l(:field_parent_issue)
value = "##{detail.value}" unless detail.value.blank?
old_value = "##{detail.old_value}" unless detail.old_value.blank?
when '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 = detail.custom_field custom_field = CustomField.find_by_id(detail.prop_key)
if custom_field if custom_field
multiple = custom_field.multiple?
label = custom_field.name label = custom_field.name
value = format_value(detail.value, custom_field.field_format) if detail.value value = format_value(detail.value, custom_field.field_format) if detail.value
old_value = format_value(detail.old_value, custom_field.field_format) if detail.old_value old_value = format_value(detail.old_value, custom_field.field_format) if detail.old_value
end end
when 'attachment' when 'attachment'
label = l(:label_attachment) label = l(:label_attachment)
when 'relation'
if detail.value && !detail.old_value
rel_issue = Issue.visible.find_by_id(detail.value)
value = rel_issue.nil? ? "#{l(:label_issue)} ##{detail.value}" :
(no_html ? rel_issue : link_to_issue(rel_issue))
elsif detail.old_value && !detail.value
rel_issue = Issue.visible.find_by_id(detail.old_value)
old_value = rel_issue.nil? ? "#{l(:label_issue)} ##{detail.old_value}" :
(no_html ? rel_issue : link_to_issue(rel_issue))
end
label = l(detail.prop_key.to_sym)
end end
call_hook(:helper_issues_show_detail_after_setting, call_hook(:helper_issues_show_detail_after_setting, {:detail => detail, :label => label, :value => value, :old_value => old_value })
{:detail => detail, :label => label, :value => value, :old_value => old_value })
label ||= detail.prop_key label ||= detail.prop_key
value ||= detail.value value ||= detail.value
@@ -351,78 +116,84 @@ module IssuesHelper
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
if detail.old_value && detail.value.blank? && detail.property != 'relation' old_value = content_tag("strike", old_value) if detail.old_value and (!detail.value or detail.value.empty?)
old_value = content_tag("del", old_value) if detail.property == 'attachment' && !value.blank? && a = Attachment.find_by_id(detail.prop_key)
end
if detail.property == 'attachment' && !value.blank? && atta = Attachment.find_by_id(detail.prop_key)
# Link to the attachment if it has not been removed # Link to the attachment if it has not been removed
value = link_to_attachment(atta, :download => true, :only_path => options[:only_path]) value = link_to_attachment(a)
if options[:only_path] != false && atta.is_text?
value += link_to(
image_tag('magnifier.png'),
:controller => 'attachments', :action => 'show',
:id => atta, :filename => atta.filename
)
end
else else
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, :only_path => options[:only_path]},
:title => l(:label_view_diff)
s << " (#{ diff_link })"
end
s.html_safe
elsif detail.value.present?
case detail.property case detail.property
when 'attr', 'cf' when 'attr', 'cf'
if detail.old_value.present? if !detail.old_value.blank?
l(:text_journal_changed, :label => label, :old => old_value, :new => value).html_safe l(:text_journal_changed, :label => label, :old => old_value, :new => value)
elsif multiple
l(:text_journal_added, :label => label, :value => value).html_safe
else else
l(:text_journal_set_to, :label => label, :value => value).html_safe l(:text_journal_set_to, :label => label, :value => value)
end end
when 'attachment', 'relation' when 'attachment'
l(:text_journal_added, :label => label, :value => value).html_safe l(:text_journal_added, :label => label, :value => value)
end end
else else
l(:text_journal_deleted, :label => label, :old => old_value).html_safe l(:text_journal_deleted, :label => label, :old => old_value)
end end
end end
# Find the name of an associated record stored in the field attribute def issues_to_csv(issues, project = nil)
def find_name_by_reflection(field, id) ic = Iconv.new(l(:general_csv_encoding), 'UTF-8')
unless id.present? decimal_separator = l(:general_csv_decimal_separator)
return nil export = FCSV.generate(:col_sep => l(:general_csv_separator)) do |csv|
end # csv header fields
association = Issue.reflect_on_association(field.to_sym) headers = [ "#",
if association l(:field_status),
record = association.class_name.constantize.find_by_id(id) l(:field_project),
if record l(:field_tracker),
record.name.force_encoding('UTF-8') if record.name.respond_to?(:force_encoding) l(:field_priority),
return record.name l(:field_subject),
end l(:field_assigned_to),
end l(:field_category),
end l(:field_fixed_version),
l(:field_author),
# Renders issue children recursively l(:field_start_date),
def render_api_issue_children(issue, api) l(:field_due_date),
return if issue.leaf? l(:field_done_ratio),
api.array :children do l(:field_estimated_hours),
issue.children.each do |child| l(:field_created_on),
api.issue(:id => child.id) do l(:field_updated_on)
api.tracker(:id => child.tracker_id, :name => child.tracker.name) unless child.tracker.nil? ]
api.subject child.subject # Export project custom fields if project is given
render_api_issue_children(child, api) # otherwise export custom fields marked as "For all projects"
end custom_fields = project.nil? ? IssueCustomField.for_all : project.all_issue_custom_fields
custom_fields.each {|f| headers << f.name}
# Description in the last column
headers << l(:field_description)
csv << headers.collect {|c| begin; ic.iconv(c.to_s); rescue; c.to_s; end }
# csv lines
issues.each do |issue|
fields = [issue.id,
issue.status.name,
issue.project.name,
issue.tracker.name,
issue.priority.name,
issue.subject,
issue.assigned_to,
issue.category,
issue.fixed_version,
issue.author.name,
format_date(issue.start_date),
format_date(issue.due_date),
issue.done_ratio,
issue.estimated_hours.to_s.gsub('.', decimal_separator),
format_time(issue.created_on),
format_time(issue.updated_on)
]
custom_fields.each {|f| fields << show_value(issue.custom_value_for(f)) }
fields << issue.description
csv << fields.collect {|c| begin; ic.iconv(c.to_s); rescue; c.to_s; end }
end end
end end
export
end end
end end
+11 -15
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2008 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,29 +16,27 @@
# 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 JournalsHelper module JournalsHelper
def render_notes(issue, journal, options={}) def render_notes(journal, options={})
content = '' content = ''
editable = User.current.logged? && (User.current.allowed_to?(:edit_issue_notes, issue.project) || (journal.user == User.current && User.current.allowed_to?(:edit_own_issue_notes, issue.project))) editable = journal.editable_by?(User.current)
links = [] links = []
if !journal.notes.blank? if !journal.notes.blank?
links << link_to(image_tag('comment.png'), links << link_to_remote(image_tag('comment.png'),
{:controller => 'journals', :action => 'new', :id => issue, :journal_id => journal}, { :url => {:controller => 'issues', :action => 'reply', :id => journal.journalized, :journal_id => journal} },
:remote => true, :title => l(:button_quote)) if options[:reply_links]
:method => 'post',
:title => l(:button_quote)) if options[:reply_links]
links << link_to_in_place_notes_editor(image_tag('edit.png'), "journal-#{journal.id}-notes", links << link_to_in_place_notes_editor(image_tag('edit.png'), "journal-#{journal.id}-notes",
{ :controller => 'journals', :action => 'edit', :id => journal, :format => 'js' }, { :controller => 'journals', :action => 'edit', :id => journal },
:title => l(:button_edit)) if editable :title => l(:button_edit)) if editable
end end
content << content_tag('div', links.join(' ').html_safe, :class => 'contextual') unless links.empty? content << content_tag('div', links.join(' '), :class => 'contextual') unless links.empty?
content << textilizable(journal, :notes) content << textilizable(journal, :notes)
css_classes = "wiki" css_classes = "wiki"
css_classes << " editable" if editable css_classes << " editable" if editable
content_tag('div', content.html_safe, :id => "journal-#{journal.id}-notes", :class => css_classes) content_tag('div', content, :id => "journal-#{journal.id}-notes", :class => css_classes)
end end
def link_to_in_place_notes_editor(text, field_id, url, options={}) def link_to_in_place_notes_editor(text, field_id, url, options={})
onclick = "$.ajax({url: '#{url_for(url)}', type: 'get'}); return false;" onclick = "new Ajax.Request('#{url_for(url)}', {asynchronous:true, evalScripts:true, method:'get'}); return false;"
link_to text, '#', options.merge(:onclick => onclick) link_to text, '#', options.merge(:onclick => onclick)
end end
end end
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2008 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
+2 -18
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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 +16,4 @@
# 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 MembersHelper module MembersHelper
def render_principals_for_new_members(project)
scope = Principal.active.sorted.not_member_of(project).like(params[:q])
principal_count = scope.count
principal_pages = Redmine::Pagination::Paginator.new principal_count, 100, params['page']
principals = scope.offset(principal_pages.offset).limit(principal_pages.per_page).all
s = content_tag('div', principals_check_box_tags('membership[user_ids][]', principals), :id => 'principals')
links = pagination_links_full(principal_pages, principal_count, :per_page_links => false) {|text, parameters, options|
link_to text, autocomplete_project_memberships_path(project, parameters.merge(:q => params[:q], :format => 'js')), :remote => true
}
s + content_tag('p', links, :class => 'pagination')
end
end end
+11 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2007 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,4 +16,13 @@
# 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,
:anchor => (message.parent_id ? "message-#{message.id}" : nil)
end
end end
+2 -54
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,54 +16,4 @@
# 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 MyHelper module MyHelper
def calendar_items(startdt, enddt)
Issue.visible.
where(:project_id => User.current.projects.map(&:id)).
where("(start_date>=? and start_date<=?) or (due_date>=? and due_date<=?)", startdt, enddt, startdt, enddt).
includes(:project, :tracker, :priority, :assigned_to).
all
end
def documents_items
Document.visible.order("#{Document.table_name}.created_on DESC").limit(10).all
end
def issuesassignedtome_items
Issue.visible.open.
where(:assigned_to_id => ([User.current.id] + User.current.group_ids)).
limit(10).
includes(:status, :project, :tracker, :priority).
order("#{IssuePriority.table_name}.position DESC, #{Issue.table_name}.updated_on DESC").
all
end
def issuesreportedbyme_items
Issue.visible.
where(:author_id => User.current.id).
limit(10).
includes(:status, :project, :tracker).
order("#{Issue.table_name}.updated_on DESC").
all
end
def issueswatched_items
Issue.visible.on_active_project.watched_by(User.current.id).recently_updated.limit(10).all
end
def news_items
News.visible.
where(:project_id => User.current.projects.map(&:id)).
limit(10).
includes(:project, :author).
order("#{News.table_name}.created_on DESC").
all
end
def timelog_items
TimeEntry.
where("#{TimeEntry.table_name}.user_id = ? AND #{TimeEntry.table_name}.spent_on BETWEEN ? AND ?", User.current.id, Date.today - 6, Date.today).
includes(:activity, :project, {:issue => [:tracker, :status]}).
order("#{TimeEntry.table_name}.spent_on DESC, #{Project.table_name}.name ASC, #{Tracker.table_name}.position ASC, #{Issue.table_name}.id ASC").
all
end
end end
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
+36 -16
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,7 +28,7 @@ module ProjectsHelper
{:name => 'versions', :action => :manage_versions, :partial => 'projects/settings/versions', :label => :label_version_plural}, {:name => 'versions', :action => :manage_versions, :partial => 'projects/settings/versions', :label => :label_version_plural},
{:name => 'categories', :action => :manage_categories, :partial => 'projects/settings/issue_categories', :label => :label_issue_category_plural}, {:name => 'categories', :action => :manage_categories, :partial => 'projects/settings/issue_categories', :label => :label_issue_category_plural},
{:name => 'wiki', :action => :manage_wiki, :partial => 'projects/settings/wiki', :label => :label_wiki}, {:name => 'wiki', :action => :manage_wiki, :partial => 'projects/settings/wiki', :label => :label_wiki},
{:name => 'repositories', :action => :manage_repository, :partial => 'projects/settings/repositories', :label => :label_repository_plural}, {:name => 'repository', :action => :manage_repository, :partial => 'projects/settings/repository', :label => :label_repository},
{: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}
] ]
@@ -46,20 +44,39 @@ module ProjectsHelper
end end
options = '' options = ''
options << "<option value=''>&nbsp;</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.html_safe, :name => 'project[parent_id]', :id => 'project_parent_id') content_tag('select', options, :name => 'project[parent_id]')
end end
# Renders the projects index # Renders a tree of projects as a nested set of unordered lists
# The given collection may be a subset of the whole project tree
# (eg. some intermediate nodes are private and can not be seen)
def render_project_hierarchy(projects) def render_project_hierarchy(projects)
render_project_nested_lists(projects) do |project| s = ''
s = link_to_project(project, {}, :class => "#{project.css_classes} #{User.current.member_of?(project) ? 'my-project' : nil}") if projects.any?
if project.description.present? ancestors = []
s << content_tag('div', textilizable(project.short_description, :project => project), :class => 'wiki description') projects.each do |project|
if (ancestors.empty? || project.is_descendant_of?(ancestors.last))
s << "<ul class='projects #{ ancestors.empty? ? 'root' : nil}'>\n"
else
ancestors.pop
s << "</li>"
while (ancestors.any? && !project.is_descendant_of?(ancestors.last))
ancestors.pop
s << "</ul></li>\n"
end
end
classes = (ancestors.empty? ? 'root' : 'child')
s << "<li class='#{classes}'><div class='#{classes}'>" +
link_to(h(project), {:controller => 'projects', :action => 'show', :id => project}, :class => "project #{User.current.member_of?(project) ? 'my-project' : nil}")
s << "<div class='wiki description'>#{textilizable(project.short_description, :project => project)}</div>" unless project.description.blank?
s << "</div>\n"
ancestors << project
end end
s s << ("</li></ul>\n" * ancestors.size)
end end
s
end end
# Returns a set of options for a select field, grouped by project. # Returns a set of options for a select field, grouped by project.
@@ -68,12 +85,15 @@ module ProjectsHelper
versions.each do |version| versions.each do |version|
grouped[version.project.name] << [version.name, version.id] grouped[version.project.name] << [version.name, version.id]
end end
# Add in the selected
if selected && !versions.include?(selected)
grouped[selected.project.name] << [selected.name, selected.id]
end
selected = selected.is_a?(Version) ? selected.id : selected
if grouped.keys.size > 1 if grouped.keys.size > 1
grouped_options_for_select(grouped, selected) grouped_options_for_select(grouped, selected && selected.id)
else else
options_for_select((grouped.values.first || []), selected) options_for_select((grouped.values.first || []), selected && selected.id)
end end
end end
+8 -168
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2007 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,84 +16,24 @@
# 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 QueriesHelper module QueriesHelper
def filters_options_for_select(query)
options_for_select(filters_options(query))
end
def filters_options(query) def operators_for_select(filter_type)
options = [[]] Query.operators_by_filter_type[filter_type].collect {|o| [l(Query.operators[o]), o]}
options += query.available_filters.map do |field, field_options|
[field_options[:name], field]
end
end
def query_filters_hidden_tags(query)
tags = ''.html_safe
query.filters.each do |field, options|
tags << hidden_field_tag("f[]", field, :id => nil)
tags << hidden_field_tag("op[#{field}]", options[:operator], :id => nil)
options[:values].each do |value|
tags << hidden_field_tag("v[#{field}][]", value, :id => nil)
end
end
tags
end
def query_columns_hidden_tags(query)
tags = ''.html_safe
query.columns.each do |column|
tags << hidden_field_tag("c[]", column.name, :id => nil)
end
tags
end
def query_hidden_tags(query)
query_filters_hidden_tags(query) + query_columns_hidden_tags(query)
end
def available_block_columns_tags(query)
tags = ''.html_safe
query.available_block_columns.each do |column|
tags << content_tag('label', check_box_tag('c[]', column.name.to_s, query.has_column?(column)) + " #{column.caption}", :class => 'inline')
end
tags
end
def query_available_inline_columns_options(query)
(query.available_inline_columns - query.columns).reject(&:frozen?).collect {|column| [column.caption, column.name]}
end
def query_selected_inline_columns_options(query)
(query.inline_columns & query.available_inline_columns).reject(&:frozen?).collect {|column| [column.caption, column.name]}
end
def render_query_columns_selection(query, options={})
tag_name = (options[:name] || 'c') + '[]'
render :partial => 'queries/columns', :locals => {:query => query, :tag_name => tag_name}
end end
def column_header(column) def column_header(column)
column.sortable ? sort_header_tag(column.name.to_s, :caption => column.caption, column.sortable ? sort_header_tag(column.name.to_s, :caption => column.caption,
:default_order => column.default_order) : :default_order => column.default_order) :
content_tag('th', h(column.caption)) content_tag('th', column.caption)
end end
def column_content(column, issue) def column_content(column, issue)
value = column.value(issue) value = column.value(issue)
if value.is_a?(Array)
value.collect {|v| column_value(column, issue, v)}.compact.join(', ').html_safe
else
column_value(column, issue, value)
end
end
def column_value(column, issue, value)
case value.class.name case value.class.name
when 'String' when 'String'
if column.name == :subject if column.name == :subject
link_to(h(value), :controller => 'issues', :action => 'show', :id => issue) link_to(h(value), :controller => 'issues', :action => 'show', :id => issue)
elsif column.name == :description
issue.description? ? content_tag('div', textilizable(issue, :description), :class => "wiki") : ''
else else
h(value) h(value)
end end
@@ -103,122 +41,24 @@ module QueriesHelper
format_time(value) format_time(value)
when 'Date' when 'Date'
format_date(value) format_date(value)
when 'Fixnum' when 'Fixnum', 'Float'
if column.name == :id if column.name == :done_ratio
link_to value, issue_path(issue)
elsif column.name == :done_ratio
progress_bar(value, :width => '80px') progress_bar(value, :width => '80px')
else else
value.to_s value.to_s
end end
when 'Float'
sprintf "%.2f", value
when 'User' when 'User'
link_to_user value link_to_user value
when 'Project' when 'Project'
link_to_project value link_to(h(value), :controller => 'projects', :action => 'show', :id => value)
when 'Version' when 'Version'
link_to(h(value), :controller => 'versions', :action => 'show', :id => value) link_to(h(value), :controller => 'versions', :action => 'show', :id => value)
when 'TrueClass' when 'TrueClass'
l(:general_text_Yes) l(:general_text_Yes)
when 'FalseClass' when 'FalseClass'
l(:general_text_No) l(:general_text_No)
when 'Issue'
value.visible? ? link_to_issue(value) : "##{value.id}"
when 'IssueRelation'
other = value.other_issue(issue)
content_tag('span',
(l(value.label_for(issue)) + " " + link_to_issue(other, :subject => false, :tracker => false)).html_safe,
:class => value.css_classes_for(issue))
else else
h(value) h(value)
end end
end end
def csv_content(column, issue)
value = column.value(issue)
if value.is_a?(Array)
value.collect {|v| csv_value(column, issue, v)}.compact.join(', ')
else
csv_value(column, issue, value)
end
end
def csv_value(column, issue, value)
case value.class.name
when 'Time'
format_time(value)
when 'Date'
format_date(value)
when 'Float'
sprintf("%.2f", value).gsub('.', l(:general_csv_decimal_separator))
when 'IssueRelation'
other = value.other_issue(issue)
l(value.label_for(issue)) + " ##{other.id}"
else
value.to_s
end
end
def query_to_csv(items, query, options={})
encoding = l(:general_csv_encoding)
columns = (options[:columns] == 'all' ? query.available_inline_columns : query.inline_columns)
query.available_block_columns.each do |column|
if options[column.name].present?
columns << column
end
end
export = FCSV.generate(:col_sep => l(:general_csv_separator)) do |csv|
# csv header fields
csv << columns.collect {|c| Redmine::CodesetUtil.from_utf8(c.caption.to_s, encoding) }
# csv lines
items.each do |item|
csv << columns.collect {|c| Redmine::CodesetUtil.from_utf8(csv_content(c, item), encoding) }
end
end
export
end
# Retrieve query from session or build a new query
def retrieve_query
if !params[:query_id].blank?
cond = "project_id IS NULL"
cond << " OR project_id = #{@project.id}" if @project
@query = IssueQuery.where(cond).find(params[:query_id])
raise ::Unauthorized unless @query.visible?
@query.project = @project
session[:query] = {:id => @query.id, :project_id => @query.project_id}
sort_clear
elsif api_request? || params[:set_filter] || session[:query].nil? || session[:query][:project_id] != (@project ? @project.id : nil)
# Give it a name, required to be valid
@query = IssueQuery.new(:name => "_")
@query.project = @project
@query.build_from_params(params)
session[:query] = {:project_id => @query.project_id, :filters => @query.filters, :group_by => @query.group_by, :column_names => @query.column_names}
else
# retrieve from session
@query = nil
@query = IssueQuery.find_by_id(session[:query][:id]) if session[:query][:id]
@query ||= IssueQuery.new(:name => "_", :filters => session[:query][:filters], :group_by => session[:query][:group_by], :column_names => session[:query][:column_names])
@query.project = @project
end
end
def retrieve_query_from_session
if session[:query]
if session[:query][:id]
@query = IssueQuery.find_by_id(session[:query][:id])
return unless @query
else
@query = IssueQuery.new(:name => "_", :filters => session[:query][:filters], :group_by => session[:query][:group_by], :column_names => session[:query][:column_names])
end
if session[:query].has_key?(:project_id)
@query.project_id = session[:query][:project_id]
else
@query.project = @project
end
@query
end
end
end end
+4 -11
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,7 +22,7 @@ module ReportsHelper
data.each { |row| data.each { |row|
match = 1 match = 1
criteria.each { |k, v| criteria.each { |k, v|
match = 0 unless (row[k].to_s == v.to_s) || (k == 'closed' && (v == 0 ? ['f', false] : ['t', true]).include?(row[k])) match = 0 unless (row[k].to_s == v.to_s) || (k == 'closed' && row[k] == (v == 0 ? "f" : "t"))
} unless criteria.nil? } unless criteria.nil?
a = a + row["total"].to_i if match == 1 a = a + row["total"].to_i if match == 1
} unless data.nil? } unless data.nil?
@@ -33,11 +31,6 @@ module ReportsHelper
def aggregate_link(data, criteria, *args) def aggregate_link(data, criteria, *args)
a = aggregate data, criteria a = aggregate data, criteria
a > 0 ? link_to(h(a), *args) : '-' a > 0 ? link_to(a, *args) : '-'
end
def aggregate_path(project, field, row, options={})
parameters = {:set_filter => 1, :subproject_id => '!*', field => row.id}.merge(options)
project_issues_path(row.is_a?(Project) ? row : project, parameters)
end end
end end
+56 -165
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,13 +15,11 @@
# 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'
module RepositoriesHelper module RepositoriesHelper
def format_revision(revision) def format_revision(txt)
if revision.respond_to? :format_identifier txt.to_s[0,8]
revision.format_identifier
else
revision.to_s
end
end end
def truncate_at_line_break(text, length = 255) def truncate_at_line_break(text, length = 255)
@@ -36,28 +32,27 @@ module RepositoriesHelper
unless properties.nil? || properties.empty? unless properties.nil? || properties.empty?
content = '' content = ''
properties.keys.sort.each do |property| properties.keys.sort.each do |property|
content << content_tag('li', "<b>#{h property}</b>: <span>#{h properties[property]}</span>".html_safe) content << content_tag('li', "<b>#{h property}</b>: <span>#{h properties[property]}</span>")
end end
content_tag('ul', content.html_safe, :class => 'properties') content_tag('ul', content, :class => 'properties')
end end
end end
def render_changeset_changes def render_changeset_changes
changes = @changeset.filechanges.limit(1000).reorder('path').all.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.filechanges.detect {|c| c.action == 'D' && c.path == change.from_path} ? 'R' : 'C'
end end
change change
when 'D' when 'D'
@changeset.filechanges.detect {|c| c.from_path == change.path} ? nil : change @changeset.changes.detect {|c| c.from_path == change.path} ? nil : change
else else
change change
end end
end.compact end.compact
tree = { } tree = { }
changes.each do |change| changes.each do |change|
@@ -73,11 +68,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|
@@ -86,59 +83,64 @@ module RepositoriesHelper
if s = tree[file][:s] if s = tree[file][:s]
style << ' folder' style << ' folder'
path_param = to_path_param(@repository.relative_path(file)) path_param = to_path_param(@repository.relative_path(file))
text = link_to(h(text), :controller => 'repositories', text = link_to(text, :controller => 'repositories',
:action => 'show', :action => 'show',
:id => @project, :id => @project,
:repository_id => @repository.identifier_param,
:path => path_param, :path => path_param,
:rev => @changeset.identifier) :rev => @changeset.revision)
output << "<li class='#{style}'>#{text}" output << "<li class='#{style}'>#{text}</li>"
output << render_changes_tree(s) output << render_changes_tree(s)
output << "</li>"
elsif c = tree[file][:c] elsif c = tree[file][:c]
style << " change-#{c.action}" style << " change-#{c.action}"
path_param = to_path_param(@repository.relative_path(c.path)) path_param = to_path_param(@repository.relative_path(c.path))
text = link_to(h(text), :controller => 'repositories', text = link_to(text, :controller => 'repositories',
:action => 'entry', :action => 'entry',
:id => @project, :id => @project,
:repository_id => @repository.identifier_param,
:path => path_param, :path => path_param,
:rev => @changeset.identifier) unless c.action == 'D' :rev => @changeset.revision) unless c.action == 'D'
text << " - #{h(c.revision)}" unless c.revision.blank? text << " - #{c.revision}" unless c.revision.blank?
text << ' ('.html_safe + link_to(l(:label_diff), :controller => 'repositories', text << ' (' + link_to('diff', :controller => 'repositories',
:action => 'diff', :action => 'diff',
:id => @project, :id => @project,
:repository_id => @repository.identifier_param,
:path => path_param, :path => path_param,
:rev => @changeset.identifier) + ') '.html_safe if c.action == 'M' :rev => @changeset.revision) + ') ' if c.action == 'M'
text << ' '.html_safe + content_tag('span', h(c.from_path), :class => 'copied-from') unless c.from_path.blank? text << ' ' + content_tag('span', c.from_path, :class => 'copied-from') unless c.from_path.blank?
output << "<li class='#{style}'>#{text}</li>" output << "<li class='#{style}'>#{text}</li>"
end end
end end
output << '</ul>' output << '</ul>'
output.html_safe output
end
def to_utf8(str)
return str if /\A[\r\n\t\x20-\x7e]*\Z/n.match(str) # for us-ascii
@encodings ||= Setting.repositories_encodings.split(',').collect(&:strip)
@encodings.each do |encoding|
begin
return Iconv.conv('UTF-8', encoding, str)
rescue Iconv::Failure
# do nothing here and try the next encoding
end
end
str
end end
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_SUPPORTED_SCM.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?),
:data => {:remote => true, :method => 'get'}) :onchange => remote_function(: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)
@@ -150,148 +152,37 @@ module RepositoriesHelper
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.safe_attribute?('url')) + '<br />(file:///, http://, https://, svn://, svn+[tunnelscheme]://)') +
'<br />'.html_safe +
'(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.safe_attribute?('url'))) +
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.safe_attribute?('url')
) +
'<br />'.html_safe + l(:text_mercurial_repository_note)) +
content_tag('p', form.select(
:path_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_scm_path_encoding)
) +
'<br />'.html_safe + 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.safe_attribute?('url')
) +
'<br />'.html_safe +
l(:text_git_repository_note)) +
content_tag('p', form.select(
:path_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_scm_path_encoding)
) +
'<br />'.html_safe + 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.safe_attribute?('root_url'))) +
content_tag('p', form.text_field(
:url,
:label => l(:field_cvs_module),
:size => 30, :required => true,
:disabled => !repository.safe_attribute?('url'))) +
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 />'.html_safe + 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.safe_attribute?('url'))) +
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.safe_attribute?('url'))) +
content_tag('p', form.select(
:path_encoding, [nil] + Setting::ENCODINGS,
:label => l(:field_scm_path_encoding)
) +
'<br />'.html_safe + l(:text_scm_path_encoding_note))
end
def index_commits(commits, heads)
return nil if commits.nil? or commits.first.parents.nil?
refs_map = {}
heads.each do |head|
refs_map[head.scmid] ||= []
refs_map[head.scmid] << head
end
commits_by_scmid = {}
commits.reverse.each_with_index do |commit, commit_index|
commits_by_scmid[commit.scmid] = {
:parent_scmids => commit.parents.collect { |parent| parent.scmid },
:rdmid => commit_index,
:refs => refs_map.include?(commit.scmid) ? refs_map[commit.scmid].join(" ") : nil,
:scmid => commit.scmid,
:href => block_given? ? yield(commit.scmid) : commit.scmid
}
end
heads.sort! { |head1, head2| head1.to_s <=> head2.to_s }
space = nil
heads.each do |head|
if commits_by_scmid.include? head.scmid
space = index_head((space || -1) + 1, head, commits_by_scmid)
end
end
# when no head matched anything use first commit
space ||= index_head(0, commits.first, commits_by_scmid)
return commits_by_scmid, space
end
def index_head(space, commit, commits_by_scmid)
stack = [[space, commits_by_scmid[commit.scmid]]]
max_space = space
until stack.empty?
space, commit = stack.pop
commit[:space] = space if commit[:space].nil?
space -= 1
commit[:parent_scmids].each_with_index do |parent_scmid, parent_index|
parent_commit = commits_by_scmid[parent_scmid]
if parent_commit and parent_commit[:space].nil?
stack.unshift [space += 1, parent_commit]
end
end
max_space = space if max_space < space
end
max_space
end end
end end
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
+6 -12
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2007 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -37,11 +35,11 @@ module SearchHelper
result << content_tag('span', h(words), :class => "highlight token-#{t}") result << content_tag('span', h(words), :class => "highlight token-#{t}")
end end
end end
result.html_safe result
end end
def type_label(t) def type_label(t)
l("label_#{t.singularize}_plural", :default => t.to_s.humanize) l("label_#{t.singularize}_plural")
end end
def project_select_tag def project_select_tag
@@ -49,7 +47,6 @@ module SearchHelper
options << [l(:label_my_projects), 'my_projects'] unless User.current.memberships.empty? options << [l(:label_my_projects), 'my_projects'] unless User.current.memberships.empty?
options << [l(:label_and_its_subprojects, @project.name), 'subprojects'] unless @project.nil? || @project.descendants.active.empty? options << [l(:label_and_its_subprojects, @project.name), 'subprojects'] unless @project.nil? || @project.descendants.active.empty?
options << [@project.name, ''] unless @project.nil? options << [@project.name, ''] unless @project.nil?
label_tag("scope", l(:description_project_scope), :class => "hidden-for-sighted") +
select_tag('scope', options_for_select(options, params[:scope].to_s)) if options.size > 1 select_tag('scope', options_for_select(options, params[:scope].to_s)) if options.size > 1
end end
@@ -60,11 +57,8 @@ 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(h(text), :q => params[:q], :titles_only => params[:titles_only], links << link_to(text, :q => params[:q], :titles_only => params[:title_only], :all_words => params[:all_words], :scope => params[:scope], t => 1)
:all_words => params[:all_words], :scope => params[:scope], t => 1)
end end
('<ul>'.html_safe + ('<ul>' + links.map {|link| content_tag('li', link)}.join(' ') + '</ul>') unless links.empty?
links.map {|link| content_tag('li', link)}.join(' ').html_safe +
'</ul>'.html_safe) unless links.empty?
end end
end end
+18 -50
View File
@@ -1,7 +1,5 @@
# encoding: utf-8
#
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -34,73 +32,43 @@ module SettingsHelper
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).html_safe + 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).html_safe
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)
content_tag("label", l(options[:label] || "setting_#{setting}")) + setting_label(setting, options) +
hidden_field_tag("settings[#{setting}][]", '').html_safe + 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( :class => 'block'
"settings[#{setting}][]", )
value, end.join
setting_values.include?(value),
:id => nil
) + text.to_s,
:class => (options[:inline] ? 'inline' : 'block')
)
end.join.html_safe
end end
def setting_text_field(setting, options={}) def setting_text_field(setting, options={})
setting_label(setting, options).html_safe + setting_label(setting, options) +
text_field_tag("settings[#{setting}]", Setting.send(setting), options).html_safe 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).html_safe + setting_label(setting, options) +
text_area_tag("settings[#{setting}]", Setting.send(setting), options).html_safe 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).html_safe + setting_label(setting, options) +
hidden_field_tag("settings[#{setting}]", 0, :id => nil).html_safe + hidden_field_tag("settings[#{setting}]", 0) +
check_box_tag("settings[#{setting}]", 1, Setting.send("#{setting}?"), options).html_safe 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 ? label_tag("settings_#{setting}", l(label || "setting_#{setting}")).html_safe : '' label != false ? content_tag("label", l(label || "setting_#{setting}")) : ''
end
# Renders a notification field for a Redmine::Notifiable option
def notification_field(notifiable)
return content_tag(:label,
check_box_tag('settings[notified_events][]',
notifiable.name,
Setting.notified_events.include?(notifiable.name), :id => nil).html_safe +
l_or_humanize(notifiable.name, :prefix => 'label_').html_safe,
:class => notifiable.parent.present? ? "parent" : '').html_safe
end
def cross_project_subtasks_options
options = [
[:label_disabled, ''],
[:label_cross_project_system, 'system'],
[:label_cross_project_tree, 'tree'],
[:label_cross_project_hierarchy, 'hierarchy'],
[:label_cross_project_descendants, 'descendants']
]
options.map {|label, value| [l(label), value.to_s]}
end end
end end
+9 -26
View File
@@ -1,5 +1,3 @@
# encoding: utf-8
#
# Helpers to sort tables using clickable column headers. # Helpers to sort tables using clickable column headers.
# #
# Author: Stuart Rackham <srackham@methods.co.nz>, March 2005. # Author: Stuart Rackham <srackham@methods.co.nz>, March 2005.
@@ -80,20 +78,15 @@ module SortHelper
@criteria.collect {|k,o| k + (o ? '' : ':desc')}.join(',') @criteria.collect {|k,o| k + (o ? '' : ':desc')}.join(',')
end end
# Returns an array of SQL fragments used to sort the list
def to_sql def to_sql
sql = @criteria.collect do |k,o| sql = @criteria.collect do |k,o|
if s = @available_criteria[k] if s = @available_criteria[k]
(o ? s.to_a : s.to_a.collect {|c| append_desc(c)}) (o ? s.to_a : s.to_a.collect {|c| "#{c} DESC"}).join(', ')
end end
end.flatten.compact end.compact.join(', ')
sql.blank? ? nil : sql sql.blank? ? nil : sql
end end
def to_a
@criteria.dup
end
def add!(key, asc) def add!(key, asc)
@criteria.delete_if {|k,o| k == key} @criteria.delete_if {|k,o| k == key}
@criteria = [[key, asc]] + @criteria @criteria = [[key, asc]] + @criteria
@@ -127,15 +120,6 @@ module SortHelper
@criteria.slice!(3) @criteria.slice!(3)
self self
end end
# Appends DESC to the sort criterion unless it has a fixed order
def append_desc(criterion)
if criterion =~ / (asc|desc)$/i
criterion
else
"#{criterion} DESC"
end
end
end end
def sort_name def sort_name
@@ -165,8 +149,7 @@ module SortHelper
# sort_clause. # sort_clause.
# - criteria can be either an array or a hash of allowed keys # - criteria can be either an array or a hash of allowed keys
# #
def sort_update(criteria, sort_name=nil) def sort_update(criteria)
sort_name ||= self.sort_name
@sort_criteria = SortCriteria.new @sort_criteria = SortCriteria.new
@sort_criteria.available_criteria = criteria @sort_criteria.available_criteria = criteria
@sort_criteria.from_param(params[:sort] || session[sort_name]) @sort_criteria.from_param(params[:sort] || session[sort_name])
@@ -187,10 +170,6 @@ module SortHelper
@sort_criteria.to_sql @sort_criteria.to_sql
end end
def sort_criteria
@sort_criteria
end
# Returns a link which sorts by the named column. # Returns a link which sorts by the named column.
# #
# - column is the name of an attribute in the sorted record collection. # - column is the name of an attribute in the sorted record collection.
@@ -212,12 +191,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(h(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
+76 -40
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -56,10 +54,10 @@ module TimelogHelper
end end
def select_hours(data, criteria, value) def select_hours(data, criteria, value)
if value.to_s.empty? if value.to_s.empty?
data.select {|row| row[criteria].blank? } data.select {|row| row[criteria].blank? }
else else
data.select {|row| row[criteria].to_s == value.to_s} data.select {|row| row[criteria] == value}
end end
end end
@@ -77,7 +75,6 @@ module TimelogHelper
[l(:label_yesterday), 'yesterday'], [l(:label_yesterday), 'yesterday'],
[l(:label_this_week), 'current_week'], [l(:label_this_week), 'current_week'],
[l(:label_last_week), 'last_week'], [l(:label_last_week), 'last_week'],
[l(:label_last_n_weeks, 2), 'last_2_weeks'],
[l(:label_last_n_days, 7), '7_days'], [l(:label_last_n_days, 7), '7_days'],
[l(:label_this_month), 'current_month'], [l(:label_this_month), 'current_month'],
[l(:label_last_month), 'last_month'], [l(:label_last_month), 'last_month'],
@@ -86,10 +83,50 @@ module TimelogHelper
value) value)
end end
def format_criteria_value(criteria_options, value) def entries_to_csv(entries)
ic = Iconv.new(l(:general_csv_encoding), 'UTF-8')
decimal_separator = l(:general_csv_decimal_separator)
custom_fields = TimeEntryCustomField.find(:all)
export = FCSV.generate(:col_sep => l(:general_csv_separator)) do |csv|
# csv header fields
headers = [l(:field_spent_on),
l(:field_user),
l(:field_activity),
l(:field_project),
l(:field_issue),
l(:field_tracker),
l(:field_subject),
l(:field_hours),
l(:field_comments)
]
# Export custom fields
headers += custom_fields.collect(&:name)
csv << headers.collect {|c| begin; ic.iconv(c.to_s); rescue; c.to_s; end }
# csv lines
entries.each do |entry|
fields = [format_date(entry.spent_on),
entry.user,
entry.activity,
entry.project,
(entry.issue ? entry.issue.id : nil),
(entry.issue ? entry.issue.tracker : nil),
(entry.issue ? entry.issue.subject : nil),
entry.hours.to_s.gsub('.', decimal_separator),
entry.comments
]
fields += custom_fields.collect {|f| show_value(entry.custom_value_for(f)) }
csv << fields.collect {|c| begin; ic.iconv(c.to_s); rescue; c.to_s; end }
end
end
export
end
def format_criteria_value(criteria, value)
if value.blank? if value.blank?
"[#{l(:label_none)}]" l(:label_none)
elsif k = criteria_options[:klass] elsif k = @available_criterias[criteria][:klass]
obj = k.find_by_id(value.to_i) obj = k.find_by_id(value.to_i)
if obj.is_a?(Issue) if obj.is_a?(Issue)
obj.visible? ? "#{obj.tracker} ##{obj.id}: #{obj.subject}" : "##{obj.id}" obj.visible? ? "#{obj.tracker} ##{obj.id}: #{obj.subject}" : "##{obj.id}"
@@ -97,58 +134,57 @@ module TimelogHelper
obj obj
end end
else else
format_value(value, criteria_options[:format]) format_value(value, @available_criterias[criteria][:format])
end end
end end
def report_to_csv(report) def report_to_csv(criterias, periods, hours)
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|
# Column headers # Column headers
headers = report.criteria.collect {|criteria| l(report.available_criteria[criteria][:label]) } headers = criterias.collect {|criteria| l(@available_criterias[criteria][:label]) }
headers += report.periods headers += periods
headers << l(:label_total_time) headers << l(:label_total)
csv << headers.collect {|c| Redmine::CodesetUtil.from_utf8( csv << headers.collect {|c| to_utf8(c) }
c.to_s,
l(:general_csv_encoding) ) }
# Content # Content
report_criteria_to_csv(csv, report.available_criteria, report.columns, report.criteria, report.periods, report.hours) report_criteria_to_csv(csv, criterias, periods, hours)
# Total row # Total row
str_total = Redmine::CodesetUtil.from_utf8(l(:label_total_time), l(:general_csv_encoding)) row = [ l(:label_total) ] + [''] * (criterias.size - 1)
row = [ str_total ] + [''] * (report.criteria.size - 1)
total = 0 total = 0
report.periods.each do |period| periods.each do |period|
sum = sum_hours(select_hours(report.hours, report.columns, period.to_s)) sum = sum_hours(select_hours(hours, @columns, period.to_s))
total += sum total += sum
row << (sum > 0 ? ("%.2f" % sum).gsub('.',decimal_separator) : '') row << (sum > 0 ? "%.2f" % sum : '')
end end
row << ("%.2f" % total).gsub('.',decimal_separator) row << "%.2f" %total
csv << row csv << row
end end
export export
end end
def report_criteria_to_csv(csv, available_criteria, columns, criteria, periods, hours, level=0) def report_criteria_to_csv(csv, criterias, periods, hours, level=0)
decimal_separator = l(:general_csv_decimal_separator) hours.collect {|h| h[criterias[level]].to_s}.uniq.each do |value|
hours.collect {|h| h[criteria[level]].to_s}.uniq.each do |value| hours_for_value = select_hours(hours, criterias[level], value)
hours_for_value = select_hours(hours, criteria[level], value)
next if hours_for_value.empty? next if hours_for_value.empty?
row = [''] * level row = [''] * level
row << Redmine::CodesetUtil.from_utf8( row << to_utf8(format_criteria_value(criterias[level], value))
format_criteria_value(available_criteria[criteria[level]], value).to_s, row += [''] * (criterias.length - level - 1)
l(:general_csv_encoding) )
row += [''] * (criteria.length - level - 1)
total = 0 total = 0
periods.each do |period| periods.each do |period|
sum = sum_hours(select_hours(hours_for_value, columns, period.to_s)) sum = sum_hours(select_hours(hours_for_value, @columns, period.to_s))
total += sum total += sum
row << (sum > 0 ? ("%.2f" % sum).gsub('.',decimal_separator) : '') row << (sum > 0 ? "%.2f" % sum : '')
end end
row << ("%.2f" % total).gsub('.',decimal_separator) row << "%.2f" %total
csv << row csv << row
if criteria.length > level + 1
report_criteria_to_csv(csv, available_criteria, columns, criteria, periods, hours_for_value, level + 1) if criterias.length > level + 1
report_criteria_to_csv(csv, criterias, periods, hours_for_value, level + 1)
end end
end end
end end
def to_utf8(s)
@ic ||= Iconv.new(l(:general_csv_encoding), 'UTF-8')
begin; @ic.iconv(s.to_s); rescue; s.to_s; end
end
end end
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,24 +19,29 @@ module UsersHelper
def users_status_options_for_select(selected) def users_status_options_for_select(selected)
user_count_by_status = User.count(:group => 'status').to_hash user_count_by_status = User.count(:group => 'status').to_hash
options_for_select([[l(:label_all), ''], options_for_select([[l(:label_all), ''],
["#{l(:status_active)} (#{user_count_by_status[1].to_i})", '1'], ["#{l(:status_active)} (#{user_count_by_status[1].to_i})", 1],
["#{l(:status_registered)} (#{user_count_by_status[2].to_i})", '2'], ["#{l(:status_registered)} (#{user_count_by_status[2].to_i})", 2],
["#{l(:status_locked)} (#{user_count_by_status[3].to_i})", '3']], selected.to_s) ["#{l(:status_locked)} (#{user_count_by_status[3].to_i})", 3]], selected)
end end
def user_mail_notification_options(user) # Options for the new membership projects combo-box
user.valid_notification_options.collect {|o| [l(o.last), o.first]} def options_for_membership_project_select(user, projects)
options = content_tag('option', "--- #{l(:actionview_instancetag_blank_option)} ---")
options << project_tree_options_for_select(projects) do |p|
{:disabled => (user.projects.include?(p))}
end
options
end end
def change_status_link(user) def change_status_link(user)
url = {:controller => 'users', :action => 'update', :id => user, :page => params[:page], :status => params[:status], :tab => nil} url = {:controller => 'users', :action => 'edit', :id => user, :page => params[:page], :status => params[:status], :tab => nil}
if user.locked? if user.locked?
link_to l(:button_unlock), url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'icon icon-unlock' link_to l(:button_unlock), url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :post, :class => 'icon icon-unlock'
elsif user.registered? elsif user.registered?
link_to l(:button_activate), url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'icon icon-unlock' link_to l(:button_activate), url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :post, :class => 'icon icon-unlock'
elsif user != User.current elsif user != User.current
link_to l(:button_lock), url.merge(:user => {:status => User::STATUS_LOCKED}), :method => :put, :class => 'icon icon-lock' link_to l(:button_lock), url.merge(:user => {:status => User::STATUS_LOCKED}), :method => :post, :class => 'icon icon-lock'
end end
end end
+11 -18
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,30 +17,25 @@
module VersionsHelper module VersionsHelper
def version_anchor(version) STATUS_BY_CRITERIAS = %w(category tracker priority author assigned_to)
if @project == version.project
anchor version.name
else
anchor "#{version.project.try(:identifier)}-#{version.name}"
end
end
STATUS_BY_CRITERIAS = %w(tracker status priority author assigned_to category)
def render_issue_status_by(version, criteria) def render_issue_status_by(version, criteria)
criteria = 'tracker' 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
# Total issue count # Total issue count
Issue.where(:fixed_version_id => version.id).group(criteria).count.each {|c,s| h[c][0] = s} Issue.count(:group => criteria,
:conditions => ["#{Issue.table_name}.fixed_version_id = ?", version.id]).each {|c,s| h[c][0] = s}
# Open issues count # Open issues count
Issue.open.where(:fixed_version_id => version.id).group(criteria).count.each {|c,s| h[c][1] = s} Issue.count(:group => criteria,
:include => :status,
:conditions => ["#{Issue.table_name}.fixed_version_id = ? AND #{IssueStatus.table_name}.is_closed = ?", version.id, false]).each {|c,s| h[c][1] = s}
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
# When grouping by an association, Rails throws this exception if there's no result (bug) # When grouping by an association, Rails throws this exception if there's no result (bug)
end end
# Sort with nil keys in last position counts = h.keys.compact.sort.collect {|k| {:group => k, :total => h[k][0], :open => h[k][1], :closed => (h[k][0] - h[k][1])}}
counts = h.keys.sort {|a,b| a.nil? ? 1 : (b.nil? ? -1 : a <=> b)}.collect {|k| {:group => k, :total => h[k][0], :open => h[k][1], :closed => (h[k][0] - h[k][1])}}
max = counts.collect {|c| c[:total]}.max max = counts.collect {|c| c[:total]}.max
render :partial => 'issue_counts', :locals => {:version => version, :criteria => criteria, :counts => counts, :max => max} render :partial => 'issue_counts', :locals => {:version => version, :criteria => criteria, :counts => counts, :max => max}
+33 -48
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2007 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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,64 +17,51 @@
module WatchersHelper module WatchersHelper
def watcher_tag(object, user, options={}) # Valid options
ActiveSupport::Deprecation.warn "#watcher_tag is deprecated and will be removed in Redmine 3.0. Use #watcher_link instead." # * :id - the element id
watcher_link(object, user) # * :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(objects, user) # Valid options
return '' unless user && user.logged? # * :replace - a string or array of element ids that will be
objects = Array.wrap(objects) # replaced
def watcher_link(object, user, options={:replace => 'watcher'})
return '' unless user && user.logged? && object.respond_to?('watched_by?')
watched = object.watched_by?(user)
url = {:controller => 'watchers',
:action => (watched ? 'unwatch' : 'watch'),
:object_type => object.class.to_s.underscore,
:object_id => object.id,
:replace => options[:replace]}
link_to_remote((watched ? l(:button_unwatch) : l(:button_watch)),
{:url => url},
:href => url_for(url),
:class => (watched ? 'icon icon-fav' : 'icon icon-fav-off'))
watched = Watcher.any_watched?(objects, user)
css = [watcher_css(objects), watched ? 'icon icon-fav' : 'icon icon-fav-off'].join(' ')
text = watched ? l(:button_unwatch) : l(:button_watch)
url = watch_path(
:object_type => objects.first.class.to_s.underscore,
:object_id => (objects.size == 1 ? objects.first.id : objects.map(&:id).sort)
)
method = watched ? 'delete' : 'post'
link_to text, url, :remote => true, :method => method, :class => css
end
# Returns the css class used to identify watch links for a given +object+
def watcher_css(objects)
objects = Array.wrap(objects)
id = (objects.size == 1 ? objects.first.id : 'bulk')
"#{objects.first.class.to_s.underscore}-#{id}-watcher"
end 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)
content = ''.html_safe object.watcher_users.collect do |user|
lis = object.watcher_users.collect do |user| s = content_tag('span', link_to_user(user), :class => 'user')
s = ''.html_safe
s << avatar(user, :size => "16").to_s
s << link_to_user(user, :class => 'user')
if remove_allowed if remove_allowed
url = {:controller => 'watchers', url = {:controller => 'watchers',
:action => 'destroy', :action => 'destroy',
:object_type => object.class.to_s.underscore, :object_type => object.class.to_s.underscore,
:object_id => object.id, :object_id => object.id,
:user_id => user} :user_id => user}
s << ' ' s += ' ' + link_to_remote(image_tag('delete.png'),
s << link_to(image_tag('delete.png'), url, {:url => url},
:remote => true, :method => 'delete', :class => "delete") :href => url_for(url),
:style => "vertical-align: middle")
end end
content << content_tag('li', s, :class => "user-#{user.id}") s
end end.join(",\n")
content.present? ? content_tag('ul', content, :class => 'watchers') : content
end
def watchers_checkboxes(object, users, checked=nil)
users.map do |user|
c = checked.nil? ? object.watched_by?(user) : checked
tag = check_box_tag 'issue[watcher_user_ids][]', user.id, c, :id => nil
content_tag 'label', "#{tag} #{h(user)}".html_safe,
:id => "issue_watcher_user_ids_#{user.id}",
:class => "floating"
end.join.html_safe
end end
end end
+2 -4
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
+44 -18
View File
@@ -1,7 +1,5 @@
# encoding: utf-8 # redMine - project management software
# # Copyright (C) 2006-2007 Jean-Philippe Lang
# Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -20,24 +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 = ''.html_safe pages.select {|p| p.parent == parent}.each do |page|
if pages.has_key?(parent) attrs = "value='#{page.id}'"
pages[parent].each do |page| attrs << " selected='selected'" if selected == page
attrs = "value='#{page.id}'" indent = (level > 0) ? ('&nbsp;' * level * 2 + '&#187; ') : nil
attrs << " selected='selected'" if selected == page
indent = (level > 0) ? ('&nbsp;' * level * 2 + '&#187; ') : ''
s << content_tag('option', (indent + h(page.pretty_title)).html_safe, :value => page.id.to_s, :selected => selected == page) + s << "<option value='#{page.id}'>#{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 wiki_page_breadcrumb(page) def html_diff(wdiff)
breadcrumb(page.ancestors.reverse.collect {|parent| words = wdiff.words.collect{|word| h(word)}
link_to(h(parent.pretty_title), {:controller => 'wiki', :action => 'show', :id => parent.title, :project_id => parent.project, :version => nil}) 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 end
+1 -23
View File
@@ -1,7 +1,5 @@
# encoding: utf-8
#
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -18,24 +16,4 @@
# 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 WorkflowsHelper module WorkflowsHelper
def field_required?(field)
field.is_a?(CustomField) ? field.is_required? : %w(project_id tracker_id subject priority_id is_private).include?(field)
end
def field_permission_tag(permissions, status, field, role)
name = field.is_a?(CustomField) ? field.id.to_s : field
options = [["", ""], [l(:label_readonly), "readonly"]]
options << [l(:label_required), "required"] unless field_required?(field)
html_options = {}
selected = permissions[status.id][name]
hidden = field.is_a?(CustomField) && !field.visible? && !role.custom_fields.to_a.include?(field)
if hidden
options[0][0] = l(:label_hidden)
selected = ''
html_options[:disabled] = true
end
select_tag("permissions[#{name}][#{status.id}]", options_for_select(options, selected), html_options)
end
end end
+38 -204
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,17 +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.
require "digest/md5" require "digest/md5"
require "fileutils"
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 :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
validates_length_of :description, :maximum => 255
validate :validate_max_file_size
acts_as_event :title => :filename, acts_as_event :title => :filename,
:url => Proc.new {|o| {:controller => 'attachments', :action => 'download', :id => o.id, :filename => o.filename}} :url => Proc.new {|o| {:controller => 'attachments', :action => 'download', :id => o.id, :filename => o.filename}}
@@ -46,25 +43,11 @@ class Attachment < ActiveRecord::Base
"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'] || File.join(Rails.root, "files") @@storage_path = "#{RAILS_ROOT}/files"
cattr_accessor :thumbnails_storage_path def validate
@@thumbnails_storage_path = File.join(Rails.root, "tmp", "thumbnails") if self.filesize > Setting.attachment_max_size.to_i.kilobytes
errors.add(:base, :too_long, :count => Setting.attachment_max_size.to_i.kilobytes)
before_save :files_to_final_location
after_destroy :delete_from_disk
# Returns an unsaved copy of the attachment
def copy(attributes=nil)
copy = self.class.new
copy.attributes = self.attributes.dup.except("id", "downloads")
copy.attributes = attributes if attributes
copy
end
def validate_max_file_size
if @temp_file && self.filesize > Setting.attachment_max_size.to_i.kilobytes
errors.add(:base, l(:error_attachment_too_big, :max_size => Setting.attachment_max_size.to_i.kilobytes))
end end
end end
@@ -72,14 +55,10 @@ class Attachment < ActiveRecord::Base
unless incoming_file.nil? unless incoming_file.nil?
@temp_file = incoming_file @temp_file = incoming_file
if @temp_file.size > 0 if @temp_file.size > 0
if @temp_file.respond_to?(:original_filename) self.filename = sanitize_filename(@temp_file.original_filename)
self.filename = @temp_file.original_filename self.disk_filename = Attachment.disk_filename(filename)
self.filename.force_encoding("UTF-8") if filename.respond_to?(:force_encoding) self.content_type = @temp_file.content_type.to_s.chomp
end if content_type.blank?
if @temp_file.respond_to?(:content_type)
self.content_type = @temp_file.content_type.to_s.chomp
end
if content_type.blank? && filename.present?
self.content_type = Redmine::MimeType.of(filename) self.content_type = Redmine::MimeType.of(filename)
end end
self.filesize = @temp_file.size self.filesize = @temp_file.size
@@ -91,62 +70,35 @@ class Attachment < ActiveRecord::Base
nil nil
end end
def filename=(arg)
write_attribute :filename, sanitize_filename(arg.to_s)
filename
end
# Copies the temporary file to its final location # Copies the temporary file to its final location
# and computes its MD5 hash # and computes its MD5 hash
def files_to_final_location def before_save
if @temp_file && (@temp_file.size > 0) if @temp_file && (@temp_file.size > 0)
self.disk_directory = target_directory logger.debug("saving '#{self.diskfile}'")
self.disk_filename = Attachment.disk_filename(filename, disk_directory)
logger.info("Saving attachment '#{self.diskfile}' (#{@temp_file.size} bytes)") if logger
path = File.dirname(diskfile)
unless File.directory?(path)
FileUtils.mkdir_p(path)
end
md5 = Digest::MD5.new md5 = Digest::MD5.new
File.open(diskfile, "wb") do |f| File.open(diskfile, "wb") do |f|
if @temp_file.respond_to?(:read) buffer = ""
buffer = "" while (buffer = @temp_file.read(8192))
while (buffer = @temp_file.read(8192)) f.write(buffer)
f.write(buffer) md5.update(buffer)
md5.update(buffer)
end
else
f.write(@temp_file)
md5.update(@temp_file)
end end
end end
self.digest = md5.hexdigest self.digest = md5.hexdigest
end end
@temp_file = nil
# Don't save the content type if it's longer than the authorized length # Don't save the content type if it's longer than the authorized length
if self.content_type && self.content_type.length > 255 if self.content_type && self.content_type.length > 255
self.content_type = nil self.content_type = nil
end end
end end
# Deletes the file from the file system if it's not referenced by other attachments # Deletes file on the disk
def delete_from_disk def after_destroy
if Attachment.where("disk_filename = ? AND id <> ?", disk_filename, id).empty? File.delete(diskfile) if !filename.blank? && File.exist?(diskfile)
delete_from_disk!
end
end end
# Returns file's location on disk # Returns file's location on disk
def diskfile def diskfile
File.join(self.class.storage_path, disk_directory.to_s, disk_filename.to_s) "#{@@storage_path}/#{self.disk_filename}"
end
def title
title = filename.to_s
if description.present?
title << " (#{description})"
end
title
end end
def increment_download def increment_download
@@ -154,63 +106,19 @@ class Attachment < ActiveRecord::Base
end end
def project def project
container.try(:project) container.project
end end
def visible?(user=User.current) def visible?(user=User.current)
if container_id container.attachments_visible?(user)
container && container.attachments_visible?(user)
else
author == user
end
end end
def deletable?(user=User.current) def deletable?(user=User.current)
if container_id container.attachments_deletable?(user)
container && container.attachments_deletable?(user)
else
author == user
end
end end
def image? def image?
!!(self.filename =~ /\.(bmp|gif|jpg|jpe|jpeg|png)$/i) self.filename =~ /\.(jpe?g|gif|png)$/i
end
def thumbnailable?
image?
end
# Returns the full path the attachment thumbnail, or nil
# if the thumbnail cannot be generated.
def thumbnail(options={})
if thumbnailable? && readable?
size = options[:size].to_i
if size > 0
# Limit the number of thumbnails per image
size = (size / 50) * 50
# Maximum thumbnail size
size = 800 if size > 800
else
size = Setting.thumbnails_size.to_i
end
size = 100 unless size > 0
target = File.join(self.class.thumbnails_storage_path, "#{id}_#{digest}_#{size}.thumb")
begin
Redmine::Thumbnail.generate(self.diskfile, target, size)
rescue => e
logger.error "An error occured while generating thumbnail for #{disk_filename} to #{target}\nException was: #{e.message}" if logger
return nil
end
end
end
# Deletes all thumbnails
def self.clear_thumbnails
Dir.glob(File.join(thumbnails_storage_path, "*.thumb")).each do |file|
File.delete file
end
end end
def is_text? def is_text?
@@ -226,101 +134,27 @@ class Attachment < ActiveRecord::Base
File.readable?(diskfile) File.readable?(diskfile)
end end
# Returns the attachment token private
def token
"#{id}.#{digest}"
end
# Finds an attachment that matches the given token and that has no container
def self.find_by_token(token)
if token.to_s =~ /^(\d+)\.([0-9a-f]+)$/
attachment_id, attachment_digest = $1, $2
attachment = Attachment.where(:id => attachment_id, :digest => attachment_digest).first
if attachment && attachment.container.nil?
attachment
end
end
end
# Bulk attaches a set of files to an object
#
# Returns a Hash of the results:
# :files => array of the attached files
# :unsaved => array of the files that could not be attached
def self.attach_files(obj, attachments)
result = obj.save_attachments(attachments, User.current)
obj.attach_saved_attachments
result
end
def self.latest_attach(attachments, filename)
attachments.sort_by(&:created_on).reverse.detect {
|att| att.filename.downcase == filename.downcase
}
end
def self.prune(age=1.day)
Attachment.where("created_on < ? AND (container_type IS NULL OR container_type = '')", Time.now - age).destroy_all
end
# Moves an existing attachment to its target directory
def move_to_target_directory!
if !new_record? & readable?
src = diskfile
self.disk_directory = target_directory
dest = diskfile
if src != dest && FileUtils.mkdir_p(File.dirname(dest)) && FileUtils.mv(src, dest)
update_column :disk_directory, disk_directory
end
end
end
# Moves existing attachments that are stored at the root of the files
# directory (ie. created before Redmine 2.3) to their target subdirectories
def self.move_from_root_to_target_directory
Attachment.where("disk_directory IS NULL OR disk_directory = ''").find_each do |attachment|
attachment.move_to_target_directory!
end
end
private
# Physically deletes the file from the file system
def delete_from_disk!
if disk_filename.present? && File.exist?(diskfile)
File.delete(diskfile)
end
end
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(/\A.*(\\|\/)/m, '') just_filename = value.gsub(/^.*(\\|\/)/, '')
# NOTE: File.basename doesn't work right with Windows paths on Unix
# INCORRECT: just_filename = File.basename(value.gsub('\\\\', '/'))
# Finally, replace invalid characters with underscore # Finally, replace all non alphanumeric, hyphens or periods with underscore
@filename = just_filename.gsub(/[\/\?\%\*\:\|\"\'<>\n\r]+/, '_') @filename = just_filename.gsub(/[^\w\.\-]/,'_')
end end
# Returns the subdirectory in which the attachment will be saved # Returns an ASCII or hashed filename
def target_directory def self.disk_filename(filename)
time = created_on || DateTime.now df = DateTime.now.strftime("%y%m%d%H%M%S") + "_"
time.strftime("%Y/%m")
end
# Returns an ASCII or hashed filename that do not
# exists yet in the given subdirectory
def self.disk_filename(filename, directory=nil)
timestamp = DateTime.now.strftime("%y%m%d%H%M%S")
ascii = ''
if filename =~ %r{^[a-zA-Z0-9_\.\-]*$} if filename =~ %r{^[a-zA-Z0-9_\.\-]*$}
ascii = filename df << filename
else else
ascii = Digest::MD5.hexdigest(filename) df << Digest::MD5.hexdigest(filename)
# keep the extension if any # keep the extension if any
ascii << $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$} df << $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$}
end end
while File.exist?(File.join(storage_path, directory.to_s, "#{timestamp}_#{ascii}")) df
timestamp.succ!
end
"#{timestamp}_#{ascii}"
end end
end end
+3 -46
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -15,15 +15,7 @@
# 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.
# Generic exception for when the AuthSource can not be reached
# (eg. can not connect to the LDAP)
class AuthSourceException < Exception; end
class AuthSourceTimeoutException < AuthSourceException; end
class AuthSource < ActiveRecord::Base class AuthSource < ActiveRecord::Base
include Redmine::SubclassFactory
include Redmine::Ciphering
has_many :users has_many :users
validates_presence_of :name validates_presence_of :name
@@ -40,44 +32,9 @@ class AuthSource < ActiveRecord::Base
"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 searchable?
false
end
def self.search(q)
results = []
AuthSource.all.each do |source|
begin
if source.searchable?
results += source.search(q)
end
rescue AuthSourceException => e
logger.error "Error while searching users in #{source.name}: #{e.message}"
end
end
results
end
def allow_password_changes?
self.class.allow_password_changes?
end
# Does this auth source backend allow password changes?
def self.allow_password_changes?
false
end
# Try to authenticate a user not yet registered against available sources # Try to authenticate a user not yet registered against available sources
def self.authenticate(login, password) def self.authenticate(login, password)
AuthSource.where(:onthefly_register => true).all.each do |source| AuthSource.find(:all, :conditions => ["onthefly_register=?", true]).each do |source|
begin begin
logger.debug "Authenticating '#{login}' against '#{source.name}'" if logger && logger.debug? logger.debug "Authenticating '#{login}' against '#{source.name}'" if logger && logger.debug?
attrs = source.authenticate(login, password) attrs = source.authenticate(login, password)
+35 -137
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -16,113 +16,65 @@
# 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 'net/ldap' require 'net/ldap'
require 'net/ldap/dn' require 'iconv'
require 'timeout'
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, :filter, :maximum => 255, :allow_blank => 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
validates_numericality_of :timeout, :only_integer => true, :allow_blank => true
validate :validate_filter
before_validation :strip_ldap_attributes before_validation :strip_ldap_attributes
def initialize(attributes=nil, *args) def after_initialize
super
self.port = 389 if self.port == 0 self.port = 389 if self.port == 0
end end
def authenticate(login, password) def authenticate(login, password)
return nil if login.blank? || password.blank? return nil if login.blank? || password.blank?
attrs = []
with_timeout do # get user's DN
attrs = get_user_dn(login, password) ldap_con = initialize_ldap_con(self.account, self.account_password)
if attrs && attrs[:dn] && authenticate_dn(attrs[:dn], password) login_filter = Net::LDAP::Filter.eq( self.attr_login, login )
logger.debug "Authentication successful for '#{login}'" if logger && logger.debug? object_filter = Net::LDAP::Filter.eq( "objectClass", "*" )
return attrs.except(:dn) dn = String.new
end ldap_con.search( :base => self.base_dn,
:filter => object_filter & login_filter,
# only ask for the DN if on-the-fly registration is disabled
:attributes=> (onthefly_register? ? ['dn', self.attr_firstname, self.attr_lastname, self.attr_mail] : ['dn'])) do |entry|
dn = entry.dn
attrs = [:firstname => AuthSourceLdap.get_attr(entry, self.attr_firstname),
:lastname => AuthSourceLdap.get_attr(entry, self.attr_lastname),
:mail => AuthSourceLdap.get_attr(entry, self.attr_mail),
:auth_source_id => self.id ] if onthefly_register?
end end
rescue Net::LDAP::LdapError => e return nil if dn.empty?
raise AuthSourceException.new(e.message) logger.debug "DN found for #{login}: #{dn}" if logger && logger.debug?
# authenticate user
ldap_con = initialize_ldap_con(dn, password)
return nil unless ldap_con.bind
# return user's attributes
logger.debug "Authentication successful for '#{login}'" if logger && logger.debug?
attrs
rescue Net::LDAP::LdapError => text
raise "LdapError: " + text
end end
# test the connection to the LDAP # test the connection to the LDAP
def test_connection def test_connection
with_timeout do ldap_con = initialize_ldap_con(self.account, self.account_password)
ldap_con = initialize_ldap_con(self.account, self.account_password) ldap_con.open { }
ldap_con.open { } rescue Net::LDAP::LdapError => text
end raise "LdapError: " + text
rescue Net::LDAP::LdapError => e
raise AuthSourceException.new(e.message)
end end
def auth_method_name def auth_method_name
"LDAP" "LDAP"
end end
# Returns true if this source can be searched for users
def searchable?
!account.to_s.include?("$login") && %w(login firstname lastname mail).all? {|a| send("attr_#{a}?")}
end
# Searches the source for users and returns an array of results
def search(q)
q = q.to_s.strip
return [] unless searchable? && q.present?
results = []
search_filter = base_filter & Net::LDAP::Filter.begins(self.attr_login, q)
ldap_con = initialize_ldap_con(self.account, self.account_password)
ldap_con.search(:base => self.base_dn,
:filter => search_filter,
:attributes => ['dn', self.attr_login, self.attr_firstname, self.attr_lastname, self.attr_mail],
:size => 10) do |entry|
attrs = get_user_attributes_from_ldap_entry(entry)
attrs[:login] = AuthSourceLdap.get_attr(entry, self.attr_login)
results << attrs
end
results
rescue Net::LDAP::LdapError => e
raise AuthSourceException.new(e.message)
end
private private
def with_timeout(&block)
timeout = self.timeout
timeout = 20 unless timeout && timeout > 0
Timeout.timeout(timeout) do
return yield
end
rescue Timeout::Error => e
raise AuthSourceTimeoutException.new(e.message)
end
def ldap_filter
if filter.present?
Net::LDAP::Filter.construct(filter)
end
rescue Net::LDAP::LdapError
nil
end
def base_filter
filter = Net::LDAP::Filter.eq("objectClass", "*")
if f = ldap_filter
filter = filter & f
end
filter
end
def validate_filter
if filter.present? && ldap_filter.nil?
errors.add(:filter, :invalid)
end
end
def strip_ldap_attributes def strip_ldap_attributes
[:attr_login, :attr_firstname, :attr_lastname, :attr_mail].each do |attr| [:attr_login, :attr_firstname, :attr_lastname, :attr_mail].each do |attr|
write_attribute(attr, read_attribute(attr).strip) unless read_attribute(attr).nil? write_attribute(attr, read_attribute(attr).strip) unless read_attribute(attr).nil?
@@ -138,60 +90,6 @@ class AuthSourceLdap < AuthSource
Net::LDAP.new options Net::LDAP.new options
end end
def get_user_attributes_from_ldap_entry(entry)
{
:dn => entry.dn,
:firstname => AuthSourceLdap.get_attr(entry, self.attr_firstname),
:lastname => AuthSourceLdap.get_attr(entry, self.attr_lastname),
:mail => AuthSourceLdap.get_attr(entry, self.attr_mail),
:auth_source_id => self.id
}
end
# Return the attributes needed for the LDAP search. It will only
# include the user attributes if on-the-fly registration is enabled
def search_attributes
if onthefly_register?
['dn', self.attr_firstname, self.attr_lastname, self.attr_mail]
else
['dn']
end
end
# Check if a DN (user record) authenticates with the password
def authenticate_dn(dn, password)
if dn.present? && password.present?
initialize_ldap_con(dn, password).bind
end
end
# Get the user's dn and any attributes for them, given their login
def get_user_dn(login, password)
ldap_con = nil
if self.account && self.account.include?("$login")
ldap_con = initialize_ldap_con(self.account.sub("$login", Net::LDAP::DN.escape(login)), password)
else
ldap_con = initialize_ldap_con(self.account, self.account_password)
end
attrs = {}
search_filter = base_filter & Net::LDAP::Filter.eq(self.attr_login, login)
ldap_con.search( :base => self.base_dn,
:filter => search_filter,
:attributes=> search_attributes) do |entry|
if onthefly_register?
attrs = get_user_attributes_from_ldap_entry(entry)
else
attrs = {:dn => entry.dn}
end
logger.debug "DN found for #{login}: #{attrs[:dn]}" if logger && logger.debug?
end
attrs
end
def self.get_attr(entry, attr_name) def self.get_attr(entry, attr_name)
if !attr_name.blank? if !attr_name.blank?
entry[attr_name].is_a?(Array) ? entry[attr_name].first : entry[attr_name] entry[attr_name].is_a?(Array) ? entry[attr_name].first : entry[attr_name]
+4 -44
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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,43 +16,25 @@
# 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 Board < ActiveRecord::Base class Board < ActiveRecord::Base
include Redmine::SafeAttributes
belongs_to :project belongs_to :project
has_many :topics, :class_name => 'Message', :conditions => "#{Message.table_name}.parent_id IS NULL", :order => "#{Message.table_name}.created_on DESC" has_many :topics, :class_name => 'Message', :conditions => "#{Message.table_name}.parent_id IS NULL", :order => "#{Message.table_name}.created_on DESC"
has_many :messages, :dependent => :destroy, :order => "#{Message.table_name}.created_on DESC" has_many :messages, :dependent => :delete_all, :order => "#{Message.table_name}.created_on DESC"
belongs_to :last_message, :class_name => 'Message', :foreign_key => :last_message_id belongs_to :last_message, :class_name => 'Message', :foreign_key => :last_message_id
acts_as_tree :dependent => :nullify acts_as_list :scope => :project_id
acts_as_list :scope => '(project_id = #{project_id} AND parent_id #{parent_id ? "= #{parent_id}" : "IS NULL"})'
acts_as_watchable acts_as_watchable
validates_presence_of :name, :description validates_presence_of :name, :description
validates_length_of :name, :maximum => 30 validates_length_of :name, :maximum => 30
validates_length_of :description, :maximum => 255 validates_length_of :description, :maximum => 255
validate :validate_board
scope :visible, lambda {|*args|
includes(:project).where(Project.allowed_to_condition(args.shift || User.current, :view_messages, *args))
}
safe_attributes 'name', 'description', 'parent_id', 'move_to'
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 reload(*args)
@valid_parents = nil
super
end
def to_s def to_s
name name
end end
def valid_parents
@valid_parents ||= project.boards - self_and_descendants
end
def reset_counters! def reset_counters!
self.class.reset_counters!(id) self.class.reset_counters!(id)
end end
@@ -65,26 +47,4 @@ class Board < ActiveRecord::Base
" last_message_id = (SELECT MAX(id) FROM #{Message.table_name} WHERE board_id=#{board_id})", " last_message_id = (SELECT MAX(id) FROM #{Message.table_name} WHERE board_id=#{board_id})",
["id = ?", board_id]) ["id = ?", board_id])
end end
def self.board_tree(boards, parent_id=nil, level=0)
tree = []
boards.select {|board| board.parent_id == parent_id}.sort_by(&:position).each do |board|
tree << [board, level]
tree += board_tree(boards, board.id, level+1)
end
if block_given?
tree.each do |board, level|
yield board, level
end
end
tree
end
protected
def validate_board
if parent_id && parent_id_changed?
errors.add(:parent_id, :invalid) unless valid_parents.include?(parent)
end
end
end end
+2 -13
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -19,19 +19,8 @@ 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_validation :replace_invalid_utf8_of_path
def relative_path def relative_path
changeset.repository.relative_path(path) changeset.repository.relative_path(path)
end end
def replace_invalid_utf8_of_path
self.path = Redmine::CodesetUtil.replace_invalid_utf8(self.path)
self.from_path = Redmine::CodesetUtil.replace_invalid_utf8(self.from_path)
end
def init_path
self.path ||= ""
end
end end
+77 -167
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # Redmine - project management software
# Copyright (C) 2006-2013 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
@@ -15,24 +15,18 @@
# 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'
class Changeset < ActiveRecord::Base class Changeset < ActiveRecord::Base
belongs_to :repository belongs_to :repository
belongs_to :user belongs_to :user
has_many :filechanges, :class_name => 'Change', :dependent => :delete_all has_many :changes, :dependent => :delete_all
has_and_belongs_to_many :issues has_and_belongs_to_many :issues
has_and_belongs_to_many :parents,
:class_name => "Changeset",
:join_table => "#{table_name_prefix}changeset_parents#{table_name_suffix}",
:association_foreign_key => 'parent_id', :foreign_key => 'changeset_id'
has_and_belongs_to_many :children,
:class_name => "Changeset",
:join_table => "#{table_name_prefix}changeset_parents#{table_name_suffix}",
:association_foreign_key => 'changeset_id', :foreign_key => 'parent_id'
acts_as_event :title => Proc.new {|o| o.title}, acts_as_event :title => Proc.new {|o| "#{l(:label_revision)} #{o.revision}" + (o.short_comments.blank? ? '' : (': ' + o.short_comments))},
:description => :long_comments, :description => :long_comments,
:datetime => :committed_on, :datetime => :committed_on,
:url => Proc.new {|o| {:controller => 'repositories', :action => 'revision', :id => o.repository.project, :repository_id => o.repository.identifier_param, :rev => o.identifier}} :url => Proc.new {|o| {:controller => 'repositories', :action => 'revision', :id => o.repository.project, :rev => o.revision}}
acts_as_searchable :columns => 'comments', acts_as_searchable :columns => 'comments',
:include => {:repository => :project}, :include => {:repository => :project},
@@ -47,24 +41,15 @@ class Changeset < ActiveRecord::Base
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
scope :visible, lambda {|*args| named_scope :visible, lambda {|*args| { :include => {:repository => :project},
includes(:repository => :project).where(Project.allowed_to_condition(args.shift || User.current, :view_changesets, *args)) :conditions => Project.allowed_to_condition(args.first || User.current, :view_changesets) } }
}
after_create :scan_for_issues
before_create :before_create_cs
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
# Returns the identifier of this changeset; depending on repository backends def comments=(comment)
def identifier write_attribute(:comments, Changeset.normalize_comments(comment))
if repository.class.respond_to? :changeset_identifier
repository.class.changeset_identifier self
else
revision.to_s
end
end end
def committed_on=(date) def committed_on=(date)
@@ -72,13 +57,8 @@ class Changeset < ActiveRecord::Base
super super
end end
# Returns the readable identifier def committer=(arg)
def format_identifier write_attribute(:committer, self.class.to_utf8(arg.to_s))
if repository.class.respond_to? :format_changeset_identifier
repository.class.format_changeset_identifier self
else
identifier
end
end end
def project def project
@@ -89,56 +69,61 @@ class Changeset < ActiveRecord::Base
user || committer.to_s.split('<').first user || committer.to_s.split('<').first
end end
def before_create_cs 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 scan_for_issues def after_create
scan_comment_for_issue_ids scan_comment_for_issue_ids
end end
require 'pp'
TIMELOG_RE = /
(
((\d+)(h|hours?))((\d+)(m|min)?)?
|
((\d+)(h|hours?|m|min))
|
(\d+):(\d+)
|
(\d+([\.,]\d+)?)h?
)
/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
ref_keywords = Setting.commit_ref_keywords.downcase.split(",").collect(&:strip) ref_keywords = Setting.commit_ref_keywords.downcase.split(",").collect(&:strip)
ref_keywords_any = ref_keywords.delete('*')
# keywords used to fix issues # keywords used to fix issues
fix_keywords = Setting.commit_update_keywords_array.map {|r| r['keywords']}.flatten.compact 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("|")
return if kw_regexp.blank?
referenced_issues = [] referenced_issues = []
comments.scan(/([\s\(\[,-]|^)((#{kw_regexp})[\s:]+)?(#\d+(\s+@#{TIMELOG_RE})?([\s,;&]+#\d+(\s+@#{TIMELOG_RE})?)*)(?=[[:punct:]]|\s|<|$)/i) do |match| if ref_keywords.delete('*')
action, refs = match[2].to_s.downcase, match[3] # find any issue ID in the comments
next unless action.present? || ref_keywords_any target_issue_ids = []
comments.scan(%r{([\s\(\[,-]|^)#(\d+)(?=[[:punct:]]|\s|<|$)}).each { |m| target_issue_ids << m[1] }
referenced_issues += find_referenced_issues_by_id(target_issue_ids)
end
refs.scan(/#(\d+)(\s+@#{TIMELOG_RE})?/).each do |m| comments.scan(Regexp.new("(#{kw_regexp})[\s:]+(([\s,;&]*#?\\d+)+)", Regexp::IGNORECASE)).each do |match|
issue, hours = find_referenced_issue_by_id(m[0].to_i), m[2] action = match[0]
if issue target_issue_ids = match[1].scan(/\d+/)
referenced_issues << issue target_issues = find_referenced_issues_by_id(target_issue_ids)
# Don't update issues or log time when importing old commits if fix_keywords.include?(action.downcase) && fix_status = IssueStatus.find_by_id(Setting.commit_fix_status_id)
unless repository.created_on && committed_on && committed_on < repository.created_on # update status of issues
fix_issue(issue, action) if fix_keywords.include?(action) logger.debug "Issues fixed by changeset #{self.revision}: #{issue_ids.join(', ')}." if logger && logger.debug?
log_time(issue, hours) if hours && Setting.commit_logtime_enabled? target_issues.each do |issue|
# the issue may have been updated by the closure of another one (eg. duplicate)
issue.reload
# don't change the status is the issue is closed
next if issue.status.is_closed?
csettext = "r#{self.revision}"
if self.scmid && (! (csettext =~ /^r[0-9]+$/))
csettext = "commit:\"#{self.scmid}\""
end end
journal = issue.init_journal(user || User.anonymous, ll(Setting.default_language, :text_status_changed_by_changeset, csettext))
issue.status = fix_status
unless Setting.commit_fix_done_ratio.blank?
issue.done_ratio = Setting.commit_fix_done_ratio.to_i
end
Redmine::Hook.call_hook(:model_changeset_scan_commit_for_issue_ids_pre_issue_update,
{ :changeset => self, :issue => issue })
issue.save
end end
end end
referenced_issues += target_issues
end end
referenced_issues.uniq! referenced_issues.uniq!
@@ -153,113 +138,30 @@ class Changeset < ActiveRecord::Base
@long_comments || split_comments.last @long_comments || split_comments.last
end end
def text_tag(ref_project=nil)
tag = if scmid?
"commit:#{scmid}"
else
"r#{revision}"
end
if repository && repository.identifier.present?
tag = "#{repository.identifier}|#{tag}"
end
if ref_project && project && ref_project != project
tag = "#{project.identifier}:#{tag}"
end
tag
end
# Returns the title used for the changeset in the activity/search results
def title
repo = (repository && repository.identifier.present?) ? " (#{repository.identifier})" : ''
comm = short_comments.blank? ? '' : (': ' + short_comments)
"#{l(:label_revision)} #{format_identifier}#{repo}#{comm}"
end
# Returns the previous changeset # Returns the previous changeset
def previous def previous
@previous ||= Changeset.where(["id < ? AND repository_id = ?", id, repository_id]).order('id DESC').first @previous ||= Changeset.find(:first, :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.where(["id > ? AND repository_id = ?", id, repository_id]).order('id ASC').first @next ||= Changeset.find(:first, :conditions => ['id > ? AND repository_id = ?', self.id, self.repository_id], :order => 'id ASC')
end end
# Creates a new Change from it's common parameters # Strips and reencodes a commit log before insertion into the database
def create_change(change) def self.normalize_comments(str)
Change.create(:changeset => self, to_utf8(str.to_s.strip)
:action => change[:action],
:path => change[:path],
:from_path => change[:from_path],
:from_revision => change[:from_revision])
end
# Finds an issue that can be referenced by the commit message
def find_referenced_issue_by_id(id)
return nil if id.blank?
issue = Issue.find_by_id(id.to_i, :include => :project)
if Setting.commit_cross_project_ref?
# all issues can be referenced/fixed
elsif issue
# issue that belong to the repository project, a subproject or a parent project only
unless issue.project &&
(project == issue.project || project.is_ancestor_of?(issue.project) ||
project.is_descendant_of?(issue.project))
issue = nil
end
end
issue
end end
private private
# Updates the +issue+ according to +action+ # Finds issues that can be referenced by the commit message
def fix_issue(issue, action) # i.e. issues that belong to the repository project, a subproject or a parent project
# the issue may have been updated by the closure of another one (eg. duplicate) def find_referenced_issues_by_id(ids)
issue.reload return [] if ids.compact.empty?
# don't change the status is the issue is closed Issue.find_all_by_id(ids, :include => :project).select {|issue|
return if issue.status && issue.status.is_closed? project == issue.project || project.is_ancestor_of?(issue.project) || project.is_descendant_of?(issue.project)
}
journal = issue.init_journal(user || User.anonymous,
ll(Setting.default_language,
:text_status_changed_by_changeset,
text_tag(issue.project)))
rule = Setting.commit_update_keywords_array.detect do |rule|
rule['keywords'].include?(action) &&
(rule['if_tracker_id'].blank? || rule['if_tracker_id'] == issue.tracker_id.to_s)
end
if rule
issue.assign_attributes rule.slice(*Issue.attribute_names)
end
Redmine::Hook.call_hook(:model_changeset_scan_commit_for_issue_ids_pre_issue_update,
{ :changeset => self, :issue => issue, :action => action })
unless issue.save
logger.warn("Issue ##{issue.id} could not be saved by changeset #{id}: #{issue.errors.full_messages}") if logger
end
issue
end
def log_time(issue, hours)
time_entry = TimeEntry.new(
:user => user,
:hours => hours,
:issue => issue,
:spent_on => commit_date,
:comments => l(:text_time_logged_by_changeset, :value => text_tag(issue.project),
:locale => Setting.default_language)
)
time_entry.activity = log_time_activity unless log_time_activity.nil?
unless time_entry.save
logger.warn("TimeEntry could not be created by changeset #{id}: #{time_entry.errors.full_messages}") if logger
end
time_entry
end
def log_time_activity
if Setting.commit_logtime_activity_id.to_i > 0
TimeEntryActivity.find_by_id(Setting.commit_logtime_activity_id.to_i)
end
end end
def split_comments def split_comments
@@ -269,14 +171,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) begin
end str = Iconv.conv('UTF-8', encoding, str)
rescue Iconv::Failure
def self.to_utf8(str, encoding) # do nothing here
Redmine::CodesetUtil.to_utf8(str, encoding) end
end
# 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
+2 -16
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -16,22 +16,8 @@
# 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 Comment < ActiveRecord::Base class Comment < ActiveRecord::Base
include Redmine::SafeAttributes
belongs_to :commented, :polymorphic => true, :counter_cache => true belongs_to :commented, :polymorphic => true, :counter_cache => true
belongs_to :author, :class_name => 'User', :foreign_key => 'author_id' belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
validates_presence_of :commented, :author, :comments validates_presence_of :commented, :author, :comments
after_create :send_notification
safe_attributes 'comments'
private
def send_notification
mailer_method = "#{commented.class.name.underscore}_comment_added"
if Setting.notified_events.include?(mailer_method)
Mailer.send(mailer_method, self).deliver
end
end
end end
+34 -292
View File
@@ -1,5 +1,5 @@
# Redmine - project management software # redMine - project management software
# Copyright (C) 2006-2013 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
@@ -16,124 +16,52 @@
# 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 CustomField < ActiveRecord::Base class CustomField < ActiveRecord::Base
include Redmine::SubclassFactory
has_many :custom_values, :dependent => :delete_all has_many :custom_values, :dependent => :delete_all
has_and_belongs_to_many :roles, :join_table => "#{table_name_prefix}custom_fields_roles#{table_name_suffix}", :foreign_key => "custom_field_id"
acts_as_list :scope => 'type = \'#{self.class}\'' acts_as_list :scope => 'type = \'#{self.class}\''
serialize :possible_values serialize :possible_values
FIELD_FORMATS = { "string" => { :name => :label_string, :order => 1 },
"text" => { :name => :label_text, :order => 2 },
"int" => { :name => :label_integer, :order => 3 },
"float" => { :name => :label_float, :order => 4 },
"list" => { :name => :label_list, :order => 5 },
"date" => { :name => :label_date, :order => 6 },
"bool" => { :name => :label_boolean, :order => 7 }
}.freeze
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_inclusion_of :field_format, :in => Redmine::CustomFieldFormat.available_formats validates_format_of :name, :with => /^[\w\s\.\'\-]*$/i
validate :validate_custom_field validates_inclusion_of :field_format, :in => FIELD_FORMATS.keys
before_validation :set_searchable def initialize(attributes = nil)
after_save :handle_multiplicity_change super
after_save do |field| self.possible_values ||= []
if field.visible_changed? && field.visible
field.roles.clear
end
end end
scope :sorted, lambda { order("#{table_name}.position ASC") } def before_validation
scope :visible, lambda {|*args|
user = args.shift || User.current
if user.admin?
# nop
elsif user.memberships.any?
where("#{table_name}.visible = ? OR #{table_name}.id IN (SELECT DISTINCT cfr.custom_field_id FROM #{Member.table_name} m" +
" INNER JOIN #{MemberRole.table_name} mr ON mr.member_id = m.id" +
" INNER JOIN #{table_name_prefix}custom_fields_roles#{table_name_suffix} cfr ON cfr.role_id = mr.role_id" +
" WHERE m.user_id = ?)",
true, user.id)
else
where(:visible => true)
end
}
def visible_by?(project, user=User.current)
visible? || user.admin?
end
def field_format=(arg)
# cannot change format of a saved custom field
super if new_record?
end
def set_searchable
# make sure these fields are not searchable # make sure these fields are not searchable
self.searchable = false if %w(int float date bool).include?(field_format) self.searchable = false if %w(int float date bool).include?(field_format)
# make sure only these fields can have multiple values
self.multiple = false unless %w(list user version).include?(field_format)
true true
end end
def validate_custom_field def validate
if self.field_format == "list" if self.field_format == "list"
errors.add(:possible_values, :blank) if self.possible_values.nil? || self.possible_values.empty? errors.add(:possible_values, :blank) if self.possible_values.nil? || self.possible_values.empty?
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? # validate default value
begin v = CustomValue.new(:custom_field => self.clone, :value => default_value, :customized => nil)
Regexp.new(regexp) v.custom_field.is_required = false
rescue errors.add(:default_value, :invalid) unless v.valid?
errors.add(:regexp, :invalid)
end
end
if default_value.present? && !valid_field_value?(default_value)
errors.add(:default_value, :invalid)
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)}.reduce(:&)
else
[]
end
when 'bool'
[[l(:general_text_Yes), '1'], [l(:general_text_No), '0']]
else
possible_values || []
end
end
def possible_values(obj=nil)
case field_format
when 'user', 'version'
possible_values_options(obj).collect(&:last)
when 'bool'
['1', '0']
else
values = super()
if values.is_a?(Array)
values.each do |value|
value.force_encoding('UTF-8') if value.respond_to?(:force_encoding)
end
values
else
[]
end
end
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)
super(arg.compact.collect(&:strip).select {|v| !v.blank?}) write_attribute(:possible_values, arg.compact.collect(&:strip).select {|v| !v.blank?})
else else
self.possible_values = arg.to_s.split(/[\n\r]+/) self.possible_values = arg.to_s.split(/[\n\r]+/)
end end
@@ -153,236 +81,50 @@ 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
end end
def value_from_keyword(keyword, customized)
possible_values_options = possible_values_options(customized)
if possible_values_options.present?
keyword = keyword.to_s.downcase
if v = possible_values_options.detect {|text, id| text.downcase == keyword}
if v.is_a?(Array)
v.last
else
v
end
end
else
keyword
end
end
# Returns a ORDER BY clause that can used to sort customized # Returns a ORDER BY clause that can used to sort customized
# objects by their value of the custom field. # objects by their value of the custom field.
# Returns nil if the custom field can not be used for sorting. # Returns false, if the custom field can not be used for sorting.
def order_statement def order_statement
return nil if multiple?
case field_format case field_format
when 'string', 'text', 'list', 'date', 'bool' when 'string', 'text', 'list', 'date', 'bool'
# COALESCE is here to make sure that blank and NULL values are sorted equally # COALESCE is here to make sure that blank and NULL values are sorted equally
"COALESCE(#{join_alias}.value, '')" "COALESCE((SELECT cv_sort.value FROM #{CustomValue.table_name} cv_sort" +
" WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
" AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
" AND cv_sort.custom_field_id=#{id} LIMIT 1), '')"
when 'int', 'float' when 'int', 'float'
# Make the database cast values into numeric # Make the database cast values into numeric
# Postgresql will raise an error if a value can not be casted! # Postgresql will raise an error if a value can not be casted!
# CustomValue validations should ensure that it doesn't occur # CustomValue validations should ensure that it doesn't occur
"CAST(CASE #{join_alias}.value WHEN '' THEN '0' ELSE #{join_alias}.value END AS decimal(30,3))" "(SELECT CAST(cv_sort.value AS decimal(60,3)) FROM #{CustomValue.table_name} cv_sort" +
when 'user', 'version' " WHERE cv_sort.customized_type='#{self.class.customized_class.name}'" +
value_class.fields_for_order_statement(value_join_alias) " AND cv_sort.customized_id=#{self.class.customized_class.table_name}.id" +
" AND cv_sort.custom_field_id=#{id} AND cv_sort.value <> '' AND cv_sort.value IS NOT NULL LIMIT 1)"
else else
nil nil
end end
end end
# Returns a GROUP BY clause that can used to group by custom value
# Returns nil if the custom field can not be used for grouping.
def group_statement
return nil if multiple?
case field_format
when 'list', 'date', 'bool', 'int'
order_statement
when 'user', 'version'
"COALESCE(#{join_alias}.value, '')"
else
nil
end
end
def join_for_order_statement
case field_format
when 'user', 'version'
"LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" +
" ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" +
" AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" +
" AND #{join_alias}.custom_field_id = #{id}" +
" AND (#{visibility_by_project_condition})" +
" AND #{join_alias}.value <> ''" +
" AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" +
" WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" +
" AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" +
" AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)" +
" LEFT OUTER JOIN #{value_class.table_name} #{value_join_alias}" +
" ON CAST(CASE #{join_alias}.value WHEN '' THEN '0' ELSE #{join_alias}.value END AS decimal(30,0)) = #{value_join_alias}.id"
when 'int', 'float'
"LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" +
" ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" +
" AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" +
" AND #{join_alias}.custom_field_id = #{id}" +
" AND (#{visibility_by_project_condition})" +
" AND #{join_alias}.value <> ''" +
" AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" +
" WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" +
" AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" +
" AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)"
when 'string', 'text', 'list', 'date', 'bool'
"LEFT OUTER JOIN #{CustomValue.table_name} #{join_alias}" +
" ON #{join_alias}.customized_type = '#{self.class.customized_class.base_class.name}'" +
" AND #{join_alias}.customized_id = #{self.class.customized_class.table_name}.id" +
" AND #{join_alias}.custom_field_id = #{id}" +
" AND (#{visibility_by_project_condition})" +
" AND #{join_alias}.id = (SELECT max(#{join_alias}_2.id) FROM #{CustomValue.table_name} #{join_alias}_2" +
" WHERE #{join_alias}_2.customized_type = #{join_alias}.customized_type" +
" AND #{join_alias}_2.customized_id = #{join_alias}.customized_id" +
" AND #{join_alias}_2.custom_field_id = #{join_alias}.custom_field_id)"
else
nil
end
end
def join_alias
"cf_#{id}"
end
def value_join_alias
join_alias + "_" + field_format
end
def visibility_by_project_condition(project_key=nil, user=User.current)
if visible? || user.admin?
"1=1"
elsif user.anonymous?
"1=0"
else
project_key ||= "#{self.class.customized_class.table_name}.project_id"
"#{project_key} IN (SELECT DISTINCT m.project_id FROM #{Member.table_name} m" +
" INNER JOIN #{MemberRole.table_name} mr ON mr.member_id = m.id" +
" INNER JOIN #{table_name_prefix}custom_fields_roles#{table_name_suffix} cfr ON cfr.role_id = mr.role_id" +
" WHERE m.user_id = #{user.id} AND cfr.custom_field_id = #{id})"
end
end
def self.visibility_condition
if user.admin?
"1=1"
elsif user.anonymous?
"#{table_name}.visible"
else
"#{project_key} IN (SELECT DISTINCT m.project_id FROM #{Member.table_name} m" +
" INNER JOIN #{MemberRole.table_name} mr ON mr.member_id = m.id" +
" INNER JOIN #{table_name_prefix}custom_fields_roles#{table_name_suffix} cfr ON cfr.role_id = mr.role_id" +
" WHERE m.user_id = #{user.id} AND cfr.custom_field_id = #{id})"
end
end
def <=>(field) def <=>(field)
position <=> field.position position <=> field.position
end end
# Returns the class that values represent
def value_class
case field_format
when 'user', 'version'
field_format.classify.constantize
else
nil
end
end
def self.customized_class def self.customized_class
self.name =~ /^(.+)CustomField$/ self.name =~ /^(.+)CustomField$/
$1.constantize rescue nil begin; $1.constantize; rescue nil; end
end end
# to move in project_custom_field # to move in project_custom_field
def self.for_all def self.for_all
where(:is_for_all => true).order('position').all find(:all, :conditions => ["is_for_all=?", true], :order => 'position')
end end
def type_name def type_name
nil nil
end end
# Returns the error messages for the given value
# or an empty array if value is a valid value for the custom field
def validate_field_value(value)
errs = []
if value.is_a?(Array)
if !multiple?
errs << ::I18n.t('activerecord.errors.messages.invalid')
end
if is_required? && value.detect(&:present?).nil?
errs << ::I18n.t('activerecord.errors.messages.blank')
end
value.each {|v| errs += validate_field_value_format(v)}
else
if is_required? && value.blank?
errs << ::I18n.t('activerecord.errors.messages.blank')
end
errs += validate_field_value_format(value)
end
errs
end
# Returns true if value is a valid value for the custom field
def valid_field_value?(value)
validate_field_value(value).empty?
end
def format_in?(*args)
args.include?(field_format)
end
protected
# Returns the error message for the given value regarding its format
def validate_field_value_format(value)
errs = []
if value.present?
errs << ::I18n.t('activerecord.errors.messages.invalid') unless regexp.blank? or value =~ Regexp.new(regexp)
errs << ::I18n.t('activerecord.errors.messages.too_short', :count => min_length) if min_length > 0 and value.length < min_length
errs << ::I18n.t('activerecord.errors.messages.too_long', :count => max_length) if max_length > 0 and value.length > max_length
# Format specific validations
case field_format
when 'int'
errs << ::I18n.t('activerecord.errors.messages.not_a_number') unless value =~ /^[+-]?\d+$/
when 'float'
begin; Kernel.Float(value); rescue; errs << ::I18n.t('activerecord.errors.messages.invalid') end
when 'date'
errs << ::I18n.t('activerecord.errors.messages.not_a_date') unless value =~ /^\d{4}-\d{2}-\d{2}$/ && begin; value.to_date; rescue; false end
when 'list'
errs << ::I18n.t('activerecord.errors.messages.inclusion') unless possible_values.include?(value)
end
end
errs
end
# Removes multiple values for the custom field after setting the multiple attribute to false
# We kepp the value with the highest id for each customized object
def handle_multiplicity_change
if !new_record? && multiple_was && !multiple
ids = custom_values.
where("EXISTS(SELECT 1 FROM #{CustomValue.table_name} cve WHERE cve.custom_field_id = #{CustomValue.table_name}.custom_field_id" +
" AND cve.customized_type = #{CustomValue.table_name}.customized_type AND cve.customized_id = #{CustomValue.table_name}.customized_id" +
" AND cve.id > #{CustomValue.table_name}.id)").
pluck(:id)
if ids.any?
custom_values.where(:id => ids).delete_all
end
end
end
end end

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