repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
Br3nda/drupal-module-project_issue
db04bcb94745d38f45e07e3cb2554b9c461fe263
#929712 by dww: Added a space between issue title and updated/new marker.
diff --git a/views/default_views/project_issue_all_projects.view.php b/views/default_views/project_issue_all_projects.view.php index 382f43b..a851405 100644 --- a/views/default_views/project_issue_all_projects.view.php +++ b/views/default_views/project_issue_all_projects.view.php @@ -1,432 +1,432 @@ <?php -// $Id: project_issue_all_projects.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ +// $Id: project_issue_all_projects.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ /** * @file * Issue queue across all projects. */ $view = new view; $view->name = 'project_issue_all_projects'; $view->description = 'Project issues for all projects'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => 'New replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'textfield', 'project_source' => 'all', 'project_uid_argument' => '', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); if (module_exists('search')) { $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'none', )); $handler->override_option('title', 'Issues for all projects'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, - 'separator' => '', + 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'Issues', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/rss'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); diff --git a/views/default_views/project_issue_project.view.php b/views/default_views/project_issue_project.view.php index 908f0fb..424ac10 100644 --- a/views/default_views/project_issue_project.view.php +++ b/views/default_views/project_issue_project.view.php @@ -1,581 +1,581 @@ <?php -// $Id: project_issue_project.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ +// $Id: project_issue_project.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ /** * @file * Issue queue for a specific project. */ $view = new view; $view->name = 'project_issue_project'; $view->description = 'Project issues by project'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), )); $fields = array( 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'component' => array( 'label' => 'Component', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => 'New replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $handler->override_option('arguments', array( 'pid' => array( 'default_action' => 'not found', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => '', 'wildcard_substitution' => '', 'title' => 'Issues for %1', 'default_argument_type' => 'fixed', 'default_argument' => '', 'validate_type' => 'project_nid', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', ), )); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'rid' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'rid_op', 'identifier' => 'version', 'label' => 'Version', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'component' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'component_op', 'identifier' => 'component', 'label' => 'Component', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), ); if (module_exists('search')) { $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'none', )); $handler->override_option('title', 'Issues by project'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'component' => 'component', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'title' => array( 'sortable' => 1, - 'separator' => '', + 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'component' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/%'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => '0', 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/rss/%'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('title', 'Recent issues'); $handler->override_option('relationships', array()); $handler->override_option('fields', array( 'title' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', 'override' => array( 'button' => 'Use default', ), ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), )); $handler->override_option('arguments', array( 'pid' => array( 'default_action' => 'default', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => '', 'wildcard_substitution' => '', 'default_argument_type' => 'node', 'default_argument' => '', 'validate_type' => 'project_nid', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array(), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => FALSE, 'expose' => array(), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), )); $handler->override_option('items_per_page', 5); $handler->override_option('use_pager', '0'); $handler->override_option('style_plugin', 'list'); $handler->override_option('style_options', array( 'grouping' => '', 'type' => 'ul', )); $handler->override_option('row_options', array( 'inline' => array( 'title' => 'title', 'timestamp' => 'timestamp', ), 'separator' => ' ', )); $handler->override_option('block_description', 'Project: recent issues'); $handler->override_option('block_caching', -1); diff --git a/views/default_views/project_issue_search_all.view.php b/views/default_views/project_issue_search_all.view.php index 26053c7..28bb68f 100644 --- a/views/default_views/project_issue_search_all.view.php +++ b/views/default_views/project_issue_search_all.view.php @@ -1,503 +1,503 @@ <?php -// $Id: project_issue_search_all.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ +// $Id: project_issue_search_all.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ /** * @file * Advanced issue search for all projects. */ $view = new view; $view->name = 'project_issue_search_all'; $view->description = 'Project issue advanced search for all projects'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'search', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => 'New replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'textfield', 'project_source' => 'all', 'project_uid_argument' => '', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'uid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_op', 'identifier' => 'assigned', 'label' => 'Assigned', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid', 'table' => 'users', 'field' => 'uid', 'relationship' => 'assigned', ), 'uid_1' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_1_op', 'identifier' => 'submitted', 'label' => 'Submitted by', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid_1', 'table' => 'users', 'field' => 'uid', 'relationship' => 'none', ), 'uid_touch' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_touch_op', 'identifier' => 'participant', 'label' => 'Participant', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid_touch', 'table' => 'node', 'field' => 'uid_touch', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); if (module_exists('search')) { $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } _project_issue_views_add_taxonomy_filters($filters); $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'none', )); $handler->override_option('title', 'Search issues for all projects'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, - 'separator' => '', + 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/search'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'Advanced search', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/search/rss'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); diff --git a/views/default_views/project_issue_search_project.view.php b/views/default_views/project_issue_search_project.view.php index 3af1c5f..28785ef 100644 --- a/views/default_views/project_issue_search_project.view.php +++ b/views/default_views/project_issue_search_project.view.php @@ -1,557 +1,557 @@ <?php -// $Id: project_issue_search_project.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ +// $Id: project_issue_search_project.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ /** * @file * Advanced issue search for a specific project. */ $view = new view; $view->name = 'project_issue_search_project'; $view->description = 'Project issue advanced search for specific projects'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'component' => array( 'label' => 'Component', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => 'New replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $handler->override_option('arguments', array( 'pid' => array( 'default_action' => 'not found', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => '', 'wildcard_substitution' => '', 'title' => 'Search issues for %1', 'default_argument_type' => 'fixed', 'default_argument' => '', 'validate_type' => 'project_nid', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', 'validate_argument_node_type' => array(), 'validate_argument_node_access' => 0, 'validate_argument_nid_type' => 'nid', 'validate_argument_vocabulary' => array(), 'validate_argument_type' => 'tid', 'validate_argument_project_term_vocabulary' => array( '1' => 0, ), 'validate_argument_project_term_argument_type' => 'tid', 'validate_argument_project_term_argument_action_top_without' => 'pass', 'validate_argument_project_term_argument_action_top_with' => 'pass', 'validate_argument_project_term_argument_action_child' => 'pass', 'validate_argument_php' => '', ), )); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'uid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_op', 'identifier' => 'assigned', 'label' => 'Assigned', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid', 'table' => 'users', 'field' => 'uid', 'relationship' => 'assigned', ), 'uid_1' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_1_op', 'identifier' => 'submitted', 'label' => 'Submitted by', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid_1', 'table' => 'users', 'field' => 'uid', 'relationship' => 'none', ), 'uid_touch' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_touch_op', 'identifier' => 'participant', 'label' => 'Participant', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid_touch', 'table' => 'node', 'field' => 'uid_touch', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'rid' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'rid_op', 'identifier' => 'version', 'label' => 'Version', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'component' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'component_op', 'identifier' => 'component', 'label' => 'Component', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'component', 'table' => 'project_issues', 'field' => 'component', 'relationship' => 'none', ), ); if (module_exists('search')) { $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } _project_issue_views_add_taxonomy_filters($filters); $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'none', )); $handler->override_option('title', 'Search issues for a project'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'component' => 'component', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'title' => array( 'sortable' => 1, - 'separator' => '', + 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'component' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/search/%'); $handler->override_option('menu', array( 'type' => 'none', 'title' => 'Advanced search', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/search/%/rss'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => '', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); diff --git a/views/default_views/project_issue_user_issues.view.php b/views/default_views/project_issue_user_issues.view.php index b9c022a..210fd78 100644 --- a/views/default_views/project_issue_user_issues.view.php +++ b/views/default_views/project_issue_user_issues.view.php @@ -1,579 +1,579 @@ <?php -// $Id: project_issue_user_issues.view.php,v 1.2 2010/09/14 23:49:50 dww Exp $ +// $Id: project_issue_user_issues.view.php,v 1.3 2010/10/02 23:12:12 dww Exp $ /** * @file * All issues a user has created or commented on. */ $view = new view; $view->name = 'project_issue_user_issues'; $view->description = 'Project issues for a specific user'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => '', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $handler->override_option('arguments', array( 'uid_touch' => array( 'default_action' => 'default', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => 'all', 'wildcard_substitution' => 'All', 'title' => 'Issues for %1', 'default_argument_type' => 'current_user', 'default_argument' => '', 'validate_type' => 'user', 'validate_fail' => 'not found', 'id' => 'uid_touch', 'table' => 'node', 'field' => 'uid_touch', 'relationship' => 'none', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', 'validate_user_argument_type' => 'either', 'validate_user_restrict_roles' => 1, 'validate_user_roles' => array('2' => 2), ), )); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'textfield', 'project_source' => 'participant', 'project_uid_argument' => 'uid_touch', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); if (module_exists('search')) { $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'project_issue_access_per_user_queue', 'project_issue_user_argument' => 'uid_touch', )); $handler->override_option('title', 'My issues'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, - 'separator' => '', + 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/user'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My issues', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/user/%/feed'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('relationships', array( 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $handler->override_option('fields', array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'sid' => array( 'label' => 'Status', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'override' => array( 'button' => 'Use default', ), 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'last_comment_timestamp' => array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), )); $handler->override_option('items_per_page', 15); $handler->override_option('use_pager', '0'); $handler->override_option('use_more', 1); $handler->override_option('use_more_always', 0); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'sid' => 'sid', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 0, 'separator' => '', ), 'title' => array( 'sortable' => 0, 'separator' => '', ), 'sid' => array( 'sortable' => 0, 'separator' => '', ), ), 'default' => '-1', )); $handler->override_option('block_description', ''); $handler->override_option('block_caching', -1); diff --git a/views/default_views/project_issue_user_projects.view.php b/views/default_views/project_issue_user_projects.view.php index a96c504..631950b 100644 --- a/views/default_views/project_issue_user_projects.view.php +++ b/views/default_views/project_issue_user_projects.view.php @@ -1,464 +1,464 @@ <?php -// $Id: project_issue_user_projects.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ +// $Id: project_issue_user_projects.view.php,v 1.2 2010/10/02 23:12:12 dww Exp $ /** * @file * Issues across all projects owned by a user. */ $view = new view; $view->name = 'project_issue_user_projects'; $view->description = "Project issues for a specific user's projects"; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => '', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $handler->override_option('arguments', array( 'uid' => array( 'default_action' => 'default', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => 'all', 'wildcard_substitution' => 'All', 'title' => 'Projects by %1', 'default_argument_type' => 'current_user', 'default_argument' => '', 'validate_type' => 'user', 'validate_fail' => 'not found', 'break_phrase' => 0, 'not' => 0, 'id' => 'uid', 'table' => 'users', 'field' => 'uid', 'relationship' => 'pid', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', 'validate_user_argument_type' => 'either', 'validate_user_restrict_roles' => 1, 'validate_user_roles' => array('2' => 2), ), )); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'select', 'project_source' => 'owner', 'project_uid_argument' => 'uid', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 0, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); if (module_exists('search')) { $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'project_issue_access_per_user_queue', 'project_issue_user_argument' => 'uid', )); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, - 'separator' => '', + 'separator' => ' ', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/user'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My projects', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('row_options', array( 'item_length' => 'default', )); $handler->override_option('path', 'project/user/%/feed'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE);
Br3nda/drupal-module-project_issue
91f03d53aafa0ab30d632586d1d4aa9ec5172d30
#929028 by dww: Made the project_issue_show_comment_signatures setting work.
diff --git a/includes/comment.inc b/includes/comment.inc index 84c3829..d93e6bd 100644 --- a/includes/comment.inc +++ b/includes/comment.inc @@ -1,669 +1,664 @@ <?php -// $Id: comment.inc,v 1.159 2010/04/24 01:58:18 dww Exp $ +// $Id: comment.inc,v 1.160 2010/10/01 21:50:24 dww Exp $ function project_issue_comment(&$arg, $op) { // $arg can be a comment object, or a form or form_values. if (is_object($arg)) { $nid = $arg->nid; } elseif (is_array($arg)) { $nid = is_array($arg['nid']) ? $arg['nid']['#value'] : $arg['nid']; } $node = node_load($nid); if ($node->type != 'project_issue') { return; } // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Maintain an array of project ids that are affected by this comment // operation. We'll use this to invalidate the "Issue cockpit" block cache // for any of these projects. $affected_projects = array(); switch ($op) { case 'insert': // Get a lock on the issue in order to generate the next comment ID. $tries = 20; $sleep_increment = 0; while ($tries) { $lock = db_query("UPDATE {project_issues} SET db_lock = 1 WHERE nid = %d AND db_lock = 0", $arg['nid']); if (db_affected_rows()) { $id = db_result(db_query("SELECT last_comment_id FROM {project_issues} WHERE nid = %d", $arg['nid'])) + 1; db_query("UPDATE {project_issues} SET last_comment_id = %d, db_lock = 0 WHERE nid = %d", $id, $arg['nid']); break; } // Wait a random and increasing amount of time before the next attempt. $sleep = rand(10000, 1000000) + $sleep_increment; usleep($sleep); $sleep_increment += 50000; $tries--; } if (isset($id)) { $rid = isset($arg['project_info']['rid']) ? $arg['project_info']['rid'] : 0; db_query("INSERT INTO {project_issue_comments} (nid, cid, pid, rid, component, category, priority, assigned, sid, title, timestamp, comment_number) VALUES (%d, %d, %d, %d, '%s', '%s', %d, %d, %d, '%s', %d, %d)", $arg['nid'], $arg['cid'], $arg['project_info']['pid'], $rid, $arg['project_info']['component'], $arg['category'], $arg['priority'], $arg['project_info']['assigned'], $arg['sid'], $arg['title'], $arg['timestamp'], $id); db_query("UPDATE {comments} SET subject = '%s' WHERE cid = %d", "#$id", $arg['cid']); project_issue_update_by_comment($arg, 'insert'); $affected_projects[$old_data->pid] = 1; $affected_projects[$arg['project_info']['pid']] = 1; } else { drupal_set_message(t('There was an error submitting your comment -- please try again. If the problem persists, contact the system administrator.'), 'error'); watchdog('project_issue', 'Error obtaining lock for project issue %nid', array('%nid' => $arg['nid']), WATCHDOG_ERROR, 'node/'. $arg['nid']); // This is a bit extreme, but we have to clean up the failed comment, // or it will appear on the issue. _comment_delete_thread((object) $arg); _comment_update_node_statistics($arg['nid']); cache_clear_all(); // The hard redirect prevents any bogus data from being inserted for the failed comment. drupal_goto('node/'. $arg['nid']); } break; case 'update': project_issue_update_by_comment($arg, 'update'); // Updating a comment can't change anything relevant about the issue for // the purposes of the issue blocks, so we don't need to touch // $affected_projects here. break; case 'delete': // Save the project that's specified in this comment so we can // invalidate its issue block cache. $deleted_comment_project_id = db_result(db_query("SELECT pid FROM {project_issue_comments} WHERE cid = %d", $arg->cid)); $affected_projects[$deleted_comment_project_id] = 1; // Actually delete the comment db_query("DELETE FROM {project_issue_comments} WHERE cid = %d", $arg->cid); $current_data = project_issue_update_by_comment($arg, 'delete'); // We should also invalidate the block cache for whatever project is now // used for this issue, since we might be deleting a comment that moved // an issue from one project to another. $affected_projects[$current_data->pid] = 1; break; case 'view': if (isset($arg->cid)) { $project_issue_table = project_issue_comment_view($original_node, $arg); } else { // Previewing a comment. $test = drupal_clone($arg); $test->pid = $arg->project_info['pid']; $test->component = $arg->project_info['component']; $test->assigned = $arg->project_info['assigned']; // Add a dummy rid if necessary -- prevents incorrect change data. $test->rid = isset($arg->project_info['rid']) ? $arg->project_info['rid'] : 0; $comment_changes = project_issue_metadata_changes($node, $old_data, $test, project_issue_field_labels('web')); $project_issue_table = theme('project_issue_comment_table', $comment_changes); } if ($project_issue_table) { $arg->comment = '<div class="project-issue"><div class="summary">'. $project_issue_table .'</div></div>' . $arg->comment; } break; } // If there are any affected projects, invalidate the block cache for those. if (!empty($affected_projects)) { foreach ($affected_projects as $pid => $value) { $cid = 'project_issue_cockpit_block:'. $pid; cache_clear_all($cid, 'cache'); } } } /** * Add project issue metadata to the comment form. * * @param $form * Reference to form structure. * @param $form_state * Current form state. */ function project_issue_form_comment_form_alter(&$form, &$form_state) { $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Comment body is not required since we validate that ourselves. unset($form['comment_filter']['comment']['#required']); // The 'your name' item just wastes screen estate. unset($form['_author']); // For existing comments, we want to preserve the comment subject, // Even if the subject field is disabled. if ($cid = $form['cid']['#value']) { $subject = db_result(db_query('SELECT subject FROM {comments} WHERE cid = %d', $cid)); } // For new comments, show the expected next number for previews. // This is only for show, the number will be generated when the comment // is posted. else { $next_id = db_result(db_query('SELECT last_comment_id FROM {project_issues} WHERE nid = %d', $form['nid']['#value'])) + 1; $subject = "#$next_id"; - // Clobber the comment signature for new followups if necessary. - // TODO: Revamp this for Drupal 6. - if (!variable_get('project_issue_show_comment_signatures', 0)) { - $form['comment_filter']['comment']['#default_value'] = ''; - } } $form['subject'] = array( '#type' => 'value', '#value' => $subject, ); // Any time we're on a reply page, show the full issue below the reply. if (project_issue_is_comment_reply()) { $form['#pre_render'][] = 'project_issue_comment_pre_render'; } // Make sure project is current here -- it may have changed when posted. if (!empty($form_state['values']['project_info']['pid'])) { $node->project_issue['pid'] = $form_state['values']['project_info']['pid']; } $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); project_issue_set_breadcrumb($node, $project); // Only allow metadata changes on new followups. if (isset($form['cid']['#value'])) { return; } // We have to set $form['#action'] to prevent AHAH nastiness. if (!empty($form['pid']['#value'])) { $form['#action'] = url('comment/reply/' . $nid . '/' . $form['pid']['#value']); } else { $form['#action'] = url('comment/reply/' . $nid); } // We need to ask for almost the same metadata as project issue itself // so let's reuse the form. $form += project_issue_form($node, $form_state, TRUE); // comment.module is basically still FAPI v1. It sets the preview button to // #type 'button', so FAPI doesn't really consider that a form submission. // However, we depend on the form being rebuilt on preview to do our magic. // Thanks to a change in 6.14 core, form.inc will only rebuild the form if // $form_state['submitted'] is TRUE. So, we set the preview button to // actually be a 'submit' button so that the form is rebuilt on preview and // our comment preview code can kick in. $form['preview']['#type'] = 'submit'; // We need this otherwise pid collides with comment. $form['project_info']['#tree'] = TRUE; $form['project_info']['#weight'] = -2; // Remove the form item that displays the current project, and // replace the static single project value with a select list // of all projects to make swapping simpler. unset($form['project_info']['project_display']); $uris = NULL; if (variable_get('project_issue_autocomplete', 0) == 1) { $form['project_info']['project_title'] = array( '#type' => 'textfield', '#title' => t('Project'), '#default_value' => $project->title, '#required' => TRUE, '#weight' => -1, '#size' => 35, '#autocomplete_path' => 'project/autocomplete/issue/project', '#attributes' => array( 'onFocus' => 'project_issue_autocomplete_handler()', ), '#ahah' => array( 'progress' => array( 'type' => 'none', ), 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', ), ); } else { $projects = project_projects_select_options($uris); $form['project_info']['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#default_value' => $project->nid, '#options' => $projects, '#required' => TRUE, '#weight' => -1, '#ahah' => array( 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', 'event' => 'change', ), ); } $form['issue_info']['#weight'] = -1; $form['#prefix'] = '<div class="project-issue"><div class="node-form"><div class="standard">'; $form['#suffix'] = '</div></div></div>'; $form['original_issue'] = array( '#type' => 'fieldset', '#title' => t('Edit issue settings'), '#description' => t('Note: changing any of these items will update the issue\'s overall values.'), '#collapsible' => TRUE, '#weight' => -10, ); $form['original_issue']['title'] = array( '#type' => 'textfield', '#title' => t('Issue title'), '#maxlength' => 128, '#default_value' => $node->title, '#weight' => -30, '#required' => TRUE, ); $form['project_info']['assigned'] = $form['issue_info']['assigned']; unset($form['issue_info']['assigned']); $form['project_info']['#prefix'] = '<div id="project-info-wrapper" class="inline-options">'; $form['project_info']['#suffix'] = '</div>'; // Remove the 'Project information' and 'Issue information' fieldsets, // since we'll move everything inside the 'Edit issue settings' fieldset. unset($form['project_info']['#type'], $form['project_info']['#title']); unset($form['issue_info']['#type'], $form['issue_info']['#title']); // Restructure the UI to de-emphasize the original project form inputs. $form['original_issue']['project_info'] = $form['project_info']; $form['original_issue']['issue_info'] = $form['issue_info']; unset($form['project_info'], $form['issue_info']); unset($form['issue_details'], $form['project_help']); drupal_add_js(drupal_get_path('module', 'project_issue') .'/project_issue.js'); } /** * Validate issue metadata on the comment form. * * @param $form * The Drupal form structure. * @param $form_state * The current state of the form. */ function project_issue_form_comment_validate($form, &$form_state) { if (empty($form['cid']['#value']) && variable_get('project_issue_autocomplete', 0) == 1) { if (empty($form_state['values']['project_info']['project_title'])) { form_set_error('project_title', t('You must enter a project to navigate to.')); } else { $pid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_info']['project_title'], 'project_project')); if (empty($pid)) { form_set_error('project_info][project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_info']['project_title']))); } else { $form_state['values']['project_info']['pid'] = $pid; } } } if (!empty($form_state['rebuild'])) { return; } // Only validate metadata changes on new followups. if (isset($form_state['values']['cid'])) { return; } $values = $form_state['values']; $project_info = $form_state['values']['project_info']; $nid = $values['nid']; $node = node_load($nid); // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Adjust new file attachments to go to the issues directory. // We have to do this during validate, otherwise we might miss // adjusting the filename before comment upload saves it (module weighting) // TODO: is this still true? project_issue_change_comment_upload_path($values); // Make sure project is current here -- it may have changed when posted. if (isset($project_info['pid'])) { $node->project_issue['pid'] = $project_info['pid']; } $project = node_load($node->project_issue['pid']); if (!empty($project) && $project->type == 'project_project') { // Force all comments to be a child of the main issue, to match the // flat display, and also to prevent accidentally deleting a thread. $form_state['values']['pid'] = 0; // Validate version. if (module_exists('project_release') && isset($project_info['rid']) && ($releases = project_release_get_releases($project, 0, 'version', 'all', array($project_info['rid'])))) { $rid = $project_info['rid']; if ($rid && !in_array($rid, array_keys($releases))) { $rid = 0; } // Check to make sure this release is not marked as an invalid // release node for user selection. $invalid_rids = variable_get('project_issue_invalid_releases', array()); if (!empty($invalid_rids) && ((empty($rid) && in_array($node->project_issue['rid'], $invalid_rids)) || in_array($rid, $invalid_rids))) { form_set_error('project_info][rid', t('%version is not a valid version, please select a different value.', array('%version' => $releases[$node->project_issue['rid']]))); } elseif (empty($rid)) { form_set_error('project_info][rid', t('You have to specify a valid version.')); } } // Add a dummy rid if necessary -- prevents incorrect change data. else { $rid = 0; } // Validate component. $component = $project_info['component']; if ($component && !in_array($component, $project->project_issue['components'])) { $component = 0; } empty($component) && form_set_error('project_info][component', t('You have to specify a valid component.')); } else { form_set_error('project_info][pid', t('You have to specify a valid project.')); } empty($values['category']) && form_set_error('category', t('You have to specify a valid category.')); // Now, make sure the comment changes *something* about the issue. // If the user uploaded a file, so long as it's not marked for removal, // we consider that a valid change to the issue, too. $has_file = FALSE; $files = isset($values['files']) ? $values['files'] : array(); foreach ($files as $number => $data) { if (empty($data['remove'])) { $has_file = TRUE; break; } } if (!$has_file && empty($values['comment'])) { $comment = drupal_clone((object) $values); $comment->pid = $project_info['pid']; $comment->component = $component; $comment->rid = $rid; $comment->assigned = $project_info['assigned']; $comment_changes = project_issue_metadata_changes($node, $old_data, $comment, project_issue_field_labels('web')); // If the PID changed, rebuild the form if (isset($comment_changes['pid']['new']) && $comment_changes['pid']['new'] === TRUE) { $form_state['rebuild'] = TRUE; } $has_change = FALSE; foreach ($comment_changes as $field => $changes) { if (isset($changes['new'])) { $has_change = TRUE; break; } } if (!$has_change) { form_set_error('comment', t('You must either add a comment, upload a file, or change something about this issue.')); } } } /** * Theme a project issue metadata table. * * @param $comment_changes * Array containing metadata differences between comments * as returned by project_issue_metadata_changes(). * @return * The themed metadata table. */ function theme_project_issue_comment_table($comment_changes) { $rows = array(); foreach ($comment_changes as $field => $change) { if (!empty($change['label']) && isset($change['old']) && isset($change['new'])) { $rows[] = theme('project_issue_comment_table_row', $field, $change); } } return $rows ? theme('table', array(), $rows) : ''; } /** * Theme a single row of the project issue metadata changes table. * * @param $field * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * An array representing one row of the table. * * NOTE: If you override this theme function, you *must* make sure * that you sanitize all output from this function that is displayed * to the user. No further escaping/filtering of the data in this * table will take place after this function. In most cases * this means that you need to run the $change['label'], $change['old'], * and $change['new'] values through either the check_plain() or * filter_xss() function to prevent XSS and other types * of problems due to any malicious input in these * field values. */ function theme_project_issue_comment_table_row($field, $change) { // Allow anchor, emphasis, and strong tags in metadata tables. $allowed_tags = array('a', 'em', 'strong'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])){ foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { $added[] = '+'. $item; } } elseif (!empty($change['new'])) { $added[] = '+'. $change['new']; } return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(implode(', ', $removed), $allowed_tags), filter_xss(implode(', ', $added), $allowed_tags), ); } elseif (in_array($field, $plain_fields)) { return array( filter_xss($change['label'], $allowed_tags) .':', check_plain(project_issue_change_summary($field, $change['old'])), '&raquo; '. check_plain(project_issue_change_summary($field, $change['new'])), ); } else { return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(project_issue_change_summary($field, $change['old']), $allowed_tags), '&raquo; '. filter_xss(project_issue_change_summary($field, $change['new']), $allowed_tags), ); } } /** * Returns the issue metadata table for a comment. * * @param $node * The corresponding node. * @param $comment * The comment, if it's set then metadata will be returned. If it's not * set then metadata will be precalculated. * @return * A themed table of issue metadata. */ function project_issue_comment_view(&$node, $comment = NULL) { static $project_issue_tables; if (isset($comment)) { return isset($project_issue_tables[$comment->cid]) ? $project_issue_tables[$comment->cid] : ''; } if (!empty($node->comment_count)) { $old = unserialize(db_result(db_query('SELECT original_issue_data FROM {project_issues} WHERE nid = %d', $node->nid))); $labels = project_issue_field_labels('web'); $result = db_query('SELECT p.cid, p.title, p.pid, p.rid, p.component, p.category, p.priority, p.assigned, p.sid FROM {project_issue_comments} p INNER JOIN {comments} c ON p.cid = c.cid WHERE p.nid = %d AND c.status = %d ORDER BY p.timestamp ASC', $node->nid, COMMENT_PUBLISHED); while ($followup = db_fetch_object($result)) { $followup_changes = project_issue_metadata_changes($node, $old, $followup, project_issue_field_labels('web')); $project_issue_tables[$followup->cid] = theme('project_issue_comment_table', $followup_changes); $old = $followup; } } } /** * Updates the project issue based on the comment inserted/updated/deleted. * * @param $comment_data * The comment data that's been submitted. * @param $op * The comment operation performed, 'insert', 'update', 'delete'. * @return * An object representing the comment data used to update the issue. */ function project_issue_update_by_comment($comment_data, $op) { switch ($op) { case 'insert': // Massage the incoming data so the structure is consistent throughout the function. $comment_data['component'] = $comment_data['project_info']['component']; $comment_data['pid'] = $comment_data['project_info']['pid']; $comment_data['rid'] = isset($comment_data['project_info']['rid']) ? $comment_data['project_info']['rid'] : 0; unset ($comment_data['project_info']); $comment_data = (object) $comment_data; // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. if (!isset($comment_data->followup_no_mail)) { // Temporary hack to get around sending of auto-close emails. project_issue_set_mail_notify($comment_data->nid); } break; case 'update': $comment_data = (object) $comment_data; break; } // In order to deal with deleted/unpublished comments, make sure that we're performing // the updates to the issue with the latest available published comment. $comment_data = project_issue_get_newest_comment($comment_data); $priority_weight = db_result(db_query('SELECT weight FROM {project_issue_priority} WHERE priority = %d', $comment_data->priority)); // Update the issue data to reflect the new final states. db_query("UPDATE {project_issues} SET pid = %d, category = '%s', component = '%s', priority = %d, rid = %d, assigned = %d, sid = %d, priority_weight = %d WHERE nid = %d", $comment_data->pid, $comment_data->category, $comment_data->component, $comment_data->priority, $comment_data->rid, $comment_data->assigned, $comment_data->sid, $priority_weight, $comment_data->nid); // Update the issue title. $node = node_load($comment_data->nid, NULL, TRUE); // Don't use cached since we changed data above. $node->title = $comment_data->title; // This also updates the changed date of the issue. node_save($node); // Return the object of comment data we used to update the issue. return $comment_data; } /** * Adjusts the filepath of issue followups so files are saved to * the correct issues directory. * * @param $comment * An array of the submitted comment values. */ function project_issue_change_comment_upload_path(&$comment) { static $run = NULL; // Only for new comments with attachments. if (empty($comment['cid']) && isset($comment['files']) && !isset($run)) { $run = TRUE; // Make sure this only gets run once. project_issue_rewrite_issue_filepath($comment['files']); } } /** * Retrieves the newest published comment for an issue. * * @param $comment_data * An object representing the current comment being edited * @return * An object representing the most recent published comment for the issue. */ function project_issue_get_newest_comment($comment_data) { // Get the cid of the most recent comment. $latest_cid = db_result(db_query_range('SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp DESC', $comment_data->nid, COMMENT_PUBLISHED, 0, 1)); if ($latest_cid) { $comment_data = db_fetch_object(db_query('SELECT * FROM {project_issue_comments} WHERE cid = %d', $latest_cid)); } // No more comments on the issue -- use the original issue metadata. else { // nid isn't stored in the original issue data, so capture it here and pass back // into the object. $nid = $comment_data->nid; $comment_data = unserialize(db_result(db_query("SELECT original_issue_data FROM {project_issues} WHERE nid = %d", $comment_data->nid))); $comment_data->nid = $nid; } return $comment_data; } /** * Test to determine if the active page is the comment reply form. * * @return * TRUE if the active page is the comment reply form, FALSE otherwise. */ function project_issue_is_comment_reply() { return arg(0) == 'comment' && arg(1) == 'reply'; } /** * Test to determine if the active page is the comment edit form. * * @return * TRUE if the active page is the comment edit form, FALSE otherwise. */ function project_issue_is_comment_edit() { return arg(0) == 'comment' && arg(1) == 'edit'; } /** * Appends the comment thread to the comment reply form. */ function project_issue_comment_pre_render($form) { // Force the correct formatting. $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; $suffix = empty($form['#suffix']) ? '' : $form['#suffix']; $node = node_load($form['nid']['#value']); // Unfortunately, the comment module blindly puts the node view // after the comment form on preview, in the case where the comment // parent is 0. If we want our issue previews to be consistent, this // ugly hack is necessary. if (isset($form['#parameters'][1]['values']['op']) && $form['#parameters'][1]['values']['op'] == t('Preview')) { $preview = comment_render($node, 0); } diff --git a/project_issue.module b/project_issue.module index 624b72e..ddffb62 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,514 +1,514 @@ <?php -// $Id: project_issue.module,v 1.185 2010/09/30 20:25:27 dww Exp $ +// $Id: project_issue.module,v 1.186 2010/10/01 21:50:23 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } /** * Implementation of hook_ctools_plugin_directory(). */ function project_issue_ctools_plugin_directory($module, $plugin) { if ($module == 'sampler') { switch ($plugin) { case 'metric': return 'metrics'; } } } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administrative pages $items['admin/project/project-issue-priority'] = array( 'title' => 'Project issue priority options', 'description' => 'Configure what issue priorities should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_priority_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.issue_priority.inc', ); $items['admin/project/project-issue-priority/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_priority_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_priority.inc' ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_admin_priority_form' => array( 'file' => 'includes/admin.issue_priority.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); @@ -1389,512 +1389,523 @@ function project_issue_token_values($type = 'all', $object = NULL) { * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { if (isset($result->project_issues_sid)) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; } if (isset($result->project_issues_priority)) { $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } } $variables['class'] .= " project-issue"; } } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( 'info' => t('Issue cockpit'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, ); return $form; } elseif ($op == 'save' && $delta == 'issue_cockpit') { variable_set('project_issue_cockpit_categories', $edit['project_issue_cockpit_categories']); // Invalidate the cache for this block since the categories might change. cache_clear_all('project_issue_cockpit_block:', 'cache', TRUE); } elseif ($op == 'view') { if (isset($edit['homebox']) && isset($edit['homebox']->nid)) { // Homebox provides stored configuration in $edit. $node = node_load($edit['homebox']->nid); } else { // Otherwise check if we are on a project page. $node = project_get_project_from_menu(); } if (!empty($node) && !empty($node->project_issue['issues']) && node_access('view', $node)) { $cid = 'project_issue_cockpit_block:'. $node->nid; if (($cache = cache_get($cid))) { $block = $cache->data; } else { module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); $block = array( 'subject' => t('Issues for @project', array('@project' => $node->title)), 'content' => theme('project_issue_issue_cockpit', $node), ); cache_set($cid, $block); } return $block; } } } /** * Provide a list of keys Homebox will store. */ function project_issue_homebox_block_keys($block) { return array('nid'); } /** * Provide an edit form specific to homebox blocks. * * Allows switching what project is used. */ function project_issue_homebox_block_edit_form($block) { $form = array(); $node = node_load($block->nid); $form['project_title'] = array( '#type' => 'textfield', '#title' => t('Project name'), '#size' => 20, '#autocomplete_path' => 'project/autocomplete/project', '#default_value' => empty($node) ? '' : $node->title, ); $form['#validate'][] = 'project_issue_homebox_block_edit_form_validate'; return $form; } /** * Validation callback for editing the project issue cockpit block via homebox. * * Makes sure a valid project title was entered and populates the nid. The nid * is automatically saved by homebox if it's in $form_state['values'] so * there's no need for a submit callback. */ function project_issue_homebox_block_edit_form_validate($form, &$form_state) { $nid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_title'], 'project_project')); if (empty($nid)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } else { $form_state['values']['nid'] = $nid; } } /** * Implemenation of hook_project_page_link_alter(). * * Add project_issue-specific links to the array of project links. */ function project_issue_project_page_link_alter(&$links, $node) { // TODO: Assumes "patch" issue status values (http://drupal.org/node/27865). // Prepend a link to the development section to view pending patches. if (!empty($node->project['uri'])) { $patches['pending_patches'] = l(t('View pending patches'), 'project/issues/search/'. $node->project['uri'], array('query' => 'status[]=8&status[]=13&status[]=14')); $links['development']['links'] = $patches + $links['development']['links']; } } /** * Implementation of hook_views_post_render(). */ function project_issue_views_post_render(&$view, &$output, &$cache) { // Add links to the top of the project_issue views. $my_projects_views = variable_get('project_issue_my_projects_views', array('project_issue_user_projects')); if (in_array($view->name, $my_projects_views)) { // Tack the "my projects" table onto the user projects view. if ($view->current_display == 'page_1') { $output = project_issue_my_projects_table() . $output; } } // Add links to the issue queue views. $query_link_views = variable_get('project_issue_query_link_views', array('project_issue_all_projects', 'project_issue_project', 'project_issue_search_all', 'project_issue_search_project', 'project_issue_user_issues')); if (in_array($view->name, $query_link_views)) { if ($view->current_display == 'page_1') { $arg = NULL; if (isset($view->argument['pid'])) { $arg = $view->argument['pid']->get_value(); } $output = project_issue_query_result_links($arg) . $output; } } } + +/** + * Preprocess function for the comment theme template. + * + * This enforces the 'project_issue_show_comment_signatures' setting. + */ +function project_issue_preprocess_comment(&$variables) { + if (!variable_get('project_issue_show_comment_signatures', 0)) { + $variables['signature'] = ''; + } +}
Br3nda/drupal-module-project_issue
f9cfcc2b5a94698f479a4858b72b1c74251148ae
#366542 by bdragon, mikey_p, dww: Replaced hook_help() hacks for printing the links at the top of various project issue pages and views.
diff --git a/includes/statistics.inc b/includes/statistics.inc index 8e3de8e..2ee9ea3 100644 --- a/includes/statistics.inc +++ b/includes/statistics.inc @@ -1,132 +1,138 @@ <?php -// $Id: statistics.inc,v 1.1 2009/06/18 03:24:03 dww Exp $ +// $Id: statistics.inc,v 1.2 2010/09/30 20:25:27 dww Exp $ /** * Page callback for the issue statistics page. */ function project_issue_statistics($project = NULL) { $states = project_issue_state(); - if ($project->nid) { + $output = ''; + if (!empty($project->nid)) { $filter = sprintf(' AND p.pid = %d ', (int)$project->nid); project_project_set_breadcrumb($project, TRUE); + $output .= project_issue_query_result_links($project->project['uri']); + } + else { + $output .= project_issue_query_result_links(); + $filter = ''; } - $output = '<div class="project-issue">'; + $output .= '<div class="project-issue">'; // Issue lifetime. $header = array(t('Category'), t('Overall'), t('Last month')); $rows = array(); $duration = time() - 30 * 24 * 60 * 60; $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 GROUP BY p.category'), $filter); while ($stat = db_fetch_object($result)) { $rows[$stat->category][0] = project_issue_category($stat->category); $rows[$stat->category][1] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); $rows[$stat->category][2] = array('data' => t('N/A'), 'class' => 'numeric'); } $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 AND n.created > %d GROUP BY p.category'), $filter, $duration); while ($stat = db_fetch_object($result)) { if ($stat->duration > 0) { $rows[$stat->category][2] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); } } $output .= '<h2>'. t('Average lifetime') .'</h2>'; $output .= theme('table', $header, $rows); $header = array( array('data' => t('Status')), array('data' => t('Overall'), 'class' => 'project-issue-numeric'), array('data' => '%', 'class' => 'project-issue-numeric'), array('data' => t('Last month'), 'class' => 'project-issue-numeric'), ); $rows = array(); // Activity overall. $total = db_result(db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s', 'p'), $filter)); $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s GROUP BY p.sid', 'p'), $filter); while ($stat = db_fetch_object($result)) { $rows[$stat->sid][0] = check_plain(project_issue_state($stat->sid)); $rows[$stat->sid][1] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); $rows[$stat->sid][2] = array('data' => number_format($stat->total / $total * 100) .'%', 'class' => 'project-issue-numeric-light'); $rows[$stat->sid][3] = array('data' => '0', 'class' => 'project-issue-numeric'); } // Activity this month. $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND n.changed > %d GROUP BY p.sid', 'p'), $filter, $duration); while ($stat = db_fetch_object($result)) { $rows[$stat->sid][3] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); } $output .= '<h2>'. t('Issue activity') .'</h2>'; $output .= theme('table', $header, $rows); // Project overview. - if (!$project->nid) { + if (!empty($project->nid)) { // Even though we don't use the tablesorting logic in the query itself, // we include it anyways because we're going to leverage the $_GET arguments // to build our own tablesorting mechanism. $header = array(); $header['project'] = array('data' => t('Project'), 'field' => 'title'); foreach ($states as $key => $value) { $header[$key] = array('data' => check_plain($value), 'field' => $key); } $header['total'] = array('data' => t('Total'), 'field' => 'total'); // Force sorting arrow to appear on active first. $header[1]['sort'] = 'desc'; $args = array(); // Since we're pulling the sid to sort by here individually in the first query // below, we can bastardize the tablesorting logic to get tablesorting. $where = ' AND p.sid = %d'; $column = 'total'; if (isset($_GET['order'])) { switch ($_GET['order']) { case 'Project': $where = ''; $column = 'title'; break; case 'Total': $where = ''; break; default: if ($state = array_search($_GET['order'], $states)) { $args[] = $state; } else { $args[] = 1; } break; } } else { $args[] = 1; } $sort = (isset($_GET['sort']) && $_GET['sort'] == 'desc') || !isset($_GET['sort']) ? 'DESC' : 'ASC'; $rows = array(); $projects = pager_query(db_rewrite_sql("SELECT pn.nid, pn.title, COUNT(n.nid) AS total FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid INNER JOIN {node} pn ON p.pid = pn.nid WHERE n.status = 1 AND pn.status = 1$where GROUP BY pn.nid, pn.title ORDER BY $column $sort"), 15, 0, db_rewrite_sql("SELECT COUNT(DISTINCT(n.nid)) FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.pid INNER JOIN {node} pin ON p.nid = pin.nid WHERE n.status = 1 AND pin.status = 1$where"), $args); $orig = array('project' => array('data' => 0)); foreach ($states as $key => $value) { $orig[$key] = array('data' => '', 'class' => 'project-issue-numeric'); } $orig['total'] = array('data' => '', 'class' => 'project-issue-numeric'); while ($project = db_fetch_object($projects)) { $rows[$project->nid] = $orig; $rows[$project->nid]['project']['data'] = l($project->title, "node/$project->nid"); $stats = db_query("SELECT sid, COUNT(nid) as total FROM {project_issues} WHERE pid = %d GROUP BY sid", $project->nid); while ($stat = db_fetch_object($stats)) { $rows[$project->nid]['total']['data'] += $stat->total; $rows[$project->nid][$stat->sid]['data'] = $stat->total; } } $output .= '<h2>'. t('Project overview') .'</h2>'; $output .= '<div class="project-issue-statistics-overview-table">'; $output .= theme('table', $header, $rows); if ($pager = theme('pager', 15, 0)) { $output .= $pager; } $output .= '</div>'; } $output .= '</div>'; return $output; } diff --git a/includes/subscribe.inc b/includes/subscribe.inc index e3fae4d..581f62f 100644 --- a/includes/subscribe.inc +++ b/includes/subscribe.inc @@ -1,165 +1,173 @@ <?php -// $Id: subscribe.inc,v 1.1 2009/06/18 03:24:59 dww Exp $ +// $Id: subscribe.inc,v 1.2 2010/09/30 20:25:27 dww Exp $ function project_issue_subscribe($form_state, $project_nid = 0) { global $user; if (!valid_email_address($user->mail)) { drupal_set_message(t('You need to provide a valid e-mail address to subscribe to issue e-mails. Please edit your user information.'), 'error'); drupal_goto('user/'. $user->uid .'/edit'); } $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); if ($project_nid) { if (!is_numeric($project_nid)) { $project_nid = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $project_nid)); } if (!$project_nid) { return drupal_not_found(); } $project = node_load($project_nid); project_project_set_breadcrumb($project, TRUE); $level = db_result(db_query('SELECT level FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $project->nid, $user->uid)); $form['single'] = array( '#type' => 'value', '#value' => $project->nid, ); $form['#project'] = array( '#type' => 'value', '#value' => $project, ); $form['subscribe'] = array( '#type' => 'markup', '#value' => '<p>'. t('Subscribe to receive e-mail notification when an issue for this project is updated.') .'</p>', ); $form['options']['#tree'] = TRUE; $form['options'][$project->nid] = array( '#type' => 'radios', '#title' => t('Subscribe to @project issues', array('@project' => $project->title)), '#default_value' => isset($level) ? $level : 0, '#options' => $levels, ); } else { $form['buttons']['all'] = array( '#type' => 'markup', '#value' => t('All projects'), ); foreach ($levels as $key => $level) { $form['buttons'][$level] = array( '#type' => 'submit', '#name' => 'all', '#value' => $level, ); } $nids = array(); $result = db_query(db_rewrite_sql("SELECT s.nid, n.title, s.level, p.uri FROM {project_subscriptions} s INNER JOIN {node} n ON n.nid = s.nid INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1 AND s.uid = %d ORDER BY n.title", 's'), $user->uid); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); foreach ($levels as $key => $level) { if ($project->level == $key) { $status[$project->nid] = $key; } } $nids[] = $project->nid; } if (empty($nids)) { $placeholders = ''; } else { $placeholders = " AND n.nid NOT IN (". implode(',', array_fill(0, count($nids), '%d')) .")"; } $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, p.uri FROM {node} n INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1". ($nids ? $placeholders : "") ." ORDER BY n.title"), $nids); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); $nids[] = $project->nid; } foreach ($nids as $nid) { $form['options']['#tree'] = TRUE; $form['options'][$nid] = array( '#type' => 'radios', '#default_value' => isset($status[$nid]) ? $status[$nid] : 0, '#options' => $levels, ); } } $form['submit'] = array( '#type' => 'submit', '#value' => t('Subscribe'), ); return $form; } function theme_project_issue_subscribe($form) { global $user; $output = ''; + if (empty($form['#project'])) { + $output .= project_issue_query_result_links(); + } + else { + $project = $form['#project']['#value']; + $output .= project_issue_query_result_links($project->project['uri']); + } + if (!isset($form['single'])) { $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); $headers = array_merge(array(t('Project')), $levels); $row = array(); foreach (element_children($form['buttons']) as $key) { $row[] = drupal_render($form['buttons'][$key]); } $rows = array($row); foreach (element_children($form['project']) as $key) { $row = array(drupal_render($form['project'][$key]['title'])); foreach ($levels as $level => $name) { $row[] = drupal_render($form['options'][$key][$level]); } $rows[] = $row; } - $output = theme('table', $headers, $rows); + $output .= theme('table', $headers, $rows); } $output .= drupal_render($form); return $output; } function project_issue_subscribe_submit($form, &$form_state) { global $user; $all = $form_state['clicked_button']['#value']; $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); // Remove previous subscriptions for user. if (isset($form_state['values']['single'])) { db_query('DELETE FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $form_state['values']['single'], $user->uid); } else { db_query('DELETE FROM {project_subscriptions} WHERE uid = %d', $user->uid); } $_level = array_search($all, $levels); foreach ($form_state['values']['options'] as $nid => $level) { if ($_level !== 0 && $level !== 0) { db_query('INSERT INTO {project_subscriptions} (nid, uid, level) VALUES (%d, %d, %d)', $nid, $user->uid, $_level ? $_level : $level); } } drupal_set_message(t('Subscription settings saved.')); if (isset($form['single'])) { $form_state['redirect'] = 'project/issues/subscribe-mail/'. $form['#project']['#value']->project['uri']; } else { $form_state['redirect'] = 'project/issues/subscribe-mail'; } } diff --git a/project_issue.module b/project_issue.module index a0ae3fe..624b72e 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,831 +1,794 @@ <?php -// $Id: project_issue.module,v 1.184 2010/09/30 19:32:58 dww Exp $ +// $Id: project_issue.module,v 1.185 2010/09/30 20:25:27 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } /** * Implementation of hook_ctools_plugin_directory(). */ function project_issue_ctools_plugin_directory($module, $plugin) { if ($module == 'sampler') { switch ($plugin) { case 'metric': return 'metrics'; } } } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administrative pages $items['admin/project/project-issue-priority'] = array( 'title' => 'Project issue priority options', 'description' => 'Configure what issue priorities should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_priority_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.issue_priority.inc', ); $items['admin/project/project-issue-priority/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_priority_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_priority.inc' ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; - - } - - // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't - // want to rely on PHP filtered headers for our views, and defining our - // own display plugin breaks other nice things like RSS, we just cheat - // and render these links in here. We'd like to remove this once a - // better solution is available that doesn't hard-code the paths. - if ($arg[0] == 'project' && $arg[1] == 'user') { - return project_issue_my_projects_table(); - } - - if ($arg[0] == 'project' && $arg[1] == 'issues') { - // If there's no other arg, we're done. - if (empty($arg[2])) { - return project_issue_query_result_links(); - } - // project/issues/user is a special case, since if there's an argument, - // it's a username, not a project. Furthermore, we don't want any links - // for anonymous. - if ($arg[2] == 'user') { - global $user; - if (empty($user->uid) && empty($arg[3])) { - return; - } - return project_issue_query_result_links(); - } - switch ($arg[2]) { - case 'search': - case 'statistics': - case 'subscribe-mail': - return project_issue_query_result_links($arg[3]); - - default: - return project_issue_query_result_links($arg[2]); - } } - } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_admin_priority_form' => array( 'file' => 'includes/admin.issue_priority.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Implement hook_project_permission_info() */ function project_issue_project_permission_info() { return array( 'maintain issues' => array( 'title' => t('Maintain issues'), 'description' => t('Allows a user to assign issues to other issue maintainers for this project.'), ), ); } /** * Implement hook_project_maintainer_save() */ function project_issue_project_maintainer_save($nid, $uid, $permissions = array()) { db_query("UPDATE {project_issue_project_maintainer} SET maintain_issues = %d WHERE nid = %d AND uid = %d", !empty($permissions['maintain issues']), $nid, $uid); if (!db_affected_rows()) { db_query("INSERT INTO {project_issue_project_maintainer} (nid, uid, maintain_issues) VALUES (%d, %d, %d)", $nid, $uid, !empty($permissions['maintain issues'])); } } /** * Implement hook_project_maintainer_remove() */ function project_issue_project_maintainer_remove($nid, $uid) { db_query("DELETE FROM {project_issue_project_maintainer} WHERE nid = %d and uid = %d", $nid, $uid); } /** * Implement hook_project_maintainer_project_load(). */ function project_issue_project_maintainer_project_load($nid, &$maintainers) { $query = db_query('SELECT u.uid, u.name, pipm.maintain_issues FROM {project_issue_project_maintainer} pipm INNER JOIN {users} u ON pipm.uid = u.uid WHERE pipm.nid = %d', $nid); while ($maintainer = db_fetch_object($query)) { if (empty($maintainers[$maintainer->uid])) { $maintainers[$maintainer->uid]['name'] = $maintainer->name; } $maintainers[$maintainer->uid]['permissions']['maintain issues'] = $maintainer->maintain_issues; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = !empty($changes['uid']) ? $changes['uid'] : $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': module_load_include('inc', 'project_issue', 'includes/project_node'); project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { @@ -1401,512 +1364,537 @@ function project_issue_token_values($type = 'all', $object = NULL) { $account = user_load($issue->assigned); $values['project_issue_assigned'] = check_plain($account->name); } $values['project_issue_category'] = project_issue_category($issue->category, FALSE); $values['project_issue_component'] = check_plain($issue->component); $values['project_issue_priority'] = project_issue_priority($issue->priority); $values['project_issue_status'] = check_plain(project_issue_state($issue->sid)); } return $values; } } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { if (isset($result->project_issues_sid)) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; } if (isset($result->project_issues_priority)) { $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } } $variables['class'] .= " project-issue"; } } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( 'info' => t('Issue cockpit'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, ); return $form; } elseif ($op == 'save' && $delta == 'issue_cockpit') { variable_set('project_issue_cockpit_categories', $edit['project_issue_cockpit_categories']); // Invalidate the cache for this block since the categories might change. cache_clear_all('project_issue_cockpit_block:', 'cache', TRUE); } elseif ($op == 'view') { if (isset($edit['homebox']) && isset($edit['homebox']->nid)) { // Homebox provides stored configuration in $edit. $node = node_load($edit['homebox']->nid); } else { // Otherwise check if we are on a project page. $node = project_get_project_from_menu(); } if (!empty($node) && !empty($node->project_issue['issues']) && node_access('view', $node)) { $cid = 'project_issue_cockpit_block:'. $node->nid; if (($cache = cache_get($cid))) { $block = $cache->data; } else { module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); $block = array( 'subject' => t('Issues for @project', array('@project' => $node->title)), 'content' => theme('project_issue_issue_cockpit', $node), ); cache_set($cid, $block); } return $block; } } } /** * Provide a list of keys Homebox will store. */ function project_issue_homebox_block_keys($block) { return array('nid'); } /** * Provide an edit form specific to homebox blocks. * * Allows switching what project is used. */ function project_issue_homebox_block_edit_form($block) { $form = array(); $node = node_load($block->nid); $form['project_title'] = array( '#type' => 'textfield', '#title' => t('Project name'), '#size' => 20, '#autocomplete_path' => 'project/autocomplete/project', '#default_value' => empty($node) ? '' : $node->title, ); $form['#validate'][] = 'project_issue_homebox_block_edit_form_validate'; return $form; } /** * Validation callback for editing the project issue cockpit block via homebox. * * Makes sure a valid project title was entered and populates the nid. The nid * is automatically saved by homebox if it's in $form_state['values'] so * there's no need for a submit callback. */ function project_issue_homebox_block_edit_form_validate($form, &$form_state) { $nid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_title'], 'project_project')); if (empty($nid)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } else { $form_state['values']['nid'] = $nid; } } /** * Implemenation of hook_project_page_link_alter(). * * Add project_issue-specific links to the array of project links. */ function project_issue_project_page_link_alter(&$links, $node) { // TODO: Assumes "patch" issue status values (http://drupal.org/node/27865). // Prepend a link to the development section to view pending patches. if (!empty($node->project['uri'])) { $patches['pending_patches'] = l(t('View pending patches'), 'project/issues/search/'. $node->project['uri'], array('query' => 'status[]=8&status[]=13&status[]=14')); $links['development']['links'] = $patches + $links['development']['links']; } } + +/** + * Implementation of hook_views_post_render(). + */ +function project_issue_views_post_render(&$view, &$output, &$cache) { + // Add links to the top of the project_issue views. + $my_projects_views = variable_get('project_issue_my_projects_views', array('project_issue_user_projects')); + if (in_array($view->name, $my_projects_views)) { + // Tack the "my projects" table onto the user projects view. + if ($view->current_display == 'page_1') { + $output = project_issue_my_projects_table() . $output; + } + } + // Add links to the issue queue views. + $query_link_views = variable_get('project_issue_query_link_views', array('project_issue_all_projects', 'project_issue_project', 'project_issue_search_all', 'project_issue_search_project', 'project_issue_user_issues')); + if (in_array($view->name, $query_link_views)) { + if ($view->current_display == 'page_1') { + $arg = NULL; + if (isset($view->argument['pid'])) { + $arg = $view->argument['pid']->get_value(); + } + $output = project_issue_query_result_links($arg) . $output; + } + } +}
Br3nda/drupal-module-project_issue
f72485a288984d4ff8b7f03168e3606df8d6fc6e
#898180 by drumm, dww: Exposed the per-project issue block to homebox.
diff --git a/project_issue.module b/project_issue.module index 442443c..a0ae3fe 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,514 +1,514 @@ <?php -// $Id: project_issue.module,v 1.183 2010/09/17 17:47:46 thehunmonkgroup Exp $ +// $Id: project_issue.module,v 1.184 2010/09/30 19:32:58 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } /** * Implementation of hook_ctools_plugin_directory(). */ function project_issue_ctools_plugin_directory($module, $plugin) { if ($module == 'sampler') { switch ($plugin) { case 'metric': return 'metrics'; } } } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administrative pages $items['admin/project/project-issue-priority'] = array( 'title' => 'Project issue priority options', 'description' => 'Configure what issue priorities should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_priority_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.issue_priority.inc', ); $items['admin/project/project-issue-priority/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_priority_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_priority.inc' ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_admin_priority_form' => array( 'file' => 'includes/admin.issue_priority.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), @@ -1316,542 +1316,597 @@ function project_issue_requirements($phase) { 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Implement hook_token_list() (from token.module). */ function project_issue_token_list($type) { if ($type == 'node') { $tokens['node'] = array( 'project_issue_pid' => t("The issue's project nid"), 'project_issue_project_title' => t("The issue's project title"), 'project_issue_project_title-raw' => t("The issue's project title raw"), 'project_issue_project_shortname' => t("The issue's project short name"), 'project_issue_category' => t("The issue's category (bug, feature)"), 'project_issue_component' => t("The issue's component"), 'project_issue_priority' => t("The issue's priority"), 'project_issue_version' => t("The issue's version (if any)"), 'project_issue_assigned' => t("The name of the user an issue is assigned to"), 'project_issue_status' => t("The issue's status"), ); return $tokens; } } /** * Implement hook_token_values() (from token.module). */ function project_issue_token_values($type = 'all', $object = NULL) { if ($type == 'node') { // Defaults in case it's not an issue or we can't load its parent project. $values = array( 'project_issue_pid' => '', 'project_issue_project_title' => '', 'project_issue_project_title-raw' => '', 'project_issue_project_shortname' => '', 'project_issue_category' => '', 'project_issue_component' => '', 'project_issue_priority' => '', 'project_issue_version' => '', 'project_issue_assigned' => '', 'project_issue_status' => '', ); if ($object->type == 'project_issue') { if (!empty($object->project_issue)) { // If $node->project_issue exists, use it. $issue = (object)$object->project_issue; } else { $issue = $object; } if ($project = node_load($issue->pid)) { $values['project_issue_pid'] = intval($issue->pid); $values['project_issue_project_title'] = check_plain($project->title); $values['project_issue_project_title-raw'] = $project->title; $values['project_issue_project_shortname'] = check_plain($project->project['uri']); } if (module_exists('project_release') && !empty($issue->rid) && $release = node_load($issue->rid)) { $values['project_issue_version'] = check_plain($release->project_release['version']); } if (!empty($issue->assigned)) { $account = user_load($issue->assigned); $values['project_issue_assigned'] = check_plain($account->name); } $values['project_issue_category'] = project_issue_category($issue->category, FALSE); $values['project_issue_component'] = check_plain($issue->component); $values['project_issue_priority'] = project_issue_priority($issue->priority); $values['project_issue_status'] = check_plain(project_issue_state($issue->sid)); } return $values; } } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { if (isset($result->project_issues_sid)) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; } if (isset($result->project_issues_priority)) { $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } } $variables['class'] .= " project-issue"; } } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( 'info' => t('Issue cockpit'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, ); return $form; } elseif ($op == 'save' && $delta == 'issue_cockpit') { variable_set('project_issue_cockpit_categories', $edit['project_issue_cockpit_categories']); // Invalidate the cache for this block since the categories might change. cache_clear_all('project_issue_cockpit_block:', 'cache', TRUE); } - elseif ($op == 'view' && ($node = project_get_project_from_menu()) && !empty($node->project_issue['issues']) && node_access('view', $node)) { - $cid = 'project_issue_cockpit_block:'. $node->nid; - if (($cache = cache_get($cid))) { - $block = $cache->data; + elseif ($op == 'view') { + if (isset($edit['homebox']) && isset($edit['homebox']->nid)) { + // Homebox provides stored configuration in $edit. + $node = node_load($edit['homebox']->nid); } else { - module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); - $block = array( - 'subject' => t('Issues for @project', array('@project' => $node->title)), - 'content' => theme('project_issue_issue_cockpit', $node), - ); - cache_set($cid, $block); + // Otherwise check if we are on a project page. + $node = project_get_project_from_menu(); } - return $block; + if (!empty($node) && !empty($node->project_issue['issues']) && node_access('view', $node)) { + $cid = 'project_issue_cockpit_block:'. $node->nid; + if (($cache = cache_get($cid))) { + $block = $cache->data; + } + else { + module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); + $block = array( + 'subject' => t('Issues for @project', array('@project' => $node->title)), + 'content' => theme('project_issue_issue_cockpit', $node), + ); + cache_set($cid, $block); + } + return $block; + } + } +} + +/** + * Provide a list of keys Homebox will store. + */ +function project_issue_homebox_block_keys($block) { + return array('nid'); +} + +/** + * Provide an edit form specific to homebox blocks. + * + * Allows switching what project is used. + */ +function project_issue_homebox_block_edit_form($block) { + $form = array(); + + $node = node_load($block->nid); + $form['project_title'] = array( + '#type' => 'textfield', + '#title' => t('Project name'), + '#size' => 20, + '#autocomplete_path' => 'project/autocomplete/project', + '#default_value' => empty($node) ? '' : $node->title, + ); + $form['#validate'][] = 'project_issue_homebox_block_edit_form_validate'; + + return $form; +} + +/** + * Validation callback for editing the project issue cockpit block via homebox. + * + * Makes sure a valid project title was entered and populates the nid. The nid + * is automatically saved by homebox if it's in $form_state['values'] so + * there's no need for a submit callback. + */ +function project_issue_homebox_block_edit_form_validate($form, &$form_state) { + $nid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_title'], 'project_project')); + if (empty($nid)) { + form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); + } + else { + $form_state['values']['nid'] = $nid; } } /** * Implemenation of hook_project_page_link_alter(). * * Add project_issue-specific links to the array of project links. */ function project_issue_project_page_link_alter(&$links, $node) { // TODO: Assumes "patch" issue status values (http://drupal.org/node/27865). // Prepend a link to the development section to view pending patches. if (!empty($node->project['uri'])) { $patches['pending_patches'] = l(t('View pending patches'), 'project/issues/search/'. $node->project['uri'], array('query' => 'status[]=8&status[]=13&status[]=14')); $links['development']['links'] = $patches + $links['development']['links']; } }
Br3nda/drupal-module-project_issue
c6eccc6075e2e2d5c5d6c3333bbec5547b544a66
#914354 by hunmonk, dww: metric to count the total number of open/fixed issues for a project, per category.
diff --git a/metrics/ProjectIssueOpenedVsClosedByCategory.class.php b/metrics/ProjectIssueOpenedVsClosedByCategory.class.php new file mode 100644 index 0000000..82cedeb --- /dev/null +++ b/metrics/ProjectIssueOpenedVsClosedByCategory.class.php @@ -0,0 +1,104 @@ +<?php +// $Id: ProjectIssueOpenedVsClosedByCategory.class.php,v 1.1 2010/09/17 17:47:46 thehunmonkgroup Exp $ + +/** + * @file + * Class for opened_vs_closed_by_category metric. + */ + +class ProjectIssueOpenedVsClosedByCategory extends SamplerMetric { + + public function computeSample() { + // Load options. + $options = $this->currentSample->options; + + $where_pieces = array(); + $args = array(); + + // The initial arguments are the 'open' project issue status options. + $open_states = project_issue_state(0, FALSE, FALSE, 0, TRUE); + + // TODO: Until http://drupal.org/node/214347 is resolved, we don't want + // the 'fixed' status in the list of open statuses, so unset it here. + unset($open_states[PROJECT_ISSUE_STATE_FIXED]); + + $open_states = array_keys($open_states); + + $args = array_merge($args, $open_states); + + // Don't compute if we're on the first sample in a sample set. + if (!$this->getPreviousSample()) { + return FALSE; + } + + // Restrict to only the passed nids. + if (!empty($options['object_ids'])) { + $where_pieces[] = "pid IN (". db_placeholders($options['object_ids']) .")"; + $args = array_merge($args, $options['object_ids']); + } + + if (empty($where_pieces)) { + $where = ''; + } + else { + $where = ' AND ' . implode(' AND ', $where_pieces); + } + + // Build total open issues counts. + $this->buildSampleResults('open', $open_states, $where, $args); + // Build total closed issues counts. + $this->buildSampleResults('closed', $open_states, $where, $args); + + // Add in total counts across all categories. + foreach ($this->currentSample->values as $project_id => $values_array) { + $this->currentSample->values[$project_id]['total_open'] = $values_array['bug_open'] + $values_array['feature_open'] + $values_array['task_open'] + $values_array['support_open']; + $this->currentSample->values[$project_id]['total_closed'] = $values_array['bug_closed'] + $values_array['feature_closed'] + $values_array['task_closed'] + $values_array['support_closed']; + } + } + + /** + * Builds the final values for total open/closed issues per project + * + * @param $state + * Issue state, 'open' or 'closed'. + * @param $open_states + * An array of state IDs that are considered 'open'. + * @param $where + * Additional filters for the query. + * @param $args + * Query arguments. + */ + protected function buildSampleResults($state, $open_states, $where, $args) { + + // Determine IN or NOT IN based on the state we're querying for. + $in = $state == 'open' ? 'IN' : 'NOT IN'; + + // Pull all issues grouped by project/category -- this query will miss any + // projects that don't have issues, but we wouldn't want to show any data + // for them, anyways. + $result = db_query("SELECT pid, category, COUNT(nid) AS count FROM {project_issues} WHERE sid $in (" . db_placeholders($open_states) . ")$where GROUP BY pid, category", $args); + // TODO: When http://drupal.org/node/115553 lands, this hard-coded list of + // categories will need to be handled differently. + $categories = array('bug', 'feature', 'task', 'support'); + $new_row = array( + 'bug_open' => 0, + 'feature_open' => 0, + 'task_open' => 0, + 'support_open' => 0, + 'bug_closed' => 0, + 'feature_closed' => 0, + 'task_closed' => 0, + 'support_closed' => 0, + ); + while ($row = db_fetch_object($result)) { + // Initialize projects with zero values. + if (!isset($this->currentSample->values[$row->pid])) { + $this->currentSample->values[$row->pid] = $new_row; + } + // Add the total count for the category to the values array + if (in_array($row->category, $categories)) { + $this->currentSample->values[$row->pid]["{$row->category}_{$state}"] = $row->count; + } + } + } +} diff --git a/metrics/opened_vs_closed_by_category.inc b/metrics/opened_vs_closed_by_category.inc new file mode 100644 index 0000000..f0259f8 --- /dev/null +++ b/metrics/opened_vs_closed_by_category.inc @@ -0,0 +1,38 @@ +<?php + +// $Id: opened_vs_closed_by_category.inc,v 1.1 2010/09/17 17:47:46 thehunmonkgroup Exp $ + +/** + * @file + * Metric plugin for counting the number of total isses that are open versus + * the total number of issues that are closed. This provides both overall + * totals, and totals per category. + * + * Note that this metric makes no use of the timestamps -- it simply provides + * totals at the time the sample is being taken. + * + * This metric accepts the following options: + * - object_ids: + * An array of nids. If passed it will restrict the results to nodes in + * this list. + */ + +$plugin = array( + 'title' => t('Total open/closed issues'), + 'description' => t("Counts the total number of open and closed issues per category for all projects."), + 'data_type' => array( + 'bug_open' => 'int', + 'feature_open' => 'int', + 'task_open' => 'int', + 'support_open' => 'int', + 'bug_closed' => 'int', + 'feature_closed' => 'int', + 'task_closed' => 'int', + 'support_closed' => 'int', + 'total_open' => 'int', + 'total_closed' => 'int', + ), + 'handler' => array( + 'class' => 'ProjectIssueOpenedVsClosedByCategory', + ), +); diff --git a/project_issue.module b/project_issue.module index f033efc..442443c 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,537 +1,549 @@ <?php -// $Id: project_issue.module,v 1.182 2010/09/14 23:49:06 dww Exp $ +// $Id: project_issue.module,v 1.183 2010/09/17 17:47:46 thehunmonkgroup Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } +/** + * Implementation of hook_ctools_plugin_directory(). + */ +function project_issue_ctools_plugin_directory($module, $plugin) { + if ($module == 'sampler') { + switch ($plugin) { + case 'metric': + return 'metrics'; + } + } +} + function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administrative pages $items['admin/project/project-issue-priority'] = array( 'title' => 'Project issue priority options', 'description' => 'Configure what issue priorities should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_priority_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.issue_priority.inc', ); $items['admin/project/project-issue-priority/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_priority_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_priority.inc' ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_admin_priority_form' => array( 'file' => 'includes/admin.issue_priority.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break;
Br3nda/drupal-module-project_issue
dbfd0a3e3d5cc7c15107aea2bc989939ce1f5055
#898170 by drumm, dww: Added a block display to the 'My issues' view.
diff --git a/views/default_views/project_issue_user_issues.view.php b/views/default_views/project_issue_user_issues.view.php index ba244b8..b9c022a 100644 --- a/views/default_views/project_issue_user_issues.view.php +++ b/views/default_views/project_issue_user_issues.view.php @@ -1,460 +1,579 @@ <?php -// $Id: project_issue_user_issues.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ +// $Id: project_issue_user_issues.view.php,v 1.2 2010/09/14 23:49:50 dww Exp $ /** * @file * All issues a user has created or commented on. */ $view = new view; $view->name = 'project_issue_user_issues'; $view->description = 'Project issues for a specific user'; $view->tag = 'Project issue'; $view->view_php = ''; $view->base_table = 'node'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('relationships', array( 'assigned' => array( 'label' => 'Assigned user', 'required' => 1, 'id' => 'assigned', 'table' => 'project_issues', 'field' => 'assigned', 'relationship' => 'none', ), 'rid' => array( 'label' => 'Version', 'required' => 0, 'id' => 'rid', 'table' => 'project_issues', 'field' => 'rid', 'relationship' => 'none', ), 'pid' => array( 'label' => 'Project node', 'required' => 1, 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', ), )); $fields = array( 'project_issue_queue' => array( 'label' => 'Project', 'link_type' => 'issues', 'exclude' => 0, 'id' => 'project_issue_queue', 'table' => 'node', 'field' => 'project_issue_queue', 'relationship' => 'pid', ), 'title' => array( 'label' => 'Summary', 'link_to_node' => 1, 'exclude' => 0, 'id' => 'title', 'table' => 'node', 'field' => 'title', 'relationship' => 'none', ), 'timestamp' => array( 'label' => '', 'alter' => array(), 'link_to_node' => 0, 'comments' => 0, 'exclude' => 0, 'id' => 'timestamp', 'table' => 'history_user', 'field' => 'timestamp', 'relationship' => 'none', ), 'sid' => array( 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', ), 'priority' => array( 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', ), 'category' => array( 'label' => 'Category', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), 'version' => array( 'label' => 'Version', 'link_to_node' => 0, 'exclude' => 0, 'id' => 'version', 'table' => 'project_release_nodes', 'field' => 'version', 'relationship' => 'rid', ), 'comment_count' => array( 'label' => 'Replies', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'exclude' => 0, 'id' => 'comment_count', 'table' => 'node_comment_statistics', 'field' => 'comment_count', 'relationship' => 'none', ), 'new_comments' => array( 'label' => '', 'set_precision' => FALSE, 'precision' => 0, 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => ' new', 'link_to_comment' => 1, 'no_empty' => 1, 'exclude' => 0, 'id' => 'new_comments', 'table' => 'node', 'field' => 'new_comments', 'relationship' => 'none', ), 'last_comment_timestamp' => array( 'label' => 'Last updated', 'date_format' => 'raw time ago', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ), 'name' => array( 'label' => 'Assigned to', 'link_to_user' => 1, 'overwrite_anonymous' => 1, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'assigned', ), ); if (module_exists('search')) { $fields['score'] = array( 'label' => 'Score', 'alter' => array(), 'set_precision' => 1, 'precision' => '3', 'decimal' => '.', 'separator' => ',', 'prefix' => '', 'suffix' => '', 'alternate_sort' => 'last_comment_timestamp', 'alternate_order' => 'desc', 'exclude' => 0, 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('fields', $fields); $handler->override_option('arguments', array( 'uid_touch' => array( 'default_action' => 'default', 'style_plugin' => 'default_summary', 'style_options' => array(), 'wildcard' => 'all', 'wildcard_substitution' => 'All', 'title' => 'Issues for %1', 'default_argument_type' => 'current_user', 'default_argument' => '', 'validate_type' => 'user', 'validate_fail' => 'not found', 'id' => 'uid_touch', 'table' => 'node', 'field' => 'uid_touch', 'relationship' => 'none', 'default_options_div_prefix' => '', 'default_argument_user' => 0, 'default_argument_fixed' => '', 'default_argument_php' => '', 'validate_user_argument_type' => 'either', 'validate_user_restrict_roles' => 1, 'validate_user_roles' => array('2' => 2), ), )); $sorts['last_comment_timestamp'] = array( 'order' => 'DESC', 'granularity' => 'second', 'id' => 'last_comment_timestamp', 'table' => 'node_comment_statistics', 'field' => 'last_comment_timestamp', 'relationship' => 'none', ); if (module_exists('search')) { $sorts['score'] = array( 'order' => 'DESC', 'id' => 'score', 'table' => 'search_index', 'field' => 'score', 'relationship' => 'none', ); } $handler->override_option('sorts', $sorts); $filters = array( 'status_extra' => array( 'operator' => '=', 'value' => '', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'status_extra', 'table' => 'node', 'field' => 'status_extra', 'relationship' => 'none', ), 'pid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'operator' => 'pid_op', 'label' => 'Project', 'use_operator' => 0, 'identifier' => 'projects', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'widget' => 'textfield', 'project_source' => 'participant', 'project_uid_argument' => 'uid_touch', 'id' => 'pid', 'table' => 'project_issues', 'field' => 'pid', 'relationship' => 'none', ), 'sid' => array( 'operator' => 'in', 'value' => array( 'Open' => 'Open', ), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'sid_op', 'identifier' => 'status', 'label' => 'Status', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'sid', 'table' => 'project_issues', 'field' => 'sid', 'relationship' => 'none', ), 'priority' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'priority_op', 'identifier' => 'priorities', 'label' => 'Priority', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'priority', 'table' => 'project_issues', 'field' => 'priority', 'relationship' => 'none', ), 'category' => array( 'operator' => 'in', 'value' => array(), 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'category_op', 'identifier' => 'categories', 'label' => 'Category', 'optional' => 1, 'single' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'category', 'table' => 'project_issues', 'field' => 'category', 'relationship' => 'none', ), ); if (module_exists('search')) { $search_filter['keys'] = array( 'operator' => 'optional', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'keys_op', 'identifier' => 'text', 'label' => 'Search for', 'optional' => 1, 'remember' => 0, ), 'id' => 'keys', 'table' => 'search_index', 'field' => 'keys', 'relationship' => 'none', ); $filters = $search_filter + $filters; } $handler->override_option('filters', $filters); $handler->override_option('access', array( 'type' => 'project_issue_access_per_user_queue', 'project_issue_user_argument' => 'uid_touch', )); $handler->override_option('title', 'My issues'); $handler->override_option('empty', 'No issues match your criteria.'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 50); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'project_issue_table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 1, 'order' => 'desc', 'columns' => array( 'project_issue_queue' => 'project_issue_queue', 'title' => 'title', 'timestamp' => 'title', 'sid' => 'sid', 'priority' => 'priority', 'category' => 'category', 'version' => 'version', 'comment_count' => 'comment_count', 'new_comments' => 'comment_count', 'last_comment_timestamp' => 'last_comment_timestamp', 'name' => 'name', 'score' => 'score', ), 'info' => array( 'project_issue_queue' => array( 'sortable' => 1, 'separator' => '', ), 'title' => array( 'sortable' => 1, 'separator' => '', ), 'timestamp' => array( 'separator' => '', ), 'sid' => array( 'sortable' => 1, 'separator' => '', ), 'priority' => array( 'sortable' => 1, 'separator' => '', ), 'category' => array( 'sortable' => 1, 'separator' => '', ), 'version' => array( 'sortable' => 1, 'separator' => '', ), 'comment_count' => array( 'sortable' => 1, 'separator' => '<br />', ), 'new_comments' => array( 'separator' => '', ), 'last_comment_timestamp' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'score' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', )); $handler = $view->new_display('page', 'Page', 'page_1'); $handler->override_option('path', 'project/issues/user'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My issues', 'description' => '', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler = $view->new_display('feed', 'Feed', 'feed_1'); $handler->override_option('style_plugin', 'rss'); $handler->override_option('style_options', array( 'mission_description' => FALSE, 'description' => '', )); $handler->override_option('row_plugin', 'node_rss'); $handler->override_option('path', 'project/issues/user/%/feed'); $handler->override_option('menu', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, )); $handler->override_option('displays', array( 'page_1' => 'page_1', 'default' => 0, )); $handler->override_option('sitename_title', FALSE); - +$handler = $view->new_display('block', 'Block', 'block_1'); +$handler->override_option('relationships', array( + 'pid' => array( + 'label' => 'Project node', + 'required' => 1, + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + ), +)); +$handler->override_option('fields', array( + 'project_issue_queue' => array( + 'label' => 'Project', + 'link_type' => 'issues', + 'exclude' => 0, + 'id' => 'project_issue_queue', + 'table' => 'node', + 'field' => 'project_issue_queue', + 'relationship' => 'pid', + ), + 'title' => array( + 'label' => 'Summary', + 'link_to_node' => 1, + 'exclude' => 0, + 'id' => 'title', + 'table' => 'node', + 'field' => 'title', + 'relationship' => 'none', + ), + 'sid' => array( + 'label' => 'Status', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 1, + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + 'override' => array( + 'button' => 'Use default', + ), + 'relationship' => 'none', + ), +)); +$handler->override_option('sorts', array( + 'last_comment_timestamp' => array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', + ), +)); +$handler->override_option('filters', array( + 'status_extra' => array( + 'operator' => '=', + 'value' => '', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'status_extra', + 'table' => 'node', + 'field' => 'status_extra', + 'relationship' => 'none', + ), +)); +$handler->override_option('items_per_page', 15); +$handler->override_option('use_pager', '0'); +$handler->override_option('use_more', 1); +$handler->override_option('use_more_always', 0); +$handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 1, + 'order' => 'desc', + 'columns' => array( + 'project_issue_queue' => 'project_issue_queue', + 'title' => 'title', + 'sid' => 'sid', + ), + 'info' => array( + 'project_issue_queue' => array( + 'sortable' => 0, + 'separator' => '', + ), + 'title' => array( + 'sortable' => 0, + 'separator' => '', + ), + 'sid' => array( + 'sortable' => 0, + 'separator' => '', + ), + ), + 'default' => '-1', +)); +$handler->override_option('block_description', ''); +$handler->override_option('block_caching', -1);
Br3nda/drupal-module-project_issue
adf3ee50d9f6caa3ffb82c8d8f7f7ae0cb20774e
#898170 by dww: Fixed bug in project_issue_preprocess_views_view_table() where it assumed every result has both a status and a priority.
diff --git a/project_issue.module b/project_issue.module index a9b6123..f033efc 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,514 +1,514 @@ <?php -// $Id: project_issue.module,v 1.181 2010/08/19 16:31:29 dww Exp $ +// $Id: project_issue.module,v 1.182 2010/09/14 23:49:06 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administrative pages $items['admin/project/project-issue-priority'] = array( 'title' => 'Project issue priority options', 'description' => 'Configure what issue priorities should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_priority_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.issue_priority.inc', ); $items['admin/project/project-issue-priority/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_priority_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_priority.inc' ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_admin_priority_form' => array( 'file' => 'includes/admin.issue_priority.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', @@ -1086,756 +1086,760 @@ function project_issue_my_projects_table() { } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes)); } $output = '<span class="project-issue-status-'. $node->project_issue['sid'] .' project-issue-status-info">'. $link; if ($include_assigned && !empty($username)) { $output .= ' <span class="project-issue-assigned-user">'. t('Assigned to: @username', array('@username' => $username)) .'</span>'; } $output .= '</span>'; return $output; } /** * Implementation of hook_form_filter_tips(). * @ingroup project_issue_filter */ function project_issue_filter_tips($delta, $format, $long = FALSE) { if ($long) { return t("References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically, with the title of the issue appended. The status of the issue is shown on hover. If '@' is appended (e.g. [#1234@]), the user the issue is assigned to will also be printed."); } else { return t('Project issue numbers (ex. [#12345]) turn into links automatically.'); } } /** * Implementation of hook_filter(). * @ingroup project_issue_filter */ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { switch ($op) { case 'list': return array(0 => t('Project Issue to link filter')); case 'description': return t('Converts references to project issues (in the form of [#12345]) into links. Caching should be disabled if node access control modules are used.'); case 'no cache': return FALSE; case 'prepare': return $text; case 'process': $regex = '(?:(?<!\w)\[#\d+(?:-\d+)?(@)?\](?!\w))|<pre>.*?<\/pre>|<code>.*?<\/code>|<a(?:[^>"\']|"[^"]*"|\'[^\']*\')*>.*?<\/a>'; $text = preg_replace_callback("/$regex/", 'project_issue_link_filter_callback', $text); return $text; } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); $allowed_roles = user_roles(FALSE, 'access project issues'); $conflict_anonymous = empty($allowed_roles[DRUPAL_ANONYMOUS_RID]); foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if (!empty($grants) && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Implement hook_token_list() (from token.module). */ function project_issue_token_list($type) { if ($type == 'node') { $tokens['node'] = array( 'project_issue_pid' => t("The issue's project nid"), 'project_issue_project_title' => t("The issue's project title"), 'project_issue_project_title-raw' => t("The issue's project title raw"), 'project_issue_project_shortname' => t("The issue's project short name"), 'project_issue_category' => t("The issue's category (bug, feature)"), 'project_issue_component' => t("The issue's component"), 'project_issue_priority' => t("The issue's priority"), 'project_issue_version' => t("The issue's version (if any)"), 'project_issue_assigned' => t("The name of the user an issue is assigned to"), 'project_issue_status' => t("The issue's status"), ); return $tokens; } } /** * Implement hook_token_values() (from token.module). */ function project_issue_token_values($type = 'all', $object = NULL) { if ($type == 'node') { // Defaults in case it's not an issue or we can't load its parent project. $values = array( 'project_issue_pid' => '', 'project_issue_project_title' => '', 'project_issue_project_title-raw' => '', 'project_issue_project_shortname' => '', 'project_issue_category' => '', 'project_issue_component' => '', 'project_issue_priority' => '', 'project_issue_version' => '', 'project_issue_assigned' => '', 'project_issue_status' => '', ); if ($object->type == 'project_issue') { if (!empty($object->project_issue)) { // If $node->project_issue exists, use it. $issue = (object)$object->project_issue; } else { $issue = $object; } if ($project = node_load($issue->pid)) { $values['project_issue_pid'] = intval($issue->pid); $values['project_issue_project_title'] = check_plain($project->title); $values['project_issue_project_title-raw'] = $project->title; $values['project_issue_project_shortname'] = check_plain($project->project['uri']); } if (module_exists('project_release') && !empty($issue->rid) && $release = node_load($issue->rid)) { $values['project_issue_version'] = check_plain($release->project_release['version']); } if (!empty($issue->assigned)) { $account = user_load($issue->assigned); $values['project_issue_assigned'] = check_plain($account->name); } $values['project_issue_category'] = project_issue_category($issue->category, FALSE); $values['project_issue_component'] = check_plain($issue->component); $values['project_issue_priority'] = project_issue_priority($issue->priority); $values['project_issue_status'] = check_plain(project_issue_state($issue->sid)); } return $values; } } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { - $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; - $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; + if (isset($result->project_issues_sid)) { + $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; + } + if (isset($result->project_issues_priority)) { + $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; + } } $variables['class'] .= " project-issue"; } } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( 'info' => t('Issue cockpit'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, ); return $form; } elseif ($op == 'save' && $delta == 'issue_cockpit') { variable_set('project_issue_cockpit_categories', $edit['project_issue_cockpit_categories']); // Invalidate the cache for this block since the categories might change. cache_clear_all('project_issue_cockpit_block:', 'cache', TRUE); } elseif ($op == 'view' && ($node = project_get_project_from_menu()) && !empty($node->project_issue['issues']) && node_access('view', $node)) { $cid = 'project_issue_cockpit_block:'. $node->nid; if (($cache = cache_get($cid))) { $block = $cache->data; } else { module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); $block = array( 'subject' => t('Issues for @project', array('@project' => $node->title)), 'content' => theme('project_issue_issue_cockpit', $node), ); cache_set($cid, $block); } return $block; } } /** * Implemenation of hook_project_page_link_alter(). * * Add project_issue-specific links to the array of project links. */ function project_issue_project_page_link_alter(&$links, $node) { // TODO: Assumes "patch" issue status values (http://drupal.org/node/27865). // Prepend a link to the development section to view pending patches. if (!empty($node->project['uri'])) { $patches['pending_patches'] = l(t('View pending patches'), 'project/issues/search/'. $node->project['uri'], array('query' => 'status[]=8&status[]=13&status[]=14')); $links['development']['links'] = $patches + $links['development']['links']; } }
Br3nda/drupal-module-project_issue
68c0872cca3218daf3a7ac17bf0682a8196bea76
#880820 by dww: Added a 'Maintain issues' per-project permission (#69556).
diff --git a/issue.inc b/issue.inc index cf21e91..845d6e4 100644 --- a/issue.inc +++ b/issue.inc @@ -1,398 +1,410 @@ <?php -// $Id: issue.inc,v 1.355 2010/04/24 01:58:18 dww Exp $ +// $Id: issue.inc,v 1.356 2010/08/19 16:31:28 dww Exp $ /** * JS callback method to return updated elements on the issue form. * This function is called when someone changes the "Project" selector. */ function project_issue_update_project() { $form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); // Rebuild the form and cache it again. $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); // These used to be path arguments. Now they arrive via form element. $issue_nid = $form['nid']['#value']; $pid = $form_state['values']['project_info']['pid']; $rid = isset($form_state['values']['project_info']['rid']) ? $form_state['values']['project_info']['rid'] : 0; $cid = $form_state['values']['cid']; $assigned_uid = $form_state['values']['project_info']['assigned']; $project_info = $form['original_issue']['project_info']; // Only generate release stuff if the project_release module is enabled. if (module_exists('project_release')) { $project->nid = $pid; if ($releases = project_release_get_releases($project, 0)) { $old_version = db_result(db_query("SELECT version FROM {project_release_nodes} WHERE nid = %d", $rid)); $releases = array(t('<none>')) + $releases; // Since the value of releases is by nid, try to match release // based on the label instead. $default = 0; foreach ($releases as $key => $label) { if ($old_version == $label) { $default = $key; } } // Element is tree'd here to match the original form layout. $project_info['#tree'] = TRUE; $project_info['rid']['#options'] = $releases; $project_info['rid']['#disabled'] = FALSE; if (!empty($default)) { $project_info['rid']['#value'] = $default; $project_info['rid']['#default_value'] = $default; } } else { $project_info['rid']['#disabled'] = TRUE; $project_info['rid']['#options'] = array(); } } // Assigned. if (is_numeric($issue_nid)) { $issue = node_load(array('nid' => $issue_nid, 'type' => 'project_issue')); } else { // @TODO: This case should not ever be hit until // http://drupal.org/node/197281 lands. $issue = new stdClass; } $issue->project_issue['pid'] = $pid; $assigned_choices = project_issue_assigned_choices($issue); $project_info['assigned']['#default_value'] = $assigned_uid; $project_info['assigned']['#options'] = $assigned_choices; // Components. $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $pid)); $components = array(); if ($project->components) { $components = array(t('<none>')); foreach (unserialize($project->components) as $component) { $component = check_plain($component); $components[$component] = $component; } } $project_info['component']['#default_value'] = $cid; $project_info['component']['#options'] = $components; // Build the HTML output for the component select. $output = theme('status_messages') . drupal_render($project_info); drupal_json(array('status' => TRUE, 'data' => $output)); exit; } /** * Build an array of users to whom an issue may be assigned. * * @param $issue * The fully loaded issue node object. * @return * A keyed array in the form uid => name containing users * to whom an issue may be assigned. */ function project_issue_assigned_choices($issue) { // Setup the array of choices for who the issue is assigned to. $assigned = array(); foreach (module_implements('project_issue_assignees') as $module) { $function = "{$module}_project_issue_assignees"; $function($assigned, $issue); } natcasesort($assigned); $assigned = array(0 => empty($issue->project_issue['assigned']) ? t('Unassigned') : t('Unassign')) + $assigned; return $assigned; } /** * Implementation of hook_project_issue_assignees(). * * This hook is used to modify the list of 'Assigned' users when creating or * commenting on an issue. * * @param $assigned * An array of key => value pairs in the format of uid => name that represents * the list of users that the issue may be assigned to. This parameter * is passed by reference so the hook may make changes, such as adding or * removing elements. * @param $node * The node object for the issue. */ function project_issue_project_issue_assignees(&$assigned, $node) { global $user; if ($user->uid) { if (isset($node->project_issue['assigned']) && $user->uid != $node->project_issue['assigned']) { // Assigned to someone else, add the currently assigned user. $account = user_load(array('uid' => $node->project_issue['assigned'])); $assigned[$node->project_issue['assigned']] = $account->name; } // Always let the person replying assign it to themselves. $assigned[$user->uid] = $user->name; + + // See if the current user is an issue maintainer for the current project. + $project = node_load($node->project_issue['pid']); + $maintainers = $project->project['maintainers']; + if (!empty($maintainers[$user->uid]['permissions']['maintain project issues'])) { + foreach ($maintainers as $uid => $maintainer) { + if (!empty($maintainer['permissions']['maintain project issues'])) { + $assigned[$uid] = $maintainer['name']; + } + } + } } if (user_access('assign and be assigned project issues')) { // All users are included if either anon or auth user has the perm. if (db_result(db_query("SELECT rid FROM {permission} WHERE perm LIKE '%%%s%%' AND rid IN(%d, %d)", 'assign and be assigned project issues', DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $result = db_query("SELECT uid, name FROM {users}"); } else { $result = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {role} r ON ur.rid = r.rid INNER JOIN {permission} p ON p.rid = r.rid WHERE p.perm LIKE '%%%s%%'", 'assign and be assigned project issues'); } while ($assignee = db_fetch_object($result)) { $assigned[$assignee->uid] = $assignee->name; } } + } // Support stuff /** * Return information about project issue state values. * * @param $sid * Integer state id to return information about, or 0 for all states. * @param $restrict * Boolean to determine if states should be restricted based on the * permissions of the current user or $account if that parameter * is provided. * @param $is_author * Boolean that indicates if the current user is the author of the * issue, which can potentially grant a wider selection of states. * @param $current_sid * The current integer state id for the issue. * @param $defaults * Boolean to request the states used for default issue queries. * @param $account * Account of a user to pass to user_access() for access checking. * This parameter will have no effect unless $restrict is also * set to TRUE. * * @return * An array of states (sid as key, name as value) that match the * given filters, or the name of the requested state. * NOTE: The state name returned is raw text, and should be filtered via * check_plain() or filter_xss() before being printed as HTML output. */ function project_issue_state($sid = 0, $restrict = false, $is_author = false, $current_sid = 0, $defaults = false, $account = NULL) { static $options; if (!$options) { $result = db_query('SELECT * FROM {project_issue_state} ORDER BY weight'); while ($state = db_fetch_object($result)) { $options[] = $state; } } foreach($options as $state) { if ($restrict) { // Check if user has access, // or if status is default status and therefore available to all, // or if user is original issue author and author has access, // or if the issue is already in a state, even if the user doesn't have // access to that state themselves. if (user_access('set issue status '. str_replace("'", "", $state->name), $account) || user_access('administer projects', $account) || ($state->sid == variable_get('project_issue_default_state', 1)) || ($state->author_has && $is_author) || ($state->sid == $current_sid) ) { $states[$state->sid] = $state->name; } } else if ($defaults) { if ($state->default_query) { $states[$state->sid] = $state->name; } } else { $states[$state->sid] = $state->name; } } return $sid ? $states[$sid] : $states; } /** * Return an array of state ids that should be used for default queries. */ function project_issue_default_states() { static $defaults; if (empty($defaults)) { $states = project_issue_state(0, false, false, 0, true); $defaults = !empty($states) ? array_keys($states) : array(1, 2, 4); } return $defaults; } /** * Return all available issue priorities, sorted by weight. * * @return * An array of priorities keyed by id. */ function project_issue_priorities() { static $priorities; if (!isset($priorities)) { $result = db_query('SELECT priority, name FROM {project_issue_priority} ORDER BY weight'); while ($object = db_fetch_object($result)) { $priorities[$object->priority] = $object->name; } } return $priorities; } /** * Return the name of a priority for a given id. * * @param $priority * The id of the priority. * @return * The name of the priority. */ function project_issue_priority($priority) { $priorities = project_issue_priorities(); if ($priority && array_key_exists($priority, $priorities)) { return $priorities[$priority]; } else { return t('[deleted priority]'); } } function project_issue_category($category = 0, $plural = 1) { if ($plural) { $categories = array('bug' => t('bug reports'), 'task' => t('tasks'), 'feature' => t('feature requests'), 'support' => t('support requests')); } else { $categories = array('bug' => t('bug report'), 'task' => t('task'), 'feature' => t('feature request'), 'support' => t('support request')); } return $category ? $categories[$category] : $categories; } function project_issue_count($pid) { $state = array(); $result = db_query('SELECT p.sid, count(p.sid) AS count FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid WHERE n.status = 1 AND p.pid = %d GROUP BY p.sid', $pid); while ($data = db_fetch_object($result)) { $state[$data->sid] = $data->count; } return $state; } /** * Return the HTML to use for the links at the top of issue query pages. * * @param $links * Array of links, indexed by the action ('create', 'search', etc). * * @see project_issue_query_result() * @see theme_links() */ function theme_project_issue_query_result_links($links) { return theme('links', $links); } /** * Provide an array of project issue summary fields. * @param $context * The context in which the fields will be displayed. * 'web' for project_issue node and comment summary tables. * 'email' for project_issue notification e-mail messages. */ function project_issue_field_labels($context) { if ($context == 'web') { $labels = array('title' => t('Title')); } else { $labels = array(); } $labels += array( 'pid' => t('Project'), 'rid' => t('Version'), 'component' => t('Component'), 'category' => t('Category'), 'priority' => t('Priority'), 'assigned' => t('Assigned to'), 'sid' => t('Status'), ); if ($context == 'email') { $labels += array( 'name' => t('Reported by'), 'updator' => t('Updated by'), ); } return $labels; } /** * Provide the text displayed to a user for a specific metadata field. * * @param $field * Name of the field. * @param $value * Value of the field. * * @return * Text to display to user. NOTE: This is unfiltered text! If this output is * being sent over the web, you must use check_plain(). */ function project_issue_change_summary($field, $value) { switch ($field) { case 'pid': $project = node_load(array('nid' => $value, 'type' => 'project_project')); return $project->title; case 'category': return $value ? project_issue_category($value, 0) : t('<none>'); case 'priority': return $value ? project_issue_priority($value) : t('<none>'); case 'rid': if ($value) { $release->nid = $value; if (module_exists('project_release')) { $release = project_release_load($release); } else { $release->project_release['version'] = t('Unknown'); } return $release->project_release['version']; } return t('<none>'); case 'assigned': $user = user_load(array('uid' => $value)); return (int) $value === 0 ? variable_get('anonymous', t('Anonymous')) : $user->name; case 'sid': return $value ? project_issue_state($value) : t('<none>'); default: return $value; } } function theme_project_issue_create_forbidden($uri = '') { global $user; if ($user->uid) { return ''; } // We cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages. $destination = "destination=". drupal_urlencode("node/add/project-issue/$uri"); if (variable_get('user_register', 1)) { return t('<a href="@login">Login</a> or <a href="@register">register</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination)))); } else { return t('<a href="@login">Login</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)))); } } diff --git a/project_issue.install b/project_issue.install index 3b01790..f3ee9e6 100644 --- a/project_issue.install +++ b/project_issue.install @@ -1,553 +1,629 @@ <?php -// $Id: project_issue.install,v 1.67 2010/07/19 19:00:34 thehunmonkgroup Exp $ +// $Id: project_issue.install,v 1.68 2010/08/19 16:31:29 dww Exp $ /** * Implementation of hook_schema(). */ function project_issue_schema() { $schema['project_issue_projects'] = array( 'description' => 'Table containing per-project issue-related settings.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {project_projects}.nid of the project.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'issues' => array( 'description' => 'Boolean value indicating whether or not issue-tracking is enabled for this project.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'components' => array( 'description' => 'A serialized array defining the components for this project.', 'type' => 'text', 'not null' => FALSE, ), 'default_component' => array( 'description' => 'The default component for new issues of this project, or an empty string if the user needs to select a component.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'help' => array( 'description' => 'Submission guidelines for issues added to this project.', 'type' => 'text', 'not null' => FALSE, ), 'mail_digest' => array( 'description' => 'E-mail address for the weekly critical issues report.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy' => array( 'description' => 'E-mail address to send a copy of all issues to.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter' => array( 'description' => 'A serialized array containing the types of issues to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter_state' => array( 'description' => 'A serialized array containing the statuses to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_reminder' => array( 'description' => 'Boolean indicating whether or not users with open issues should receive a monthly reminder.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('nid'), ); $schema['project_issues'] = array( 'description' => 'The base table for issues.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {node}.nid of this project_issue node.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'category' => array( 'description' => 'Category of the issue.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'component' => array( 'description' => 'Component of the issue as defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => 'Current {project_issue_priority}.priority of this issue.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'priority_weight' => array( 'description' => 'The denormalized weight from {project_issue_priority}.weight.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) for this issue (only used in conjunction with the project_release module).', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue is currently assigned.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'Current {project_issue_state}.sid of this issue.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'original_issue_data' => array( 'description' => 'A serialized object containing the original metadata values that were used when this issue was created.', 'type' => 'text', 'not null' => TRUE, ), 'last_comment_id' => array( 'description' => '{comments}.cid of the most recent comment added to the issue. 0 if no comment has been added yet.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'db_lock' => array( 'description' => 'Row-lock indicator to prevent race conditions when determining sequential comment number (http://drupal.org/node/180866).', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_issues_pid' => array('pid'), 'project_issues_sid' => array('sid'), 'project_issues_nid_assigned' => array('nid', 'assigned'), 'project_issues_priority_weight' => array('priority_weight'), ), 'primary key' => array('nid'), ); $schema['project_issue_comments'] = array( 'description' => 'The base table for comments added to issues.', 'fields' => array( 'nid' => array( 'description' => 'References {project_issues}.nid, the issue to which this comment was added.', 'type' => 'int', 'not null' => FALSE, ), 'cid' => array( 'description' => 'Primary Key: The {comments}.cid for this comment.', 'type' => 'int', 'not null' => FALSE, ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) after this comment was made (only used in conjunction with the project_release module).', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'component' => array( 'description' => 'Component of the issue after this comment was made. Components are defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'category' => array( 'description' => 'Category of this issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => 'The {project_issue_priority}.priority of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue was assigned after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'The {project_issue_state}.sid of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs after this comment was made.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'title' => array( 'description' => 'The title of the issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, ), 'timestamp' => array( 'description' => 'Timestamp for this comment.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, ), 'comment_number' => array( 'description' => 'The sequential number for this comment in the issue.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('cid'), 'indexes' => array( 'nid_timestamp' => array('nid', 'timestamp'), 'comment_number' => array('comment_number'), ), ); $schema['project_issue_priority'] = array( 'description' => 'The available options for the priority values for issues.', 'fields' => array( 'priority' => array( 'description' => 'Primary Key: Unique id for this priority.', 'type' => 'serial', 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this priority.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this priority, used when ordering issues by priority. Denormalized into {project_issues}.priority_weight.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('priority'), ); $schema['project_subscriptions'] = array( 'description' => 'Table keeping track of per-user project_issue subscriptions.', 'fields' => array( 'nid' => array( 'description' => '{project_projects}.nid of the project to which the user is subscribed.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'uid' => array( 'description' => 'The {users}.uid for this subscriber.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'level' => array( 'description' => 'The type of subscription for the project. Possible values are: 0 = not subscribed, 1 = subscribed to own issues or 2 = subscribed to all issues.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_subscriptions_nid_uid_level' => array('nid', 'uid', 'level'), ), ); $schema['project_issue_state'] = array( 'description' => 'Table that holds all possible values for issue statuses.', 'fields' => array( 'sid' => array( 'description' => 'Primary Key: Unique id for this status.', 'type' => 'serial', 'unsigned' => 1, 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this status.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this status, used when ordering statuses', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'author_has' => array( 'description' => 'Boolean indicating whether or not the author of an issue may use this issue status in that issue, regardless of the permissions controlling site-wide use of this status.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'default_query' => array( 'description' => 'Boolean indicating whether or not issues with this status are included in default queries.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('sid'), ); + $schema['project_issue_project_maintainer'] = array( + 'description' => t('Users who have various per-project maintainer permissions.'), + 'fields' => array( + 'nid' => array( + 'description' => t('Foreign key: {project_projects}.nid of the project.'), + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0, + ), + 'uid' => array( + 'description' => t('Foreign key: {users}.uid of a user with any project maintainer permissions.'), + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0, + ), + 'maintain_issues' => array( + 'description' => t('Can this user maintain issues for the given project.'), + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0, + ), + ), + 'primary key' => array('nid', 'uid'), + ); return $schema; } /** * Implementation of hook_install(). */ function project_issue_install() { // We need to check this before we try to create the table, so that // if it already exists, we don't attempt to insert our own values. $project_issue_state_existed = db_table_exists('project_issue_state'); // Create tables. drupal_install_schema('project_issue'); if (!$project_issue_state_existed) { // sid, name, weight, author-can-set, in-default-queries project_issue_init_state(1, 'active', -13, 0, 1); project_issue_init_state(2, 'fixed', 1, 0, 1); project_issue_init_state(3, 'duplicate', 4, 0, 0); project_issue_init_state(4, 'postponed', 6, 0, 1); project_issue_init_state(5, "won't fix", 9, 0, 0); project_issue_init_state(6, 'by design', 11, 0, 0); project_issue_init_state(7, 'closed', 13, 1, 0); project_issue_init_state(8, 'needs review', -8, 0, 0); project_issue_init_state(13, 'needs work', -6, 0, 0); project_issue_init_state(14, 'ready to commit', -2, 0, 0); // Since we're hacking in auto-increment values here, // update the sequence value for Postgres -- ugly but necessary for now. if ($GLOBALS['db_type'] == 'pgsql') { db_query("SELECT setval('project_issue_state_sid_seq', 14)"); } } db_query("UPDATE {system} SET weight = 2 WHERE name = 'project_issue'"); // Set up future followups to be read/write. if (module_exists('comment')) { variable_set('comment_project_issue', COMMENT_NODE_READ_WRITE); } // Enable file attachments for followups. variable_set('comment_upload_project_issue', 1); // Enable file attachments for issues. variable_set('upload_project_issue', 1); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (1, 'critical', 1)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (2, 'normal', 2)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (3, 'minor', 3)"); } /** * Implementation of hook_uninstall(). */ function project_issue_uninstall() { // Remove tables. drupal_uninstall_schema('project_issue'); $variables = array( 'project_issue_default_state', 'project_directory_issues', 'project_reply_to', 'project_issue_digest_last', 'project_issue_cockpit_categories', 'project_issue_digest_interval', 'project_issue_reminder_last', 'project_issue_reminder_interval', 'project_issue_show_comment_signatures', 'project_issue_site_help', 'project_issue_invalid_releases', 'project_issue_followup_user', 'project_issue_hook_cron', ); foreach ($variables as $variable) { variable_del($variable); } } /** * Implementation of hook_enable(). */ function project_issue_enable() { project_issue_add_missing_projects(); } /** * Initialize a given issue state in the database. */ function project_issue_init_state($sid, $name, $weight, $author, $query) { db_query("INSERT INTO {project_issue_state} (sid, name, weight, author_has, default_query) VALUES (%d, '%s', %d, %d, %d)", $sid, $name, $weight, $author, $query); } /** * Check for existing project nodes that do not have an entry in the * {project_issue_projects} table, and add them. */ function project_issue_add_missing_projects() { $projects = db_query("SELECT n.nid, pip.nid AS pip_nid FROM {node} n LEFT JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.type = 'project_project' AND pip.nid IS NULL"); while ($project = db_fetch_object($projects)) { db_query('INSERT INTO {project_issue_projects} (nid) VALUES (%d)', $project->nid); } } /** * Remove stale setting that's now provided by views. */ function project_issue_update_6000() { variable_del('project_issues_per_page'); return array(); } /** * Add the 'default_component' field to {project_issue_projects}. */ function project_issue_update_6001() { $ret = array(); db_add_field($ret, 'project_issue_projects', 'default_component', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '')); return $ret; } /** * Make {project_issue_comments}.cid the primary key for that table. */ function project_issue_update_6002() { $ret = array(); db_add_primary_key($ret, 'project_issue_comments', array('cid')); if (empty($ret[0]['success'])) { return array(array('success' => TRUE, 'query' => '<strong>' . t("It is safe to ignore warnings about 'Multiple primary key defined'.") . '</strong>')); } return $ret; } /** * Add table for project_issue_priority, and insert default values. */ function project_issue_update_6003() { $ret = array(); $table = array( 'description' => 'The issue priorities.', 'fields' => array( 'priority' => array( 'description' => 'Primary Key: Unique id for this priority.', 'type' => 'serial', 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this priority.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this priority, used when ordering issues by priority. Denormalized into {project_issues}.priority_weight.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('priority'), ); db_create_table($ret, 'project_issue_priority', $table); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (1, 'critical', 1)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (2, 'normal', 2)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (3, 'minor', 3)"); db_add_field($ret, 'project_issues', 'priority_weight', array('type' => 'int', 'not null' => TRUE, 'default' => '0', 'size' => 'tiny')); return $ret; } /** * Update {project_issues} with denormalized priority weight. */ function project_issue_update_6004(&$sandbox) { $ret = array(); // Reconstruct a batch context. $context = array('sandbox' => &$sandbox); // Load the include. require_once drupal_get_path('module', 'project_issue') .'/includes/admin.batch_confirm.inc'; // Call the batch upgrade which will set its variables in the sandbox. _project_issue_batch_update('UPDATE {project_issues} SET priority_weight = priority WHERE nid BETWEEN %d AND %d', array(), $context); // Pass back progress. $ret['#finished'] = $context['finished']; return $ret; } /** * Add an index to {project_issues}.priority_weight. */ function project_issue_update_6005() { $ret = array(); db_add_index($ret, 'project_issues', 'project_issues_priority_weight', array('priority_weight')); return $ret; } + +/** + * Add the {project_issue_project_maintainer} table. + */ +function project_issue_update_6006() { + $ret = array(); + + $table = array( + 'description' => t('Users who have various per-project maintainer permissions.'), + 'fields' => array( + 'nid' => array( + 'description' => t('Foreign key: {project_projects}.nid of the project.'), + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0, + ), + 'uid' => array( + 'description' => t('Foreign key: {users}.uid of a user with any project maintainer permissions.'), + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0, + ), + 'maintain_issues' => array( + 'description' => t('Can this user maintain issues for the given project.'), + 'type' => 'int', + 'unsigned' => TRUE, + 'not null' => TRUE, + 'default' => 0, + ), + ), + 'primary key' => array('nid', 'uid'), + ); + db_create_table($ret, 'project_issue_project_maintainer', $table); + + // Initially populate the table so that every project owner has full + // powers on their own projects. + $ret[] = update_sql("INSERT INTO {project_issue_project_maintainer} (nid, uid, maintain_issues) SELECT nid, uid, 1 FROM {node} WHERE type = 'project_project'"); + + // If CVS module is enabled, also populate the table from the + // {cvs_project_maintainers} table so that anyone with CVS access + // who is not the project owner can maintain issues. + if (module_exists('cvs')) { + $ret[] = update_sql("INSERT INTO {project_issue_project_maintainer} (nid, uid, maintain_issues) SELECT cpm.nid, cpm.uid, 1 FROM {cvs_project_maintainers} cpm INNER JOIN {node} n ON cpm.nid = n.nid WHERE cpm.uid != n.uid"); + } + + return $ret; +} diff --git a/project_issue.module b/project_issue.module index a1f42b9..a9b6123 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,1062 +1,1104 @@ <?php -// $Id: project_issue.module,v 1.180 2010/04/24 01:58:18 dww Exp $ +// $Id: project_issue.module,v 1.181 2010/08/19 16:31:29 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administrative pages $items['admin/project/project-issue-priority'] = array( 'title' => 'Project issue priority options', 'description' => 'Configure what issue priorities should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_priority_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.issue_priority.inc', ); $items['admin/project/project-issue-priority/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_priority_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_priority.inc' ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_admin_priority_form' => array( 'file' => 'includes/admin.issue_priority.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } +/** + * Implement hook_project_permission_info() + */ +function project_issue_project_permission_info() { + return array( + 'maintain issues' => array( + 'title' => t('Maintain issues'), + 'description' => t('Allows a user to assign issues to other issue maintainers for this project.'), + ), + ); +} + +/** + * Implement hook_project_maintainer_save() + */ +function project_issue_project_maintainer_save($nid, $uid, $permissions = array()) { + db_query("UPDATE {project_issue_project_maintainer} SET maintain_issues = %d WHERE nid = %d AND uid = %d", !empty($permissions['maintain issues']), $nid, $uid); + if (!db_affected_rows()) { + db_query("INSERT INTO {project_issue_project_maintainer} (nid, uid, maintain_issues) VALUES (%d, %d, %d)", $nid, $uid, !empty($permissions['maintain issues'])); + } +} + +/** + * Implement hook_project_maintainer_remove() + */ +function project_issue_project_maintainer_remove($nid, $uid) { + db_query("DELETE FROM {project_issue_project_maintainer} WHERE nid = %d and uid = %d", $nid, $uid); +} + +/** + * Implement hook_project_maintainer_project_load(). + */ +function project_issue_project_maintainer_project_load($nid, &$maintainers) { + $query = db_query('SELECT u.uid, u.name, pipm.maintain_issues FROM {project_issue_project_maintainer} pipm INNER JOIN {users} u ON pipm.uid = u.uid WHERE pipm.nid = %d', $nid); + while ($maintainer = db_fetch_object($query)) { + if (empty($maintainers[$maintainer->uid])) { + $maintainers[$maintainer->uid]['name'] = $maintainer->name; + } + $maintainers[$maintainer->uid]['permissions']['maintain issues'] = $maintainer->maintain_issues; + } +} + /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = !empty($changes['uid']) ? $changes['uid'] : $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': module_load_include('inc', 'project_issue', 'includes/project_node'); project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implementation of hook_mail(). (stub function) */ function project_issue_mail($key, &$message, $params) { module_load_include('inc', 'project_issue', 'includes/mail'); return _project_issue_mail($key, $message, $params); } /** * Implementation of hook_mailhandler(). (stub function) */ function project_issue_mailhandler($node, $result, $i, $header, $mailbox) { module_load_include('inc', 'project_issue', 'includes/mail'); return _project_issue_mailhandler($node, $result, $i, $header, $mailbox); } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implement hook_delete() for project issue nodes. */ function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } /** * Implement hook_form() for project issue nodes. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_form($node, $form_state, $include_metadata_fields); } /** * Implement hook_validate() for project issue nodes. */ function project_issue_validate($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_validate($node); } /** * Implement hook_insert() for project issue nodes. */ function project_issue_insert($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_insert($node); } /** * Implement hook_view() for project issue nodes. */ function project_issue_view($node, $teaser = FALSE, $page = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_view'); return _project_issue_view($node, $teaser, $page); } /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { module_load_include('inc', 'project_issue', 'includes/mail'); foreach ($nids as $nid) { project_issue_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]);
Br3nda/drupal-module-project_issue
232f276e9536ca89d62c301a799ead4f3e81f421
#175555 by mikey_p: Add custom Priority Levels. bug fixes for the batch update function. add an index for priority_weight.
diff --git a/includes/admin.batch_confirm.inc b/includes/admin.batch_confirm.inc index 56d2e52..a810d31 100644 --- a/includes/admin.batch_confirm.inc +++ b/includes/admin.batch_confirm.inc @@ -1,66 +1,55 @@ <?php -// $Id: admin.batch_confirm.inc,v 1.1 2010/04/24 01:58:18 dww Exp $ +// $Id: admin.batch_confirm.inc,v 1.2 2010/07/19 19:00:34 thehunmonkgroup Exp $ /** * @file * Batch operations for updating denormalized issue priority weight and status. */ /** * Run a SQL query in batch for each row in the {project_issues} table. * * This function will find the range of all rows in the {project_issues} table - * and run a query against that table incerementally, 100 rows at a time. This + * and run a query against that table incerementally, 500 rows at a time. This * function is intended to be used with batch_set(). * * @param $sql * A SQL query intended to be run for each row in the {project_issues} table. * Usually an update query, it is recommended to include 'BETWEEN %d AND %d' * to prevent timeouts. * @param $base_arguments * An array of base arguments to pass to the query. The first and last nid of * the current range are appended to the end of this query, for specifying a * range with BETWEEN. * @param $context * An array containing information about batch progress. $context['sandbox'] * contains the following keys which will be populated after this function * has been called: - * 'min' The minimum value, or starting point. * 'max' The maximum value, or end point. * 'current' The nid of the last row that has been updated. - * 'finished' Will contain a percentage of total rows processed, and will - * be set to 1 when all rows have been processed. */ function _project_issue_batch_update($sql, $base_arguments, &$context = array()) { - $last_nid = 0; - $first_nid = 0; - if (!isset($context['sandbox']['min'])) { - // Avoid COUNT(*) like hell. + if (!isset($context['sandbox']['current'])) { $context['sandbox']['max'] = db_result(db_query('SELECT MAX(nid) FROM {project_issues}')); - // We will use > so use - 1 when choosing the smallest nid. - $context['sandbox']['min'] = db_result(db_query('SELECT MIN(nid) - 1 FROM {project_issues}')); - $context['sandbox']['current'] = $context['sandbox']['min']; + $context['sandbox']['current'] = 0; } + + $limit = 500; + + // Add range of rows to process to query arguments. $arguments = $base_arguments; - // MySQL does not support LIMIT & IN/ALL/ANY/SOME subquery so we do the hard - // work ourselves: find 100 nids and record the first and the last. - $results = db_query_range('SELECT nid FROM {project_issues} WHERE nid > %d ORDER BY nid ASC', $context['sandbox']['current'], 0, 100); - while ($node = db_fetch_object($results)) { - if (!isset($first_nid)) { - $first_nid = $node->nid; - } - $last_nid = $node->nid; - } - $arguments[] = $first_nid; + $last_nid = $context['sandbox']['current'] + $limit; + $arguments[] = $context['sandbox']['current']; $arguments[] = $last_nid; + db_query($sql, $arguments); - // Note that we do not count exactly as there can be holes. That's still - // better than running COUNT() on large datasets. + + // Check to see if finished, report progress and update $context['sandbox']['current']. if ($last_nid < $context['sandbox']['max']) { - $context['finished'] = ($last_nid - $context['sandbox']['min']) / ($context['sandbox']['max'] - $context['sandbox']['min']); + $context['finished'] = $last_nid / $context['sandbox']['max']; $context['sandbox']['current'] = $last_nid; } else { $context['finished'] = 1; } } diff --git a/project_issue.install b/project_issue.install index 1956d68..3b01790 100644 --- a/project_issue.install +++ b/project_issue.install @@ -1,541 +1,553 @@ <?php -// $Id: project_issue.install,v 1.66 2010/06/07 22:46:14 dww Exp $ +// $Id: project_issue.install,v 1.67 2010/07/19 19:00:34 thehunmonkgroup Exp $ /** * Implementation of hook_schema(). */ function project_issue_schema() { $schema['project_issue_projects'] = array( 'description' => 'Table containing per-project issue-related settings.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {project_projects}.nid of the project.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'issues' => array( 'description' => 'Boolean value indicating whether or not issue-tracking is enabled for this project.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'components' => array( 'description' => 'A serialized array defining the components for this project.', 'type' => 'text', 'not null' => FALSE, ), 'default_component' => array( 'description' => 'The default component for new issues of this project, or an empty string if the user needs to select a component.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'help' => array( 'description' => 'Submission guidelines for issues added to this project.', 'type' => 'text', 'not null' => FALSE, ), 'mail_digest' => array( 'description' => 'E-mail address for the weekly critical issues report.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy' => array( 'description' => 'E-mail address to send a copy of all issues to.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter' => array( 'description' => 'A serialized array containing the types of issues to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter_state' => array( 'description' => 'A serialized array containing the statuses to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_reminder' => array( 'description' => 'Boolean indicating whether or not users with open issues should receive a monthly reminder.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('nid'), ); $schema['project_issues'] = array( 'description' => 'The base table for issues.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {node}.nid of this project_issue node.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'category' => array( 'description' => 'Category of the issue.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'component' => array( 'description' => 'Component of the issue as defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => 'Current {project_issue_priority}.priority of this issue.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'priority_weight' => array( 'description' => 'The denormalized weight from {project_issue_priority}.weight.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) for this issue (only used in conjunction with the project_release module).', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue is currently assigned.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'Current {project_issue_state}.sid of this issue.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'original_issue_data' => array( 'description' => 'A serialized object containing the original metadata values that were used when this issue was created.', 'type' => 'text', 'not null' => TRUE, ), 'last_comment_id' => array( 'description' => '{comments}.cid of the most recent comment added to the issue. 0 if no comment has been added yet.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'db_lock' => array( 'description' => 'Row-lock indicator to prevent race conditions when determining sequential comment number (http://drupal.org/node/180866).', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_issues_pid' => array('pid'), 'project_issues_sid' => array('sid'), 'project_issues_nid_assigned' => array('nid', 'assigned'), + 'project_issues_priority_weight' => array('priority_weight'), ), 'primary key' => array('nid'), ); $schema['project_issue_comments'] = array( 'description' => 'The base table for comments added to issues.', 'fields' => array( 'nid' => array( 'description' => 'References {project_issues}.nid, the issue to which this comment was added.', 'type' => 'int', 'not null' => FALSE, ), 'cid' => array( 'description' => 'Primary Key: The {comments}.cid for this comment.', 'type' => 'int', 'not null' => FALSE, ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) after this comment was made (only used in conjunction with the project_release module).', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'component' => array( 'description' => 'Component of the issue after this comment was made. Components are defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'category' => array( 'description' => 'Category of this issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => 'The {project_issue_priority}.priority of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue was assigned after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'The {project_issue_state}.sid of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs after this comment was made.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'title' => array( 'description' => 'The title of the issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, ), 'timestamp' => array( 'description' => 'Timestamp for this comment.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, ), 'comment_number' => array( 'description' => 'The sequential number for this comment in the issue.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('cid'), 'indexes' => array( 'nid_timestamp' => array('nid', 'timestamp'), 'comment_number' => array('comment_number'), ), ); $schema['project_issue_priority'] = array( 'description' => 'The available options for the priority values for issues.', 'fields' => array( 'priority' => array( 'description' => 'Primary Key: Unique id for this priority.', 'type' => 'serial', 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this priority.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this priority, used when ordering issues by priority. Denormalized into {project_issues}.priority_weight.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('priority'), ); $schema['project_subscriptions'] = array( 'description' => 'Table keeping track of per-user project_issue subscriptions.', 'fields' => array( 'nid' => array( 'description' => '{project_projects}.nid of the project to which the user is subscribed.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'uid' => array( 'description' => 'The {users}.uid for this subscriber.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'level' => array( 'description' => 'The type of subscription for the project. Possible values are: 0 = not subscribed, 1 = subscribed to own issues or 2 = subscribed to all issues.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_subscriptions_nid_uid_level' => array('nid', 'uid', 'level'), ), ); $schema['project_issue_state'] = array( 'description' => 'Table that holds all possible values for issue statuses.', 'fields' => array( 'sid' => array( 'description' => 'Primary Key: Unique id for this status.', 'type' => 'serial', 'unsigned' => 1, 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this status.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this status, used when ordering statuses', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'author_has' => array( 'description' => 'Boolean indicating whether or not the author of an issue may use this issue status in that issue, regardless of the permissions controlling site-wide use of this status.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'default_query' => array( 'description' => 'Boolean indicating whether or not issues with this status are included in default queries.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('sid'), ); return $schema; } /** * Implementation of hook_install(). */ function project_issue_install() { // We need to check this before we try to create the table, so that // if it already exists, we don't attempt to insert our own values. $project_issue_state_existed = db_table_exists('project_issue_state'); // Create tables. drupal_install_schema('project_issue'); if (!$project_issue_state_existed) { // sid, name, weight, author-can-set, in-default-queries project_issue_init_state(1, 'active', -13, 0, 1); project_issue_init_state(2, 'fixed', 1, 0, 1); project_issue_init_state(3, 'duplicate', 4, 0, 0); project_issue_init_state(4, 'postponed', 6, 0, 1); project_issue_init_state(5, "won't fix", 9, 0, 0); project_issue_init_state(6, 'by design', 11, 0, 0); project_issue_init_state(7, 'closed', 13, 1, 0); project_issue_init_state(8, 'needs review', -8, 0, 0); project_issue_init_state(13, 'needs work', -6, 0, 0); project_issue_init_state(14, 'ready to commit', -2, 0, 0); // Since we're hacking in auto-increment values here, // update the sequence value for Postgres -- ugly but necessary for now. if ($GLOBALS['db_type'] == 'pgsql') { db_query("SELECT setval('project_issue_state_sid_seq', 14)"); } } db_query("UPDATE {system} SET weight = 2 WHERE name = 'project_issue'"); // Set up future followups to be read/write. if (module_exists('comment')) { variable_set('comment_project_issue', COMMENT_NODE_READ_WRITE); } // Enable file attachments for followups. variable_set('comment_upload_project_issue', 1); // Enable file attachments for issues. variable_set('upload_project_issue', 1); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (1, 'critical', 1)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (2, 'normal', 2)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (3, 'minor', 3)"); } /** * Implementation of hook_uninstall(). */ function project_issue_uninstall() { // Remove tables. drupal_uninstall_schema('project_issue'); $variables = array( 'project_issue_default_state', 'project_directory_issues', 'project_reply_to', 'project_issue_digest_last', 'project_issue_cockpit_categories', 'project_issue_digest_interval', 'project_issue_reminder_last', 'project_issue_reminder_interval', 'project_issue_show_comment_signatures', 'project_issue_site_help', 'project_issue_invalid_releases', 'project_issue_followup_user', 'project_issue_hook_cron', ); foreach ($variables as $variable) { variable_del($variable); } } /** * Implementation of hook_enable(). */ function project_issue_enable() { project_issue_add_missing_projects(); } /** * Initialize a given issue state in the database. */ function project_issue_init_state($sid, $name, $weight, $author, $query) { db_query("INSERT INTO {project_issue_state} (sid, name, weight, author_has, default_query) VALUES (%d, '%s', %d, %d, %d)", $sid, $name, $weight, $author, $query); } /** * Check for existing project nodes that do not have an entry in the * {project_issue_projects} table, and add them. */ function project_issue_add_missing_projects() { $projects = db_query("SELECT n.nid, pip.nid AS pip_nid FROM {node} n LEFT JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.type = 'project_project' AND pip.nid IS NULL"); while ($project = db_fetch_object($projects)) { db_query('INSERT INTO {project_issue_projects} (nid) VALUES (%d)', $project->nid); } } /** * Remove stale setting that's now provided by views. */ function project_issue_update_6000() { variable_del('project_issues_per_page'); return array(); } /** * Add the 'default_component' field to {project_issue_projects}. */ function project_issue_update_6001() { $ret = array(); db_add_field($ret, 'project_issue_projects', 'default_component', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '')); return $ret; } /** * Make {project_issue_comments}.cid the primary key for that table. */ function project_issue_update_6002() { $ret = array(); db_add_primary_key($ret, 'project_issue_comments', array('cid')); if (empty($ret[0]['success'])) { return array(array('success' => TRUE, 'query' => '<strong>' . t("It is safe to ignore warnings about 'Multiple primary key defined'.") . '</strong>')); } return $ret; } /** * Add table for project_issue_priority, and insert default values. */ function project_issue_update_6003() { $ret = array(); $table = array( 'description' => 'The issue priorities.', 'fields' => array( 'priority' => array( 'description' => 'Primary Key: Unique id for this priority.', 'type' => 'serial', 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this priority.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this priority, used when ordering issues by priority. Denormalized into {project_issues}.priority_weight.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('priority'), ); db_create_table($ret, 'project_issue_priority', $table); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (1, 'critical', 1)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (2, 'normal', 2)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (3, 'minor', 3)"); db_add_field($ret, 'project_issues', 'priority_weight', array('type' => 'int', 'not null' => TRUE, 'default' => '0', 'size' => 'tiny')); return $ret; } /** * Update {project_issues} with denormalized priority weight. */ function project_issue_update_6004(&$sandbox) { $ret = array(); // Reconstruct a batch context. $context = array('sandbox' => &$sandbox); // Load the include. require_once drupal_get_path('module', 'project_issue') .'/includes/admin.batch_confirm.inc'; // Call the batch upgrade which will set its variables in the sandbox. _project_issue_batch_update('UPDATE {project_issues} SET priority_weight = priority WHERE nid BETWEEN %d AND %d', array(), $context); // Pass back progress. $ret['#finished'] = $context['finished']; return $ret; } + +/** + * Add an index to {project_issues}.priority_weight. + */ +function project_issue_update_6005() { + $ret = array(); + + db_add_index($ret, 'project_issues', 'project_issues_priority_weight', array('priority_weight')); + + return $ret; +}
Br3nda/drupal-module-project_issue
f2747e3e7af6465ffca05c6b67eb4828ab18ea53
#347199 by dww, AmrMostafa: Fixed bug where various project tables were not populated on projects that were created before add-ons are enabled (e.g. {project_release_projects} and {project_issue_projects}).
diff --git a/includes/project_edit_issues.inc b/includes/project_edit_issues.inc index 8672ce3..4f8f10b 100644 --- a/includes/project_edit_issues.inc +++ b/includes/project_edit_issues.inc @@ -1,292 +1,297 @@ <?php -// $Id: project_edit_issues.inc,v 1.3 2009/08/21 21:58:23 dww Exp $ +// $Id: project_edit_issues.inc,v 1.4 2010/06/07 22:46:15 dww Exp $ /** * @file * Code for the "issues" subtab to the edit tab on project nodes. */ /** * Page callback for the "issues" subtab to the edit tab on project nodes. */ function project_issue_project_edit_issues($node) { project_project_set_breadcrumb($node); drupal_set_title(check_plain($node->title)); return drupal_get_form('project_issue_project_edit_form', $node); } /** * Theme function to render the issue subtab form. */ function theme_project_issue_project_edit_form($form) { drupal_add_tabledrag('project-issue-edit-project-components-table', 'order', 'self', 'project-issue-component-weight'); $header = array( array('data' => t('Name')), array('data' => t('Weight')), array('data' => t('Operations')) ); // List the existing components. foreach (element_children($form['component']) as $key) { $rows[] = array( 'class' => 'draggable', 'data' => array( drupal_render($form['component'][$key]['name']), drupal_render($form['component'][$key]['weight']), drupal_render($form['component'][$key]['delete']), ), ); } // Add a row to add a new component. $rows[] = array( 'class' => 'draggable', 'data' => array( drupal_render($form['component_add']['name']), drupal_render($form['component_add']['weight']), NULL, ), ); $output = drupal_render($form['issue']); $output .= drupal_render($form['email']); $output .= '<h3>' . t('Issue components') . '</h3>'; $output .= '<div>' . theme('table', $header, $rows, array('id' => 'project-issue-edit-project-components-table')) . '</div>'; $output .= drupal_render($form); return $output; } /** * Form builder for the issues subtab on the edit tab for project nodes. */ function project_issue_project_edit_form(&$form_state, $node) { /* Issue properties */ $form['issue'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#collapsible' => TRUE, ); $form['issue']['issue'] = array( '#type' => 'item', '#title' => t('Issue tracker'), ); $form['issue']['issues'] = array( '#type' => 'checkbox', '#title' => t('Enable issue tracker'), '#return_value' => 1, '#default_value' => isset($node->project_issue['issues']) ? $node->project_issue['issues'] : 1, '#description' => t('Let users submit bug requests, patches, feature requests, support requests, etc.'), ); $form['issue']['help'] = array( '#type' => 'textarea', '#title' => t('Submission guidelines'), '#default_value' => isset($node->project_issue['help']) ? $node->project_issue['help'] : NULL, '#cols' => 20, '#rows' => 5, ); $weight = 0; $default_component_options[0] = t('<none> (user must select)'); $form['component']['#tree'] = TRUE; $number_components = count($node->project_issue['components']); $delta = max(20, $number_components + 10); foreach ($node->project_issue['components'] as $component) { $default_component_options[$component] = $component; $form['component'][$component]['name'] = array( '#type' => 'textfield', '#default_value' => $component, '#size' => 20, ); $form['component'][$component]['weight'] = array( '#type' => 'weight', '#default_value' => $weight, '#delta' => $delta, '#attributes' => array('class' => 'project-issue-component-weight'), ); // For the delete links, we just need the offset of the component as // currently stored in the DB or node. So, we can just use the $weight. // Using an integer offset avoids problems with urlencoding for component // names that have '/' in them. $del_link = ($component != $node->project_issue['default_component']) ? l(t('Delete'), 'node/'. $node->nid .'/edit/component/delete/'. $weight) : ''; $form['component'][$component]['delete'] = array( '#type' => 'markup', '#value' => $del_link, ); $weight++; } $form['component_add']['#tree'] = TRUE; $form['component_add']['name'] = array( '#type' => 'textfield', '#size' => 20, ); $form['component_add']['weight'] = array( '#type' => 'weight', '#default_value' => $weight, '#delta' => $delta, '#attributes' => array('class' => 'project-issue-component-weight'), ); $form['default_component'] = array( '#type' => 'select', '#title' => t('Default component for new issues'), '#options' => $default_component_options, '#default_value' => !empty($node->project_issue['default_component']) ? $node->project_issue['default_component'] : 0, ); /* E-mail options */ $form['email'] = array( '#type' => 'fieldset', '#title' => t('Issue e-mail options'), '#collapsible' => TRUE, '#collapsed' => TRUE, ); $form['email']['mail_digest'] = array( '#type' => 'textfield', '#title' => t('Weekly critical issues report'), '#default_value' => isset($node->project_issue['mail_digest']) ? $node->project_issue['mail_digest'] : NULL, '#size' => 20, '#maxlength' => 255, '#description' => t('To get a weekly digest of critical issues specify an e-mail address.'), ); $form['email']['mail_copy'] = array( '#type' => 'textfield', '#title' => t('Issues e-mail address'), '#default_value' => isset($node->project_issue['mail_copy']) ? $node->project_issue['mail_copy'] : NULL, '#size' => 20, '#maxlength' => 255, '#description' => t('If you wish to receive a copy of all the issues to a central location specify an address here. <em>Note: the copy will contain links to file attachments.</em>'), ); $options = project_issue_category(); $form['email']['categories'] = array( '#type' => 'item', '#title' => t('Categories'), '#description' => t('Which issue categories to e-mail. If none is checked all categories will be posted.'), ); $form['email']['mail_copy_filter']['#tree'] = TRUE; foreach ($options as $key => $choice) { $form['email']['mail_copy_filter'][$key] = array( '#type' => 'checkbox', '#title' => $choice, '#return_value' => $key, '#default_value' => isset($node->project_issue['mail_copy_filter'][$key]) ? $node->project_issue['mail_copy_filter'][$key] : NULL, ); } $options = project_issue_state(); $form['email']['states'] = array( '#type' => 'item', '#title' => t('States'), '#description' => t('Which issue states to e-mail. If none is checked all states will be posted.'), ); $form['email']['mail_copy_filter_state']['#tree'] = TRUE; foreach ($options as $key => $choice) { $form['email']['mail_copy_filter_state'][$key] = array( '#type' => 'checkbox', '#title' => check_plain($choice), '#return_value' => $key, '#default_value' => isset($node->project_issue['mail_copy_filter_state'][$key]) ? $node->project_issue['mail_copy_filter_state'][$key] : NULL, ); } if (user_access('administer projects')) { $form['email']['reminder'] = array( '#type' => 'item', '#title' => t('Monthly reminder'), ); $form['email']['mail_reminder'] = array( '#type' => 'checkbox', '#title' => t('Send monthly reminders to users'), '#return_value' => 1, '#default_value' => isset($node->project_issue['mail_reminder']) ? $node->project_issue['mail_reminder'] : NULL, '#description' => t('Enabling this will send a monthly reminder to users that have open issues registered.'), ); } $form['nid'] = array('#type' => 'value', '#value' => $node->nid); $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), '#weight' => 45, ); return $form; } /** * Validation handler when project admins use the issues subtab. * @see project_issue_project_edit_issues */ function project_issue_project_edit_form_validate($form, &$form_state) { if (!empty($form_state['values']['mail_digest']) && ($data = user_validate_mail($form_state['values']['mail_digest']))) { form_set_error('mail_digest', $data); } if (!empty($form_state['values']['mail_copy']) && ($data = user_validate_mail($form_state['values']['mail_copy']))) { form_set_error('mail_copy', $data); } } /** * Submit handler when project admins use the issues subtab. * @see project_issue_project_edit_issues */ function project_issue_project_edit_form_submit($form, &$form_state) { $components = array(); if (!empty($form_state['values']['component_add']['name'])) { $components[trim($form_state['values']['component_add']['name'])] = $form_state['values']['component_add']['weight']; } if (!empty($form_state['values']['component'])) { foreach ($form_state['values']['component'] as $component) { $components[trim($component['name'])] = $component['weight']; } } asort($components); $components = serialize(array_keys($components)); $default_component = !empty($form_state['values']['default_component']) ? $form_state['values']['default_component'] : ''; $mail_copy_filter = serialize($form_state['values']['mail_copy_filter']); $mail_copy_filter_state = serialize($form_state['values']['mail_copy_filter_state']); db_query("UPDATE {project_issue_projects} SET issues = %d, components = '%s',default_component = '%s', mail_digest = '%s', mail_reminder = %d, mail_copy = '%s', mail_copy_filter = '%s', mail_copy_filter_state = '%s', help = '%s' WHERE nid = %d", $form_state['values']['issues'], $components, $default_component, $form_state['values']['mail_digest'], $form_state['values']['mail_reminder'], $form_state['values']['mail_copy'], $mail_copy_filter, $mail_copy_filter_state, $form_state['values']['help'], $form_state['values']['nid']); + if (!db_affected_rows()) { + // It's possible there's no record in {project_issue_projects} if this + // particular project was created before project_issue.module was enabled. + db_query("INSERT INTO {project_issue_projects} (nid, issues, components, default_component, mail_digest, mail_reminder, mail_copy, mail_copy_filter, mail_copy_filter_state, help) VALUES (%d, %d, '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s')", $form_values['nid'], $form_values['issues'], $components, $default_component, $form_values['mail_digest'], $form_values['mail_reminder'], $form_values['mail_copy'], $mail_copy_filter, $mail_copy_filter_state, $form_values['help']); + } db_query("UPDATE {node} SET changed = %d WHERE nid = %d", time(), $form_state['values']['nid']); drupal_set_message(t('Issue settings have been saved.')); } function project_issue_component_delete_form($form_state, $project, $component_offset) { $component = $project->project_issue['components'][$component_offset]; $form['component'] = array( '#type' => 'value', '#value' => $component, ); $form['project'] = array( '#type' => 'value', '#value' => $project, ); return confirm_form( $form, t('Are you sure you want to delete the component %component?', array('%component' => $component)), 'node/' . $project->nid . '/edit/issues', t('This action cannot be undone.'), t('Delete'), t('Cancel') ); } function project_issue_component_delete_form_submit($form, &$form_state) { $project = $form_state['values']['project']; $component = $form_state['values']['component']; project_issue_delete_component($project, $component); drupal_set_message(t('Issue component %component deleted.', array('%component' => $component))); $form_state['redirect'] = 'node/' . $project->nid . '/edit/issues'; } /** * Remove a component from a given project. * * @param $project * The project to remove the component from. * @param $component * The component to remove. */ function project_issue_delete_component($project, $component) { $components = array_diff($project->project_issue['components'], array($component)); db_query("UPDATE {project_issue_projects} SET components = '%s' WHERE nid = %d", serialize($components), $project->nid); db_query("UPDATE {node} SET changed = %d WHERE nid = %d", time(), $project->nid); } diff --git a/project_issue.install b/project_issue.install index 1222180..1956d68 100644 --- a/project_issue.install +++ b/project_issue.install @@ -1,538 +1,541 @@ <?php -// $Id: project_issue.install,v 1.65 2010/04/24 01:58:18 dww Exp $ +// $Id: project_issue.install,v 1.66 2010/06/07 22:46:14 dww Exp $ /** * Implementation of hook_schema(). */ function project_issue_schema() { $schema['project_issue_projects'] = array( 'description' => 'Table containing per-project issue-related settings.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {project_projects}.nid of the project.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'issues' => array( 'description' => 'Boolean value indicating whether or not issue-tracking is enabled for this project.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'components' => array( 'description' => 'A serialized array defining the components for this project.', 'type' => 'text', 'not null' => FALSE, ), 'default_component' => array( 'description' => 'The default component for new issues of this project, or an empty string if the user needs to select a component.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'help' => array( 'description' => 'Submission guidelines for issues added to this project.', 'type' => 'text', 'not null' => FALSE, ), 'mail_digest' => array( 'description' => 'E-mail address for the weekly critical issues report.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy' => array( 'description' => 'E-mail address to send a copy of all issues to.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter' => array( 'description' => 'A serialized array containing the types of issues to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter_state' => array( 'description' => 'A serialized array containing the statuses to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_reminder' => array( 'description' => 'Boolean indicating whether or not users with open issues should receive a monthly reminder.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('nid'), ); $schema['project_issues'] = array( 'description' => 'The base table for issues.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {node}.nid of this project_issue node.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'category' => array( 'description' => 'Category of the issue.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'component' => array( 'description' => 'Component of the issue as defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => 'Current {project_issue_priority}.priority of this issue.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'priority_weight' => array( 'description' => 'The denormalized weight from {project_issue_priority}.weight.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) for this issue (only used in conjunction with the project_release module).', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue is currently assigned.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'Current {project_issue_state}.sid of this issue.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'original_issue_data' => array( 'description' => 'A serialized object containing the original metadata values that were used when this issue was created.', 'type' => 'text', 'not null' => TRUE, ), 'last_comment_id' => array( 'description' => '{comments}.cid of the most recent comment added to the issue. 0 if no comment has been added yet.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'db_lock' => array( 'description' => 'Row-lock indicator to prevent race conditions when determining sequential comment number (http://drupal.org/node/180866).', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_issues_pid' => array('pid'), 'project_issues_sid' => array('sid'), 'project_issues_nid_assigned' => array('nid', 'assigned'), ), 'primary key' => array('nid'), ); $schema['project_issue_comments'] = array( 'description' => 'The base table for comments added to issues.', 'fields' => array( 'nid' => array( 'description' => 'References {project_issues}.nid, the issue to which this comment was added.', 'type' => 'int', 'not null' => FALSE, ), 'cid' => array( 'description' => 'Primary Key: The {comments}.cid for this comment.', 'type' => 'int', 'not null' => FALSE, ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) after this comment was made (only used in conjunction with the project_release module).', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'component' => array( 'description' => 'Component of the issue after this comment was made. Components are defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'category' => array( 'description' => 'Category of this issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => 'The {project_issue_priority}.priority of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue was assigned after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'The {project_issue_state}.sid of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs after this comment was made.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'title' => array( 'description' => 'The title of the issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, ), 'timestamp' => array( 'description' => 'Timestamp for this comment.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, ), 'comment_number' => array( 'description' => 'The sequential number for this comment in the issue.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('cid'), 'indexes' => array( 'nid_timestamp' => array('nid', 'timestamp'), 'comment_number' => array('comment_number'), ), ); $schema['project_issue_priority'] = array( 'description' => 'The available options for the priority values for issues.', 'fields' => array( 'priority' => array( 'description' => 'Primary Key: Unique id for this priority.', 'type' => 'serial', 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this priority.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this priority, used when ordering issues by priority. Denormalized into {project_issues}.priority_weight.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('priority'), ); $schema['project_subscriptions'] = array( 'description' => 'Table keeping track of per-user project_issue subscriptions.', 'fields' => array( 'nid' => array( 'description' => '{project_projects}.nid of the project to which the user is subscribed.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'uid' => array( 'description' => 'The {users}.uid for this subscriber.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'level' => array( 'description' => 'The type of subscription for the project. Possible values are: 0 = not subscribed, 1 = subscribed to own issues or 2 = subscribed to all issues.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_subscriptions_nid_uid_level' => array('nid', 'uid', 'level'), ), ); $schema['project_issue_state'] = array( 'description' => 'Table that holds all possible values for issue statuses.', 'fields' => array( 'sid' => array( 'description' => 'Primary Key: Unique id for this status.', 'type' => 'serial', 'unsigned' => 1, 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this status.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this status, used when ordering statuses', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'author_has' => array( 'description' => 'Boolean indicating whether or not the author of an issue may use this issue status in that issue, regardless of the permissions controlling site-wide use of this status.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'default_query' => array( 'description' => 'Boolean indicating whether or not issues with this status are included in default queries.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('sid'), ); return $schema; } +/** + * Implementation of hook_install(). + */ function project_issue_install() { // We need to check this before we try to create the table, so that // if it already exists, we don't attempt to insert our own values. $project_issue_state_existed = db_table_exists('project_issue_state'); // Create tables. drupal_install_schema('project_issue'); if (!$project_issue_state_existed) { // sid, name, weight, author-can-set, in-default-queries project_issue_init_state(1, 'active', -13, 0, 1); project_issue_init_state(2, 'fixed', 1, 0, 1); project_issue_init_state(3, 'duplicate', 4, 0, 0); project_issue_init_state(4, 'postponed', 6, 0, 1); project_issue_init_state(5, "won't fix", 9, 0, 0); project_issue_init_state(6, 'by design', 11, 0, 0); project_issue_init_state(7, 'closed', 13, 1, 0); project_issue_init_state(8, 'needs review', -8, 0, 0); project_issue_init_state(13, 'needs work', -6, 0, 0); project_issue_init_state(14, 'ready to commit', -2, 0, 0); // Since we're hacking in auto-increment values here, // update the sequence value for Postgres -- ugly but necessary for now. if ($GLOBALS['db_type'] == 'pgsql') { db_query("SELECT setval('project_issue_state_sid_seq', 14)"); } } - project_issue_add_missing_projects(); - db_query("UPDATE {system} SET weight = 2 WHERE name = 'project_issue'"); // Set up future followups to be read/write. if (module_exists('comment')) { variable_set('comment_project_issue', COMMENT_NODE_READ_WRITE); } // Enable file attachments for followups. variable_set('comment_upload_project_issue', 1); // Enable file attachments for issues. variable_set('upload_project_issue', 1); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (1, 'critical', 1)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (2, 'normal', 2)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (3, 'minor', 3)"); } /** * Implementation of hook_uninstall(). */ function project_issue_uninstall() { // Remove tables. drupal_uninstall_schema('project_issue'); $variables = array( 'project_issue_default_state', 'project_directory_issues', 'project_reply_to', 'project_issue_digest_last', 'project_issue_cockpit_categories', 'project_issue_digest_interval', 'project_issue_reminder_last', 'project_issue_reminder_interval', 'project_issue_show_comment_signatures', 'project_issue_site_help', 'project_issue_invalid_releases', 'project_issue_followup_user', 'project_issue_hook_cron', ); foreach ($variables as $variable) { variable_del($variable); } } +/** + * Implementation of hook_enable(). + */ function project_issue_enable() { project_issue_add_missing_projects(); } /** * Initialize a given issue state in the database. */ function project_issue_init_state($sid, $name, $weight, $author, $query) { db_query("INSERT INTO {project_issue_state} (sid, name, weight, author_has, default_query) VALUES (%d, '%s', %d, %d, %d)", $sid, $name, $weight, $author, $query); } /** * Check for existing project nodes that do not have an entry in the * {project_issue_projects} table, and add them. - * */ function project_issue_add_missing_projects() { $projects = db_query("SELECT n.nid, pip.nid AS pip_nid FROM {node} n LEFT JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.type = 'project_project' AND pip.nid IS NULL"); while ($project = db_fetch_object($projects)) { db_query('INSERT INTO {project_issue_projects} (nid) VALUES (%d)', $project->nid); } } /** * Remove stale setting that's now provided by views. */ function project_issue_update_6000() { variable_del('project_issues_per_page'); return array(); } /** * Add the 'default_component' field to {project_issue_projects}. */ function project_issue_update_6001() { $ret = array(); db_add_field($ret, 'project_issue_projects', 'default_component', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '')); return $ret; } /** * Make {project_issue_comments}.cid the primary key for that table. */ function project_issue_update_6002() { $ret = array(); db_add_primary_key($ret, 'project_issue_comments', array('cid')); if (empty($ret[0]['success'])) { return array(array('success' => TRUE, 'query' => '<strong>' . t("It is safe to ignore warnings about 'Multiple primary key defined'.") . '</strong>')); } return $ret; } /** * Add table for project_issue_priority, and insert default values. */ function project_issue_update_6003() { $ret = array(); $table = array( 'description' => 'The issue priorities.', 'fields' => array( 'priority' => array( 'description' => 'Primary Key: Unique id for this priority.', 'type' => 'serial', 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this priority.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this priority, used when ordering issues by priority. Denormalized into {project_issues}.priority_weight.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('priority'), ); db_create_table($ret, 'project_issue_priority', $table); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (1, 'critical', 1)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (2, 'normal', 2)"); db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (3, 'minor', 3)"); db_add_field($ret, 'project_issues', 'priority_weight', array('type' => 'int', 'not null' => TRUE, 'default' => '0', 'size' => 'tiny')); return $ret; } /** * Update {project_issues} with denormalized priority weight. */ function project_issue_update_6004(&$sandbox) { $ret = array(); // Reconstruct a batch context. $context = array('sandbox' => &$sandbox); // Load the include. require_once drupal_get_path('module', 'project_issue') .'/includes/admin.batch_confirm.inc'; // Call the batch upgrade which will set its variables in the sandbox. _project_issue_batch_update('UPDATE {project_issues} SET priority_weight = priority WHERE nid BETWEEN %d AND %d', array(), $context); // Pass back progress. $ret['#finished'] = $context['finished']; return $ret; }
Br3nda/drupal-module-project_issue
6802c0ba85c80da8e7659be7979642109763c949
#175555 by chx, mikey_p, dww: Added ability to create custom priorities.
diff --git a/generate/project_issue_generate.inc b/generate/project_issue_generate.inc index ce6326c..ce09c3d 100644 --- a/generate/project_issue_generate.inc +++ b/generate/project_issue_generate.inc @@ -1,249 +1,249 @@ <?php -// $Id: project_issue_generate.inc,v 1.13 2009/03/21 18:50:17 thehunmonkgroup Exp $ +// $Id: project_issue_generate.inc,v 1.14 2010/04/24 01:58:18 dww Exp $ // If not in 'safe mode', increase the maximum execution time. if (!ini_get('safe_mode')) { set_time_limit(240); } /** * Generate some random project issues. * * @param $number * Number of issues to generate. */ function project_issue_generate_issues($number) { module_load_include('inc', 'devel', 'devel_generate'); module_load_include('inc', 'node', 'node.pages'); $empty_variables = array(); // After retrieving the possible values for each of these variables, we // need to check and make sure that at least one value was returned. If // not, we're likely to get fatal errors later on in this function. $projects = _project_issue_generate_get_field('projects'); if (empty($projects)) { $empty_variables[] = 'projects'; } $categories = _project_issue_generate_get_field('categories'); if (empty($categories)) { $empty_variables[] = 'categories'; } $priorities = _project_issue_generate_get_field('priorities'); if (empty($priorities)) { $empty_variables[] = 'priorities'; } $users = _project_issue_generate_get_field('users'); if (empty($users)) { $empty_variables[] = 'users'; } $loaded_users = array(); // Return now if any of the above variables were empty. if (!empty($empty_variables)) { drupal_set_message(t('No values for %variables could be found to use with automatically generated issues, so no issues were created.', array('%variables' => implode(', ', $empty_variables))), 'error'); return; } srand((double) microtime() * 1000000); for ($i = 0; $i < $number; $i++) { $project = $projects[array_rand($projects)]; $project_node = node_load($project->nid); $components = unserialize($project->components); $releases = project_release_get_releases($project_node, FALSE); $issue = new stdClass(); $issue->pid = $project->nid; $issue->category = $categories[array_rand($categories)]; $issue->component = $components[array_rand($components)]; $issue->priority = array_rand($priorities); $issue->title = devel_create_greeking(rand(2, 15), true); $issue->body = devel_create_content(); $issue->rid = array_rand($releases); // The user must be chosen before status (sid) so that we can make sure // that the status is set such that the user would have permission to // set the status as such. $account = user_load(array('uid' => $users[array_rand($users)]->uid)); $issue->name = $account->uid; $issue->sid = array_rand(_project_issue_generate_get_permitted_sids($account)); if (!isset($issue->sid)) { unset($issue); continue; } // Currently, project_issue nodes can either be unassigned or assigned // to the user creating the project_issue node (or in the case of comments // the user creating the comment). $possible_assignments = array(0, $account->uid); $issue->assigned = $possible_assignments[array_rand($possible_assignments)]; $issue->type = 'project_issue'; $issue->comment = COMMENT_NODE_READ_WRITE; node_save($issue); } drupal_set_message(format_plural($number, 'Your issue has been created.', '@count issues have been created.')); } /** * Generate some random project issues. * * @param $number * Number of comments to generate. */ function project_issue_generate_issue_comments($number) { $empty_variables = array(); // After retrieving the possible values for each of these variables, we // need to check and make sure that at least one value was returned. If // not, we're likely to get fatal errors later on in this function. $issues = _project_issue_generate_get_field('issues'); if (empty($issues)) { $empty_variables[] = 'issues'; } $projects = _project_issue_generate_get_field('projects'); if (empty($projects)) { $empty_variables[] = 'projects'; } $categories = _project_issue_generate_get_field('categories'); if (empty($categories)) { $empty_variables[] = 'categories'; } $priorities = _project_issue_generate_get_field('priorities'); if (empty($priorities)) { $empty_variables[] = 'priorities'; } $users = _project_issue_generate_get_field('users'); if (empty($users)) { $empty_variables[] = 'users'; } // Return now if any of the above variables were empty. if (!empty($empty_variables)) { drupal_set_message(t('No values for %variables could be found to use with automatically generated comments, so no issue comments were created.', array('%variables' => implode(', ', $empty_variables))), 'error'); return; } srand((double) microtime() * 1000000); for ($i = 0; $i < $number; $i++) { // Select a random issue to add a comment to. $k = array_rand($issues); // Update our copy of the issue to randomly decide what to change with // the new comment. This way, if we decide not to alter something, we // can leave the current value alone. $account = user_load(array('uid' => $users[array_rand($users)]->uid)); $project = $projects[array_rand($projects)]; if (rand(0, 1)) { $issues[$k]->pid = $project->nid; // If the project changes, the version must also change. $project_node = node_load($issues[$k]->pid, NULL, TRUE); $releases = project_release_get_releases($project_node, FALSE); $issues[$k]->rid = array_rand($releases); // And so must the component. $components = $project_node->project_issue['components']; $issues[$k]->component = $components[array_rand($components)]; } elseif (rand(0, 1)) { $components = unserialize($project->components); $issues[$k]->component = $components[array_rand($components)]; } if (rand(0, 1)) { $issues[$k]->category = $categories[array_rand($categories)]; } if (rand(0, 1)) { $issues[$k]->priority = array_rand($priorities); } if (rand(0, 1)) { $issues[$k]->title = devel_create_greeking(rand(2, 10), true); } if (rand(0, 1)) { $issues[$k]->sid = array_rand(_project_issue_generate_get_permitted_sids($account)); if (!isset($issues[$k]->sid)) { unset($comment); continue; } } if (rand(0, 1)) { $project_node = node_load($issues[$k]->pid, NULL, TRUE); $releases = project_release_get_releases($project_node, FALSE); $issues[$k]->rid = array_rand($releases); } // Construct a comment to put the issue into the state we just decided. $comment = array(); $comment['uid'] = $account->uid; $comment['project_info'] = array('pid' => $issues[$k]->pid, 'component' => $issues[$k]->component, 'rid' => $issues[$k]->rid); $comment['category'] = $issues[$k]->category; $comment['priority'] = $issues[$k]->priority; $comment['title'] = $issues[$k]->title; $comment['sid'] = $issues[$k]->sid; if (rand(0, 1)) { $comment['comment'] = devel_create_content(); } else { $comment['comment'] = ''; } $comment['format'] = 1; $comment['cid'] = ''; $comment['nid'] = $issues[$k]->nid; project_issue_add_followup($comment); } drupal_set_message(format_plural($number, 'Your comment has been created.', '@count comments have been created.')); } function _project_issue_generate_get_field($field, $pool_size = 100) { module_load_include('inc', 'project_issue', 'issue'); switch ($field) { case 'issues': $issues = array(); $results = db_query('SELECT p.nid, p.pid, p.category, p.component, p.priority, p.sid, p.rid, n.title FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid'); while ($result = db_fetch_object($results)) { $issues[] = $result; } return $issues; case 'projects': $projects = array(); $result = db_query('SELECT nid, components FROM {project_issue_projects}'); while ($project = db_fetch_object($result)) { $projects[] = $project; } return $projects; case 'categories': return array_keys(project_issue_category()); case 'priorities': - return project_issue_priority(); + return project_issue_priorities(); case 'users': // Determine what role ids have permission to create project_issue nodes. $users = array(); $allowed_roles = user_roles(FALSE, 'create project issues'); // If any authenticated user can create project_issue nodes, // then there is no need for an INNER JOIN in our query. // Otherwise, the query needs to INNER JOIN on the users // table so that only users with roles that are allowed to // create project_issue nodes are selected. if (isset($allowed_roles[DRUPAL_AUTHENTICATED_RID])) { $join = ''; $where = ''; } else { $join = 'INNER JOIN {users_roles} ur ON u.uid = ur.uid'; $where = "WHERE ur.rid IN (". implode(', ', array_keys($allowed_roles)) .")"; } $sql = "SELECT u.uid FROM {users} u $join $where ORDER BY RAND() LIMIT %d"; $result = db_query($sql, $pool_size); while ($user = db_fetch_object($result)) { $users[] = $user; } return $users; } } function _project_issue_generate_get_permitted_sids($user) { static $permitted_states; if (!isset($permitted_states)) { $permitted_states = array(); } if (isset($user->uid)) { if (isset($permitted_states[$user->uid])) { return $permitted_states[$user->uid]; } else { $states = project_issue_state($sid = 0, TRUE, TRUE, 0, FALSE, $user); $permitted_states[$user->uid] = $states; return $states; } } return array(); } diff --git a/includes/admin.batch_confirm.inc b/includes/admin.batch_confirm.inc new file mode 100644 index 0000000..56d2e52 --- /dev/null +++ b/includes/admin.batch_confirm.inc @@ -0,0 +1,66 @@ +<?php +// $Id: admin.batch_confirm.inc,v 1.1 2010/04/24 01:58:18 dww Exp $ + +/** + * @file + * Batch operations for updating denormalized issue priority weight and status. + */ + +/** + * Run a SQL query in batch for each row in the {project_issues} table. + * + * This function will find the range of all rows in the {project_issues} table + * and run a query against that table incerementally, 100 rows at a time. This + * function is intended to be used with batch_set(). + * + * @param $sql + * A SQL query intended to be run for each row in the {project_issues} table. + * Usually an update query, it is recommended to include 'BETWEEN %d AND %d' + * to prevent timeouts. + * @param $base_arguments + * An array of base arguments to pass to the query. The first and last nid of + * the current range are appended to the end of this query, for specifying a + * range with BETWEEN. + * @param $context + * An array containing information about batch progress. $context['sandbox'] + * contains the following keys which will be populated after this function + * has been called: + * 'min' The minimum value, or starting point. + * 'max' The maximum value, or end point. + * 'current' The nid of the last row that has been updated. + * 'finished' Will contain a percentage of total rows processed, and will + * be set to 1 when all rows have been processed. + */ +function _project_issue_batch_update($sql, $base_arguments, &$context = array()) { + $last_nid = 0; + $first_nid = 0; + if (!isset($context['sandbox']['min'])) { + // Avoid COUNT(*) like hell. + $context['sandbox']['max'] = db_result(db_query('SELECT MAX(nid) FROM {project_issues}')); + // We will use > so use - 1 when choosing the smallest nid. + $context['sandbox']['min'] = db_result(db_query('SELECT MIN(nid) - 1 FROM {project_issues}')); + $context['sandbox']['current'] = $context['sandbox']['min']; + } + $arguments = $base_arguments; + // MySQL does not support LIMIT & IN/ALL/ANY/SOME subquery so we do the hard + // work ourselves: find 100 nids and record the first and the last. + $results = db_query_range('SELECT nid FROM {project_issues} WHERE nid > %d ORDER BY nid ASC', $context['sandbox']['current'], 0, 100); + while ($node = db_fetch_object($results)) { + if (!isset($first_nid)) { + $first_nid = $node->nid; + } + $last_nid = $node->nid; + } + $arguments[] = $first_nid; + $arguments[] = $last_nid; + db_query($sql, $arguments); + // Note that we do not count exactly as there can be holes. That's still + // better than running COUNT() on large datasets. + if ($last_nid < $context['sandbox']['max']) { + $context['finished'] = ($last_nid - $context['sandbox']['min']) / ($context['sandbox']['max'] - $context['sandbox']['min']); + $context['sandbox']['current'] = $last_nid; + } + else { + $context['finished'] = 1; + } +} diff --git a/includes/admin.issue_priority.inc b/includes/admin.issue_priority.inc new file mode 100644 index 0000000..0f3992d --- /dev/null +++ b/includes/admin.issue_priority.inc @@ -0,0 +1,227 @@ +<?php +// $Id: admin.issue_priority.inc,v 1.1 2010/04/24 01:58:18 dww Exp $ + +/** + * @file + * Code for the issue priorities admin configuration form. + */ + +/** + * Build the form for project_issue_admin_priority_form. + */ +function project_issue_admin_priority_form(&$form_state) { + $result = db_query('SELECT priority, name, weight FROM {project_issue_priority} ORDER BY weight'); + $max = 15; + $delta = 0; + while ($priority = db_fetch_object($result)) { + // We need to ensure the weight options include the maximum existing + // weight. + $max = max($delta, $priority->weight); + $form['priority'][$priority->priority]['name'] = array( + '#type' => 'textfield', + '#default_value' => $priority->name, + '#size' => 20, + '#maxlength' => 255, + ); + $form['priority'][$priority->priority]['weight'] = array( + '#type' => 'weight', + '#default_value' => $priority->weight, + '#delta' => &$delta, + '#attributes' => array('class' => 'project-issue-priority-weight'), + ); + $form['delete'][$priority->priority]['#value'] = l(t('Delete'), 'admin/project/project-issue-priority/delete/'. $priority->priority); + } + $delta = $max + 1; + $form['priority'][0]['name'] = array( + '#type' => 'textfield', + '#default_value' => '', + '#size' => 20, + '#maxlength' => 255, + ); + $form['priority'][0]['weight'] = array( + '#type' => 'weight', + // Make sure that the new item has a weight higher than highest priority + // since new item appears at bottom of the form by default. + '#default_value' => $max + 1, + '#delta' => $max + 1, + '#attributes' => array('class' => 'project-issue-priority-weight'), + ); + $form['delete'][0]['#value'] = ''; + + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Save'), + ); + $form['#tree'] = TRUE; + return $form; +} + +/** + * Render the HTML for the admin issue priority form. + * + * @see project_issue_admin_priority_form() + * @see drupal_add_tabledrag() + */ +function theme_project_issue_admin_priority_form($form) { + drupal_add_tabledrag('project-issue-admin-priority-table', 'order', 'self', 'project-issue-priority-weight'); + $header = array( + t('Priority'), + t('Weight'), + t('Operations'), + ); + foreach (element_children($form['priority']) as $key) { + $rows[] = array( + 'class' => 'draggable', + 'data' => array( + drupal_render($form['priority'][$key]['name']), + drupal_render($form['priority'][$key]['weight']), + drupal_render($form['delete'][$key]), + ), + ); + } + $output = '<div>' . theme('table', $header, $rows, array('id' => 'project-issue-admin-priority-table')) . '</div>'; + $output .= drupal_render($form); + return $output; +} + +/** + * Submit handler for project_issue_admin_states_form. + */ +function project_issue_admin_priority_form_submit($form, &$form_state) { + $offset = 0; + foreach ($form_state['values']['priority'] as $priority_id => $value) { + $offset = min($offset, $value['weight']); + } + // $offset at this point contains the smallest weight. If that's below zero, + // then adding it to every weight will result in unsigned weights. Otherwise + // such addition is not necessary. + $offset = $offset < 0 ? -$offset : 0; + // Update existing priorities. + $update_expression = ''; + $weights = array(); + foreach ($form_state['values']['priority'] as $priority_id => $value) { + $weight = $value['weight'] + $offset; + $form_state['values']['priority'][$priority_id]['weight'] = $weight; + // Update existing. + if ($priority_id) { + $priority = db_fetch_object(db_query('SELECT priority, name, weight FROM {project_issue_priority} WHERE priority = %d', $priority_id)); + $update = $priority->name !== $value['name']; + // Check to see whether the record needs updating. We love PHP and '0'. + if ((string)$priority->weight !== (string)$weight) { + $update_expression .= " WHEN %d THEN %d"; + $weights[] = $priority->priority; + $weights[] = $weight; + $update = TRUE; + } + if ($update) { + db_query("UPDATE {project_issue_priority} SET name = '%s', weight = %d WHERE priority = %d", $value['name'], $weight, $priority_id); + } + } + // Add new priority. + elseif ($value['name']) { + // Check to see whether the state already exists: + $issue_state = db_result(db_query("SELECT COUNT(*) FROM {project_issue_priority} WHERE name = '%s'", $value['name'])); + if (empty($issue_state)) { + db_query("INSERT INTO {project_issue_priority} (name, weight) VALUES ('%s', %d)", $value['name'], $weight); + } + else { + drupal_set_message(t('Priority %priority already exists.', array ('%priority' => $value['name'])), 'error'); + } + } + } + if ($weights) { + $weight_sql = "UPDATE {project_issues} SET priority_weight = CASE priority $update_expression ELSE priority_weight END WHERE nid BETWEEN %d AND %d"; + $batch = array( + 'operations' => array( + array('_project_issue_batch_update', array($weight_sql, $weights)), + ), + 'title' => t('Processing'), + // We use a single multi-pass operation, so the default + // 'Remaining x of y operations' message will be confusing here. + 'progress_message' => '', + 'error_message' => t('The update has encountered an error.'), + // The operations do not live in the .module file, so we need to + // tell the batch engine which file to load before calling them. + 'file' => drupal_get_path('module', 'project_issue') .'/includes/admin.batch_confirm.inc', + ); + batch_set($batch); + } +} + +/** + * Build a confirmation form when deleting an issue priority. + * + * This allows the admin to re-prioritize any issues with the priority being + * deleted using admin.batch_confirm.inc. + * + * @param $form_state + * The state of the form we're trying to build. + * @param $priority_id + * The {project_issue_priority}.priority ID being deleted. + */ +function project_issue_delete_priority_confirm(&$form_state, $priority_id) { + // Helper functions are in issue.inc. + require_once drupal_get_path('module', 'project_issue') .'/issue.inc'; + $schema = drupal_get_schema('project_issues'); + if (!function_exists('project_issue_priority') || !isset($schema['fields']['priority']) || !db_table_exists('project_issue_priority')) { + return drupal_access_denied(); + } + $priorities = project_issue_priorities(); + $name = $priorities[$priority_id]; + unset($priorities[$priority_id]); + + // $column is verified to exist. + $total = db_result(db_query("SELECT COUNT(nid) AS total FROM {project_issues} WHERE priority = %d", $priority_id)); + if ($total > 0) { + $form['new_pid'] = array( + '#type' => 'select', + '#title' => t('Reassign priority'), + '#default_value' => $priority_id, + '#options' => $priorities, + '#description' => format_plural($total, 'There is 1 existing issue assigned @name priority. Please select a new priority for this issue.', 'There are @count existing issues assigned @name priority. Please select a new priority for these issues.', array('@name' => $name)), + ); + } + $form['pid'] = array( + '#type' => 'value', + '#value' => $priority_id, + ); + $form['name'] = array( + '#type' => 'hidden', + '#value' => $name, + ); + return confirm_form( + $form, + t('Are you sure you want to delete the priority %name?', array('%name' => $name)), + 'admin/project/project-issue-priority', + t('This action cannot be undone.'), + t('Delete'), t('Cancel') + ); +} + +/** + * Submit handler for confirm form when deleting an issue priority. + */ +function project_issue_delete_priority_confirm_submit($form, &$form_state) { + db_query('DELETE FROM {project_issue_priority} WHERE priority = %d', $form_state['values']['pid']); + $form_state['redirect'] = 'admin/project/project-issue-priority'; + drupal_set_message(t('Project issue priority %name deleted.', array('%name' => $form_state['values']['name']))); + if (isset($form_state['values']['new_pid'])) { + $priority_weight = db_result(db_query('SELECT weight FROM {project_issue_priority} WHERE priority = %d', $form_state['values']['new_pid'])); + $arguments = array($form_state['values']['new_pid'], $priority_weight, $form_state['values']['pid']); + $update_sql = "UPDATE {project_issues} SET priority = %d, priority_weight = %d WHERE priority = %d AND nid BETWEEN %d AND %d"; + $batch = array( + 'operations' => array( + array('_project_issue_batch_update', array($update_sql, $arguments)), + ), + 'title' => t('Processing'), + // We use a single multi-pass operation, so the default + // 'Remaining x of y operations' message will be confusing here. + 'progress_message' => '', + 'error_message' => t('The update has encountered an error.'), + // The operations do not live in the .module file, so we need to + // tell the batch engine which file to load before calling them. + 'file' => drupal_get_path('module', 'project_issue') .'/includes/admin.batch_confirm.inc', + ); + batch_set($batch); + } +} diff --git a/includes/admin.issue_status.inc b/includes/admin.issue_status.inc index 744de90..ef299b9 100644 --- a/includes/admin.issue_status.inc +++ b/includes/admin.issue_status.inc @@ -1,193 +1,207 @@ <?php -// $Id: admin.issue_status.inc,v 1.2 2010/04/24 01:13:33 dww Exp $ +// $Id: admin.issue_status.inc,v 1.3 2010/04/24 01:58:18 dww Exp $ /** * @file * Code for the issue status admin configuration form. */ function theme_project_issue_admin_states_form($form) { drupal_add_tabledrag('project-issue-status-admin-table', 'order', 'self', 'project-issue-status-weight'); $header = array( array('data' => t('ID')), array('data' => t('Name')), array('data' => t('Weight')), array('data' => t('Author may set')), array('data' => t('In default queries')), array('data' => t('Default status')), array('data' => t('Operations')) ); foreach (element_children($form['status']) as $key) { $rows[] = array( 'class' => 'draggable', 'data' => array( drupal_render($form['status'][$key]['sid']), drupal_render($form['status'][$key]['name']), drupal_render($form['status'][$key]['weight']), drupal_render($form['status'][$key]['author_has']), drupal_render($form['status'][$key]['default_query']), drupal_render($form['default_state'][$key]), drupal_render($form['delete'][$key]), ), ); } $rows[] = array( 'class' => 'draggable', 'data' => array( NULL, drupal_render($form['status_add']['name']), drupal_render($form['status_add']['weight']), drupal_render($form['status_add']['author_has']), drupal_render($form['status_add']['default_query']), NULL, NULL, ), ); $output = '<div>' . theme('table', $header, $rows, array('id' => 'project-issue-status-admin-table')) . '</div>'; $output .= drupal_render($form); return $output; } function project_issue_admin_states_form(&$form_state) { $result = db_query('SELECT * FROM {project_issue_state} ORDER BY weight'); $default_state = variable_get('project_issue_default_state', 1); $default_states = project_issue_default_states(); $form['status']['#tree'] = TRUE; while ($state = db_fetch_object($result)) { $options[$state->sid] = ''; $form['status'][$state->sid]['sid'] = array( '#type' => 'markup', '#value' => $state->sid, ); $form['status'][$state->sid]['name'] = array( '#type' => 'textfield', '#default_value' => $state->name, '#size' => 20, '#maxlength' => 255, ); $form['status'][$state->sid]['weight'] = array( '#type' => 'weight', '#default_value' => $state->weight, '#delta' => 15, '#attributes' => array('class' => 'project-issue-status-weight'), ); $form['status'][$state->sid]['author_has'] = array( '#type' => 'checkbox', '#default_value' => $state->author_has, ); $form['status'][$state->sid]['default_query'] = array( '#type' => 'checkbox', '#default_value' => in_array($state->sid, $default_states), ); $del_link = ($state->sid != $default_state) ? l(t('Delete'), 'admin/project/project-issue-status/delete/'. $state->sid) : ''; $form['delete'][$state->sid] = array( '#type' => 'markup', '#value' => $del_link, ); } $form['default_state'] = array( '#type' => 'radios', '#options' => $options, '#default_value' => $default_state, ); $form['status_add']['name'] = array( '#type' => 'textfield', '#size' => 20, '#maxlength' => 255, ); $form['status_add']['weight'] = array( '#type' => 'weight', '#default_value' => 0, '#delta' => 15, '#attributes' => array('class' => 'project-issue-status-weight'), ); $form['status_add']['author_has'] = array( '#type' => 'checkbox', ); $form['status_add']['default_query'] = array( '#type' => 'checkbox', ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), ); $form['#tree'] = TRUE; return $form; } /** * Submit handler for project_issue_admin_states_form. */ function project_issue_admin_states_form_submit($form, &$form_state) { // Check for and apply changes or additions to project issue status options. if (isset($form_state['values']['default_state'])) { variable_set('project_issue_default_state', $form_state['values']['default_state']); } // Update existing status options. if($form_state['values']['status']) { foreach ($form_state['values']['status'] as $sid => $value) { $state = db_fetch_object(db_query('SELECT name, weight, author_has, default_query FROM {project_issue_state} WHERE sid = %d', $sid)); // Check to see whether the record needs updating. if (($state->name != $value['name']) || ($state->weight != $value['weight']) || ($state->author_has != $value['author_has']) || ($state->default_query != $value['default_query'])) { db_query("UPDATE {project_issue_state} SET name = '%s', weight = %d, author_has = %d, default_query = %d WHERE sid = %d", $value['name'], $value['weight'], $value['author_has'], $value['default_query'], $sid); } } } // Add any new status options. if (isset($form_state['values']['status_add']) && !empty($form_state['values']['status_add']['name'])) { // Check to see whether the state already exists: $issue_state = db_result(db_query("SELECT COUNT(*) FROM {project_issue_state} WHERE name = '%s'", $form_state['values']['status_add']['name'])); if (empty($issue_state)) { db_query("INSERT INTO {project_issue_state} (name, weight, author_has, default_query) VALUES ('%s', %d, %d, %d)", $form_state['values']['status_add']['name'], $form_state['values']['status_add']['weight'], $form_state['values']['status_add']['author_has'], $form_state['values']['status_add']['default_query']); } else { drupal_set_message(t('Status %status already exists.', array ('%status' => $form_state['values']['status_add']['name'])), 'error'); } } } function project_issue_delete_state_confirm(&$form_state, $sid) { $states = project_issue_state(); $name = $states[$sid]; $total = db_result(db_query('SELECT COUNT(nid) AS total FROM {project_issues} WHERE sid = %d', $sid)); if ($total > 0) { $form['new_sid'] = array( '#type' => 'select', '#title' => t('Reassign status'), '#default_value' => $sid, '#options' => $states, '#description' => format_plural($total, 'There is 1 existing issue assigned to @name status. Please select a new status for this issue.', 'There are @count existing issues assigned to @name status. Please select a new status for these issues.', array('@name' => $name)), ); } $form['sid'] = array( '#type' => 'value', '#value' => $sid, ); $form['name'] = array( '#type' => 'hidden', '#value' => $name, ); return confirm_form( $form, t('Are you sure you want to delete the status option %name?', array('%name' => $name)), 'admin/project/project-issue-status', t('This action cannot be undone.'), t('Delete'), t('Cancel') ); } function project_issue_delete_state_confirm_validate($form, &$form_state) { if ($form_state['values']['new_sid'] == $form_state['values']['sid']) { form_set_error('new_sid', t('Choose a new issue status for existing issues of status %name.', array('%name' => $form_state['values']['name']))); } } function project_issue_delete_state_confirm_submit($form, &$form_state) { + db_query('DELETE FROM {project_issue_state} WHERE sid = %d', $form_state['values']['sid']); + $form_state['redirect'] = 'admin/project/project-issue-status'; + drupal_set_message(t('Project issue status %name deleted.', array('%name' => $form_state['values']['name']))); if ($form_state['values']['new_sid']) { - db_query('UPDATE {project_issues} SET sid = %d WHERE sid = %d', $form_state['values']['new_sid'], $form_state['values']['sid']); + $arguments = array($form_state['values']['new_sid'], $form_state['values']['sid']); + $update_sql = "UPDATE {project_issues} SET sid = %d WHERE sid = %d AND nid BETWEEN %d AND %d"; + $batch = array( + 'operations' => array( + array('_project_issue_batch_update', array($update_sql, $arguments)), + ), + 'title' => t('Processing'), + // We use a single multi-pass operation, so the default + // 'Remaining x of y operations' message will be confusing here. + 'progress_message' => '', + 'error_message' => t('The update has encountered an error.'), + // The operations do not live in the .module file, so we need to + // tell the batch engine which file to load before calling them. + 'file' => drupal_get_path('module', 'project_issue') .'/includes/admin.batch_confirm.inc', + ); + batch_set($batch); } - db_query('DELETE FROM {project_issue_state} WHERE sid = %d', $form_state['values']['sid']); - drupal_set_message(t('Project issue status %issue deleted.', array('%issue' => $form_state['values']['name']))); - $form_state['redirect'] ='admin/project/project-issue-status'; } - diff --git a/includes/comment.inc b/includes/comment.inc index 3f8d393..84c3829 100644 --- a/includes/comment.inc +++ b/includes/comment.inc @@ -1,674 +1,676 @@ <?php -// $Id: comment.inc,v 1.158 2010/04/22 09:34:54 dww Exp $ +// $Id: comment.inc,v 1.159 2010/04/24 01:58:18 dww Exp $ function project_issue_comment(&$arg, $op) { // $arg can be a comment object, or a form or form_values. if (is_object($arg)) { $nid = $arg->nid; } elseif (is_array($arg)) { $nid = is_array($arg['nid']) ? $arg['nid']['#value'] : $arg['nid']; } $node = node_load($nid); if ($node->type != 'project_issue') { return; } // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Maintain an array of project ids that are affected by this comment // operation. We'll use this to invalidate the "Issue cockpit" block cache // for any of these projects. $affected_projects = array(); switch ($op) { case 'insert': // Get a lock on the issue in order to generate the next comment ID. $tries = 20; $sleep_increment = 0; while ($tries) { $lock = db_query("UPDATE {project_issues} SET db_lock = 1 WHERE nid = %d AND db_lock = 0", $arg['nid']); if (db_affected_rows()) { $id = db_result(db_query("SELECT last_comment_id FROM {project_issues} WHERE nid = %d", $arg['nid'])) + 1; db_query("UPDATE {project_issues} SET last_comment_id = %d, db_lock = 0 WHERE nid = %d", $id, $arg['nid']); break; } // Wait a random and increasing amount of time before the next attempt. $sleep = rand(10000, 1000000) + $sleep_increment; usleep($sleep); $sleep_increment += 50000; $tries--; } if (isset($id)) { $rid = isset($arg['project_info']['rid']) ? $arg['project_info']['rid'] : 0; db_query("INSERT INTO {project_issue_comments} (nid, cid, pid, rid, component, category, priority, assigned, sid, title, timestamp, comment_number) VALUES (%d, %d, %d, %d, '%s', '%s', %d, %d, %d, '%s', %d, %d)", $arg['nid'], $arg['cid'], $arg['project_info']['pid'], $rid, $arg['project_info']['component'], $arg['category'], $arg['priority'], $arg['project_info']['assigned'], $arg['sid'], $arg['title'], $arg['timestamp'], $id); db_query("UPDATE {comments} SET subject = '%s' WHERE cid = %d", "#$id", $arg['cid']); project_issue_update_by_comment($arg, 'insert'); $affected_projects[$old_data->pid] = 1; $affected_projects[$arg['project_info']['pid']] = 1; } else { drupal_set_message(t('There was an error submitting your comment -- please try again. If the problem persists, contact the system administrator.'), 'error'); watchdog('project_issue', 'Error obtaining lock for project issue %nid', array('%nid' => $arg['nid']), WATCHDOG_ERROR, 'node/'. $arg['nid']); // This is a bit extreme, but we have to clean up the failed comment, // or it will appear on the issue. _comment_delete_thread((object) $arg); _comment_update_node_statistics($arg['nid']); cache_clear_all(); // The hard redirect prevents any bogus data from being inserted for the failed comment. drupal_goto('node/'. $arg['nid']); } break; case 'update': project_issue_update_by_comment($arg, 'update'); // Updating a comment can't change anything relevant about the issue for // the purposes of the issue blocks, so we don't need to touch // $affected_projects here. break; case 'delete': // Save the project that's specified in this comment so we can // invalidate its issue block cache. $deleted_comment_project_id = db_result(db_query("SELECT pid FROM {project_issue_comments} WHERE cid = %d", $arg->cid)); $affected_projects[$deleted_comment_project_id] = 1; // Actually delete the comment db_query("DELETE FROM {project_issue_comments} WHERE cid = %d", $arg->cid); $current_data = project_issue_update_by_comment($arg, 'delete'); // We should also invalidate the block cache for whatever project is now // used for this issue, since we might be deleting a comment that moved // an issue from one project to another. $affected_projects[$current_data->pid] = 1; break; case 'view': if (isset($arg->cid)) { $project_issue_table = project_issue_comment_view($original_node, $arg); } else { // Previewing a comment. $test = drupal_clone($arg); $test->pid = $arg->project_info['pid']; $test->component = $arg->project_info['component']; $test->assigned = $arg->project_info['assigned']; // Add a dummy rid if necessary -- prevents incorrect change data. $test->rid = isset($arg->project_info['rid']) ? $arg->project_info['rid'] : 0; $comment_changes = project_issue_metadata_changes($node, $old_data, $test, project_issue_field_labels('web')); $project_issue_table = theme('project_issue_comment_table', $comment_changes); } if ($project_issue_table) { $arg->comment = '<div class="project-issue"><div class="summary">'. $project_issue_table .'</div></div>' . $arg->comment; } break; } // If there are any affected projects, invalidate the block cache for those. if (!empty($affected_projects)) { foreach ($affected_projects as $pid => $value) { $cid = 'project_issue_cockpit_block:'. $pid; cache_clear_all($cid, 'cache'); } } } /** * Add project issue metadata to the comment form. * * @param $form * Reference to form structure. * @param $form_state * Current form state. */ function project_issue_form_comment_form_alter(&$form, &$form_state) { $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Comment body is not required since we validate that ourselves. unset($form['comment_filter']['comment']['#required']); // The 'your name' item just wastes screen estate. unset($form['_author']); // For existing comments, we want to preserve the comment subject, // Even if the subject field is disabled. if ($cid = $form['cid']['#value']) { $subject = db_result(db_query('SELECT subject FROM {comments} WHERE cid = %d', $cid)); } // For new comments, show the expected next number for previews. // This is only for show, the number will be generated when the comment // is posted. else { $next_id = db_result(db_query('SELECT last_comment_id FROM {project_issues} WHERE nid = %d', $form['nid']['#value'])) + 1; $subject = "#$next_id"; // Clobber the comment signature for new followups if necessary. // TODO: Revamp this for Drupal 6. if (!variable_get('project_issue_show_comment_signatures', 0)) { $form['comment_filter']['comment']['#default_value'] = ''; } } $form['subject'] = array( '#type' => 'value', '#value' => $subject, ); // Any time we're on a reply page, show the full issue below the reply. if (project_issue_is_comment_reply()) { $form['#pre_render'][] = 'project_issue_comment_pre_render'; } // Make sure project is current here -- it may have changed when posted. if (!empty($form_state['values']['project_info']['pid'])) { $node->project_issue['pid'] = $form_state['values']['project_info']['pid']; } $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); project_issue_set_breadcrumb($node, $project); // Only allow metadata changes on new followups. if (isset($form['cid']['#value'])) { return; } // We have to set $form['#action'] to prevent AHAH nastiness. if (!empty($form['pid']['#value'])) { $form['#action'] = url('comment/reply/' . $nid . '/' . $form['pid']['#value']); } else { $form['#action'] = url('comment/reply/' . $nid); } // We need to ask for almost the same metadata as project issue itself // so let's reuse the form. $form += project_issue_form($node, $form_state, TRUE); // comment.module is basically still FAPI v1. It sets the preview button to // #type 'button', so FAPI doesn't really consider that a form submission. // However, we depend on the form being rebuilt on preview to do our magic. // Thanks to a change in 6.14 core, form.inc will only rebuild the form if // $form_state['submitted'] is TRUE. So, we set the preview button to // actually be a 'submit' button so that the form is rebuilt on preview and // our comment preview code can kick in. $form['preview']['#type'] = 'submit'; // We need this otherwise pid collides with comment. $form['project_info']['#tree'] = TRUE; $form['project_info']['#weight'] = -2; // Remove the form item that displays the current project, and // replace the static single project value with a select list // of all projects to make swapping simpler. unset($form['project_info']['project_display']); $uris = NULL; if (variable_get('project_issue_autocomplete', 0) == 1) { $form['project_info']['project_title'] = array( '#type' => 'textfield', '#title' => t('Project'), '#default_value' => $project->title, '#required' => TRUE, '#weight' => -1, '#size' => 35, '#autocomplete_path' => 'project/autocomplete/issue/project', '#attributes' => array( 'onFocus' => 'project_issue_autocomplete_handler()', ), '#ahah' => array( 'progress' => array( 'type' => 'none', ), 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', ), ); } else { $projects = project_projects_select_options($uris); $form['project_info']['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#default_value' => $project->nid, '#options' => $projects, '#required' => TRUE, '#weight' => -1, '#ahah' => array( 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', 'event' => 'change', ), ); } $form['issue_info']['#weight'] = -1; $form['#prefix'] = '<div class="project-issue"><div class="node-form"><div class="standard">'; $form['#suffix'] = '</div></div></div>'; $form['original_issue'] = array( '#type' => 'fieldset', '#title' => t('Edit issue settings'), '#description' => t('Note: changing any of these items will update the issue\'s overall values.'), '#collapsible' => TRUE, '#weight' => -10, ); $form['original_issue']['title'] = array( '#type' => 'textfield', '#title' => t('Issue title'), '#maxlength' => 128, '#default_value' => $node->title, '#weight' => -30, '#required' => TRUE, ); $form['project_info']['assigned'] = $form['issue_info']['assigned']; unset($form['issue_info']['assigned']); $form['project_info']['#prefix'] = '<div id="project-info-wrapper" class="inline-options">'; $form['project_info']['#suffix'] = '</div>'; // Remove the 'Project information' and 'Issue information' fieldsets, // since we'll move everything inside the 'Edit issue settings' fieldset. unset($form['project_info']['#type'], $form['project_info']['#title']); unset($form['issue_info']['#type'], $form['issue_info']['#title']); // Restructure the UI to de-emphasize the original project form inputs. $form['original_issue']['project_info'] = $form['project_info']; $form['original_issue']['issue_info'] = $form['issue_info']; unset($form['project_info'], $form['issue_info']); unset($form['issue_details'], $form['project_help']); drupal_add_js(drupal_get_path('module', 'project_issue') .'/project_issue.js'); } /** * Validate issue metadata on the comment form. * * @param $form * The Drupal form structure. * @param $form_state * The current state of the form. */ function project_issue_form_comment_validate($form, &$form_state) { if (empty($form['cid']['#value']) && variable_get('project_issue_autocomplete', 0) == 1) { if (empty($form_state['values']['project_info']['project_title'])) { form_set_error('project_title', t('You must enter a project to navigate to.')); } else { $pid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_info']['project_title'], 'project_project')); if (empty($pid)) { form_set_error('project_info][project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_info']['project_title']))); } else { $form_state['values']['project_info']['pid'] = $pid; } } } if (!empty($form_state['rebuild'])) { return; } // Only validate metadata changes on new followups. if (isset($form_state['values']['cid'])) { return; } $values = $form_state['values']; $project_info = $form_state['values']['project_info']; $nid = $values['nid']; $node = node_load($nid); // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Adjust new file attachments to go to the issues directory. // We have to do this during validate, otherwise we might miss // adjusting the filename before comment upload saves it (module weighting) // TODO: is this still true? project_issue_change_comment_upload_path($values); // Make sure project is current here -- it may have changed when posted. if (isset($project_info['pid'])) { $node->project_issue['pid'] = $project_info['pid']; } $project = node_load($node->project_issue['pid']); if (!empty($project) && $project->type == 'project_project') { // Force all comments to be a child of the main issue, to match the // flat display, and also to prevent accidentally deleting a thread. $form_state['values']['pid'] = 0; // Validate version. if (module_exists('project_release') && isset($project_info['rid']) && ($releases = project_release_get_releases($project, 0, 'version', 'all', array($project_info['rid'])))) { $rid = $project_info['rid']; if ($rid && !in_array($rid, array_keys($releases))) { $rid = 0; } // Check to make sure this release is not marked as an invalid // release node for user selection. $invalid_rids = variable_get('project_issue_invalid_releases', array()); if (!empty($invalid_rids) && ((empty($rid) && in_array($node->project_issue['rid'], $invalid_rids)) || in_array($rid, $invalid_rids))) { form_set_error('project_info][rid', t('%version is not a valid version, please select a different value.', array('%version' => $releases[$node->project_issue['rid']]))); } elseif (empty($rid)) { form_set_error('project_info][rid', t('You have to specify a valid version.')); } } // Add a dummy rid if necessary -- prevents incorrect change data. else { $rid = 0; } // Validate component. $component = $project_info['component']; if ($component && !in_array($component, $project->project_issue['components'])) { $component = 0; } empty($component) && form_set_error('project_info][component', t('You have to specify a valid component.')); } else { form_set_error('project_info][pid', t('You have to specify a valid project.')); } empty($values['category']) && form_set_error('category', t('You have to specify a valid category.')); // Now, make sure the comment changes *something* about the issue. // If the user uploaded a file, so long as it's not marked for removal, // we consider that a valid change to the issue, too. $has_file = FALSE; $files = isset($values['files']) ? $values['files'] : array(); foreach ($files as $number => $data) { if (empty($data['remove'])) { $has_file = TRUE; break; } } if (!$has_file && empty($values['comment'])) { $comment = drupal_clone((object) $values); $comment->pid = $project_info['pid']; $comment->component = $component; $comment->rid = $rid; $comment->assigned = $project_info['assigned']; $comment_changes = project_issue_metadata_changes($node, $old_data, $comment, project_issue_field_labels('web')); // If the PID changed, rebuild the form if (isset($comment_changes['pid']['new']) && $comment_changes['pid']['new'] === TRUE) { $form_state['rebuild'] = TRUE; } $has_change = FALSE; foreach ($comment_changes as $field => $changes) { if (isset($changes['new'])) { $has_change = TRUE; break; } } if (!$has_change) { form_set_error('comment', t('You must either add a comment, upload a file, or change something about this issue.')); } } } /** * Theme a project issue metadata table. * * @param $comment_changes * Array containing metadata differences between comments * as returned by project_issue_metadata_changes(). * @return * The themed metadata table. */ function theme_project_issue_comment_table($comment_changes) { $rows = array(); foreach ($comment_changes as $field => $change) { if (!empty($change['label']) && isset($change['old']) && isset($change['new'])) { $rows[] = theme('project_issue_comment_table_row', $field, $change); } } return $rows ? theme('table', array(), $rows) : ''; } /** * Theme a single row of the project issue metadata changes table. * * @param $field * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * An array representing one row of the table. * * NOTE: If you override this theme function, you *must* make sure * that you sanitize all output from this function that is displayed * to the user. No further escaping/filtering of the data in this * table will take place after this function. In most cases * this means that you need to run the $change['label'], $change['old'], * and $change['new'] values through either the check_plain() or * filter_xss() function to prevent XSS and other types * of problems due to any malicious input in these * field values. */ function theme_project_issue_comment_table_row($field, $change) { // Allow anchor, emphasis, and strong tags in metadata tables. $allowed_tags = array('a', 'em', 'strong'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])){ foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { $added[] = '+'. $item; } } elseif (!empty($change['new'])) { $added[] = '+'. $change['new']; } return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(implode(', ', $removed), $allowed_tags), filter_xss(implode(', ', $added), $allowed_tags), ); } elseif (in_array($field, $plain_fields)) { return array( filter_xss($change['label'], $allowed_tags) .':', check_plain(project_issue_change_summary($field, $change['old'])), '&raquo; '. check_plain(project_issue_change_summary($field, $change['new'])), ); } else { return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(project_issue_change_summary($field, $change['old']), $allowed_tags), '&raquo; '. filter_xss(project_issue_change_summary($field, $change['new']), $allowed_tags), ); } } /** * Returns the issue metadata table for a comment. * * @param $node * The corresponding node. * @param $comment * The comment, if it's set then metadata will be returned. If it's not * set then metadata will be precalculated. * @return * A themed table of issue metadata. */ function project_issue_comment_view(&$node, $comment = NULL) { static $project_issue_tables; if (isset($comment)) { return isset($project_issue_tables[$comment->cid]) ? $project_issue_tables[$comment->cid] : ''; } if (!empty($node->comment_count)) { $old = unserialize(db_result(db_query('SELECT original_issue_data FROM {project_issues} WHERE nid = %d', $node->nid))); $labels = project_issue_field_labels('web'); $result = db_query('SELECT p.cid, p.title, p.pid, p.rid, p.component, p.category, p.priority, p.assigned, p.sid FROM {project_issue_comments} p INNER JOIN {comments} c ON p.cid = c.cid WHERE p.nid = %d AND c.status = %d ORDER BY p.timestamp ASC', $node->nid, COMMENT_PUBLISHED); while ($followup = db_fetch_object($result)) { $followup_changes = project_issue_metadata_changes($node, $old, $followup, project_issue_field_labels('web')); $project_issue_tables[$followup->cid] = theme('project_issue_comment_table', $followup_changes); $old = $followup; } } } /** * Updates the project issue based on the comment inserted/updated/deleted. * * @param $comment_data * The comment data that's been submitted. * @param $op * The comment operation performed, 'insert', 'update', 'delete'. * @return * An object representing the comment data used to update the issue. */ function project_issue_update_by_comment($comment_data, $op) { switch ($op) { case 'insert': // Massage the incoming data so the structure is consistent throughout the function. $comment_data['component'] = $comment_data['project_info']['component']; $comment_data['pid'] = $comment_data['project_info']['pid']; $comment_data['rid'] = isset($comment_data['project_info']['rid']) ? $comment_data['project_info']['rid'] : 0; unset ($comment_data['project_info']); $comment_data = (object) $comment_data; // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. if (!isset($comment_data->followup_no_mail)) { // Temporary hack to get around sending of auto-close emails. project_issue_set_mail_notify($comment_data->nid); } break; case 'update': $comment_data = (object) $comment_data; break; } // In order to deal with deleted/unpublished comments, make sure that we're performing // the updates to the issue with the latest available published comment. $comment_data = project_issue_get_newest_comment($comment_data); + $priority_weight = db_result(db_query('SELECT weight FROM {project_issue_priority} WHERE priority = %d', $comment_data->priority)); + // Update the issue data to reflect the new final states. - db_query("UPDATE {project_issues} SET pid = %d, category = '%s', component = '%s', priority = %d, rid = %d, assigned = %d, sid = %d WHERE nid = %d", $comment_data->pid, $comment_data->category, $comment_data->component, $comment_data->priority, $comment_data->rid, $comment_data->assigned, $comment_data->sid, $comment_data->nid); + db_query("UPDATE {project_issues} SET pid = %d, category = '%s', component = '%s', priority = %d, rid = %d, assigned = %d, sid = %d, priority_weight = %d WHERE nid = %d", $comment_data->pid, $comment_data->category, $comment_data->component, $comment_data->priority, $comment_data->rid, $comment_data->assigned, $comment_data->sid, $priority_weight, $comment_data->nid); // Update the issue title. $node = node_load($comment_data->nid, NULL, TRUE); // Don't use cached since we changed data above. $node->title = $comment_data->title; // This also updates the changed date of the issue. node_save($node); // Return the object of comment data we used to update the issue. return $comment_data; } /** * Adjusts the filepath of issue followups so files are saved to * the correct issues directory. * * @param $comment * An array of the submitted comment values. */ function project_issue_change_comment_upload_path(&$comment) { static $run = NULL; // Only for new comments with attachments. if (empty($comment['cid']) && isset($comment['files']) && !isset($run)) { $run = TRUE; // Make sure this only gets run once. project_issue_rewrite_issue_filepath($comment['files']); } } /** * Retrieves the newest published comment for an issue. * * @param $comment_data * An object representing the current comment being edited * @return * An object representing the most recent published comment for the issue. */ function project_issue_get_newest_comment($comment_data) { // Get the cid of the most recent comment. $latest_cid = db_result(db_query_range('SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp DESC', $comment_data->nid, COMMENT_PUBLISHED, 0, 1)); if ($latest_cid) { $comment_data = db_fetch_object(db_query('SELECT * FROM {project_issue_comments} WHERE cid = %d', $latest_cid)); } // No more comments on the issue -- use the original issue metadata. else { // nid isn't stored in the original issue data, so capture it here and pass back // into the object. $nid = $comment_data->nid; $comment_data = unserialize(db_result(db_query("SELECT original_issue_data FROM {project_issues} WHERE nid = %d", $comment_data->nid))); $comment_data->nid = $nid; } return $comment_data; } /** * Test to determine if the active page is the comment reply form. * * @return * TRUE if the active page is the comment reply form, FALSE otherwise. */ function project_issue_is_comment_reply() { return arg(0) == 'comment' && arg(1) == 'reply'; } /** * Test to determine if the active page is the comment edit form. * * @return * TRUE if the active page is the comment edit form, FALSE otherwise. */ function project_issue_is_comment_edit() { return arg(0) == 'comment' && arg(1) == 'edit'; } /** * Appends the comment thread to the comment reply form. */ function project_issue_comment_pre_render($form) { // Force the correct formatting. $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; $suffix = empty($form['#suffix']) ? '' : $form['#suffix']; $node = node_load($form['nid']['#value']); // Unfortunately, the comment module blindly puts the node view // after the comment form on preview, in the case where the comment // parent is 0. If we want our issue previews to be consistent, this // ugly hack is necessary. if (isset($form['#parameters'][1]['values']['op']) && $form['#parameters'][1]['values']['op'] == t('Preview')) { $preview = comment_render($node, 0); } else { $preview = node_show($node, 0); } $form['#suffix'] = $suffix . $preview; return $form; } diff --git a/includes/issue_node_form.inc b/includes/issue_node_form.inc index 0c87c1e..8096ca7 100644 --- a/includes/issue_node_form.inc +++ b/includes/issue_node_form.inc @@ -1,484 +1,486 @@ <?php -// $Id: issue_node_form.inc,v 1.6 2010/04/20 07:05:25 dww Exp $ +// $Id: issue_node_form.inc,v 1.7 2010/04/24 01:58:18 dww Exp $ /** * @file * Code required for the issue node form. */ /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects (nid => title, grouped by project type // categories if any), and also get an array of project shortnames. $short_names = array(); $projects = project_projects_select_options($short_names); if (empty($projects)) { drupal_set_message(t('You do not have access to any projects.'), 'error'); // No reason to return a project selector form with no elements, so just // return an empty array for the form. return array(); } // See if there's only one project the user has access to, and if so, // redirect directly to the issue form for that project. if (count($short_names) == 1) { drupal_goto('node/add/project-issue/' . key($short_names)); } // Otherwise, return a form to select which project to submit an issue for. $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => array(t('<none>')) + $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Private helper to implement hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function _project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); - $priorities = project_issue_priority(); + $priorities = project_issue_priorities(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => check_markup($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => check_markup($project_help), '#suffix' => '</div>', ); } + $priority = $node->project_issue['priority'] ? $node->project_issue['priority'] : variable_get('project_issue_priority_default', 2); if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if (!empty($releases)) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), - '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, + '#default_value' => $priority, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'value', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } else { // If we're not allowing issue metadata changes, add all of these values // into the form so they show up in the $node->project_issue array during // validation and submit, so we're consistent with where they live. $form['project_issue'] = array('#tree' => TRUE); $form['project_issue']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if (isset($node->project_issue['rid'])) { $form['project_issue']['rid'] = array( '#type' => 'value', '#value' => $node->project_issue['rid'], ); } $form['project_issue']['component'] = array( '#type' => 'value', '#value' => $node->project_issue['component'], ); $form['project_issue']['category'] = array( '#type' => 'value', '#value' => $node->project_issue['category'], ); $form['project_issue']['priority'] = array( '#type' => 'value', - '#value' => $node->project_issue['priority'], + '#value' => $priority, ); $form['project_issue']['assigned'] = array( '#type' => 'value', '#value' => $node->project_issue['assigned'], ); $form['project_issue']['sid'] = array( '#type' => 'value', '#value' => $node->project_issue['sid'], ); } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Private helper to implement hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function _project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } /** * Private helper to implement hook_insert(). * * @param $node * Object containing form values from the project_issue node form. This is * NOT a fully loaded $node object, so the issue-related values are directly * in $node, not in the $node->project_issue array. */ function _project_issue_insert($node) { // Permanently store the original issue states in a serialized array. This // is a bit yucky, but we need them for proper handling of states workflow. // The current states need to be stored in {project_issues} as well for // query efficiency in issue queue searches, and it seems too messy to add a // bunch of new columns to the {project_issues} table for the original // states. $original_issue_data = new stdClass(); $fields = array( 'pid' => 0, 'rid' => 0, 'component' => '', 'category' => '', 'priority' => 0, 'assigned' => 0, 'sid' => 0, 'title' => '', ); foreach ($fields as $field => $default) { // Some of the incoming data may not have the correct default. if (empty($node->$field)) { $node->$field = $default; } $original_issue_data->$field = $node->$field; } - db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); + $priority_weight = db_result(db_query('SELECT weight FROM {project_issue_priority} WHERE priority = %d', $node->priority)); + + db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock, priority_weight) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0, $priority_weight); // Invalidate the "Issue cockpit" block cache for this project, since the // new issue will have altered the summary totals. cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); } - diff --git a/includes/mail.inc b/includes/mail.inc index 20097b3..12a710a 100644 --- a/includes/mail.inc +++ b/includes/mail.inc @@ -1,577 +1,577 @@ <?php -// $Id: mail.inc,v 1.125 2010/04/17 22:04:49 thehunmonkgroup Exp $ +// $Id: mail.inc,v 1.126 2010/04/24 01:58:18 dww Exp $ /** * @file * Project issue tracking email notifications system. */ /** * Implementation of hook_mailhandler(). */ function _project_issue_mailhandler($node, $result, $i, $header, $mailbox) { if ($node->type == 'project') { if (node_access('create', 'project_issue')) { $node->nid = preg_replace('/@.+/', '', $node->nid); if ($node->nid) { /* ** Base the new entry on the node it belongs to, this ensures all ** values are initially correct. */ $entry = node_load(array('nid' => $node->nid, 'type' => 'project_issue')); } // Possible attributes $fields = array( 'pid' => t('Project'), 'category' => t('Category'), 'component' => t('Component'), 'priority' => t('Priority'), 'rid' => t('Version'), 'assigned' => t('Assigned to'), 'sid' => t('Status') ); /* ** Only change the title if it doesn't have the old title in it. ** This should prevent the title from changing due to added ** prefixes. It may on occasion make false positives, but if ** a title change is that minor who cares? */ $entry->title = (strpos($node->title, $entry->title)) ? $entry->title : $node->title; $entry->teaser = $node->teaser; $entry->body = $node->body; $entry->uid = $node->uid; foreach ($fields as $var => $text) { $text = strtolower(str_replace(' ', '_', $text)); if (isset($node->project_issue[$text])) { $node->project_issue[$text] = trim($node->project_issue[$text]); switch ($var) { case 'pid': $project = node_load($node->project_issue[$text]); if ($project->nid) { $entry->project_issue['pid'] = $project->nid; } break; case 'category': if (($category = array_search($node->project_issue[$text], project_issue_category(0, 0)))) { $entry->project_issue['category'] = $category; } break; case 'priority': - if (($priority = array_search($node->project_issue[$text], project_issue_priority()))) { + if (($priority = array_search($node->project_issue[$text], project_issue_priorities()))) { $entry->project_issue['priority'] = $priority; } break; case 'rid': if ($entry->project_issue['pid'] && ($nid = db_result(db_query("SELECT nid FROM {project_release_nodes} WHERE pid = %d AND version = '%s'", $entry->project_issue['pid'], $node->project_issue[$text]), 0))) { $entry->project_issue['rid'] = $nid; } break; case 'assigned': if ($user = user_load(array('name' => $node->project_issue[$text]))) { $entry->project_issue['assigned'] = $user->uid; } break; case 'sid': if (($state = array_search($node->project_issue[$text], project_issue_state()))) { $entry->project_issue['sid'] = $state; } break; case 'component': if ($entry->project_issue['pid'] && ($project = node_load(array('nid' => $entry->project_issue['pid'], 'type' => 'project_project')))) { if ($project && in_array($node->project_issue[$text], $project->project_issue['components'])) { $entry->project_issue['component'] = $node->project_issue[$text]; } } break; } } } if (empty($entry->nid)) { $entry->sid = variable_get('project_issue_default_state', 1); $entry->type = 'project_issue'; $entry = node_validate($entry, $error); $error or ($entry->nid = node_save($entry)); } else { $error = project_comment_validate($entry); $error or project_comment_save($entry); } } else { $error['user'] = t('You are not authorized to access this page.'); } if ($error && $mailbox['replies']) { // Send the user his errors $mailto = mailhandler_get_fromaddress($header, $mailbox); $mailfrom = variable_get('site_mail', ini_get('sendmail_from')); $headers = array( 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', ); $body = t('You had some errors in your submission:'); foreach ($error as $field => $text) { $body .= "\n * $field: $text"; } drupal_mail('project_issue_mailhandler_error', $mailto, t('E-mail submission to !sn failed - !subj', array('!sn' => variable_get('site_name', 'Drupal'), '!subj' => $header->subject)), $body, $mailfrom, $headers); } // Return a NULL result so mailhandler doesn't save the node using the default methods. return NULL; } else { return $node; } } /** * preg_replace_callback() callback used for capturing URLs and transforming links * into footer links. */ function _project_issue_mail_url_callback($match = FALSE) { static $urls = array(); if (!empty($match) && is_array($match)) { $url = $match[2]; // If $url was an internal link, we need to strip the base_path // off before passing it to url(), to avoid doubling up on the base_path. // @todo Check that this actually works when using language specific url rewriting. $base_path = base_path(); $base_length = strlen($base_path); if (substr($url, 0, $base_length) == $base_path) { $url = substr($url, $base_length); } $urls[] = url($url, array('absolute' => TRUE)); return $match[3] .' ['. count($urls) .']'; } return $urls; } /** * Add a section to the email body. * Note: URL link numbers are not reset between calls to this function. */ function project_issue_mail_output(&$body, $html = 1, $format = FILTER_FORMAT_DEFAULT) { static $i = 0; if ($html) { $body = check_markup($body, $format, FALSE); // Convert inline links into footer links. //$pattern = '@<a +([^ >]+ )*?href *= *"([^>"]+?)"[^>]*>([^<]+?)</a>@i'; $pattern = '@<a[^>]*\shref\s*=\s*([\'"])([^>]+?)\1[^>]*>(.+?)</a>@is'; $body = preg_replace_callback($pattern, '_project_issue_mail_url_callback', $body); $urls = _project_issue_mail_url_callback(); if (count($urls)) { $body .= "\n"; for ($max = count($urls); $i < $max; $i++) { $body .= '['. ($i + 1) .'] '. $urls[$i] ."\n"; } } $body = preg_replace('!</?blockquote>!i', '"', $body); $body = preg_replace('!</?(em|i)>!i', '/', $body); $body = preg_replace('!</?(b|strong)>!i', '*', $body); $body = preg_replace("@<br />(?!\n)@i", "\n", $body); $body = preg_replace("@</p>(?!\n\n)@i", "\n\n", $body); $body = preg_replace("@<li>@i", "* ", $body); $body = preg_replace("@</li>\n?@i", "\n", $body); $body = strip_tags($body); $body = decode_entities($body); $body = wordwrap($body, 72); } else { $body = decode_entities($body); } } /** * Send mail notifications. */ function project_issue_mail_notify($nid) { global $user; if (defined('PROJECT_NOMAIL')) { return; } $node = node_load($nid, NULL, TRUE); // We don't want any notifications for unpublished nodes. if (empty($node) || !$node->status) { return; } $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); // Store a copy of the issue, so we can load the original issue values // below. $issue = drupal_clone($node); // Load in the original issue data here, since we want a running // reverse history. $original_issue_data = unserialize($node->project_issue['original_issue_data']); $fields = project_issue_field_labels('email'); foreach ($fields as $field => $label) { if ($field != 'name' && $field != 'updator') { $issue->original_issue_metadata->$field = $original_issue_data->$field; } } // Record users that are connected to this issue. $uids = array(); if (!empty($node->uid)) { $uids[$node->uid] = $node->uid; } if (!empty($node->project_issue['assigned'])) { $uids[$node->project_issue['assigned']] = $node->project_issue['assigned']; } // Create complete history of the bug report. $history = array($issue); $result = db_query('SELECT u.name, c.cid, c.nid, c.subject, c.comment, c.uid, c.format, pic.* FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid INNER JOIN {users} u ON u.uid = c.uid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp', $node->nid, COMMENT_PUBLISHED); while ($comment = db_fetch_object($result)) { $comment->comment = db_decode_blob($comment->comment); $comment->files = comment_upload_load_files($comment->cid); $history[] = $comment; // Record users that are connected to this issue. if ($comment->uid) { $uids[$comment->uid] = $comment->uid; } } if (count($uids)) { $placeholders = implode(',', array_fill(0, count($uids), '%d')); array_unshift($uids, $node->project_issue['pid']); $result = db_query("SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND (p.level = 2 OR (p.level = 1 AND u.uid IN ($placeholders)))", $uids); } else { $result = db_query('SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND p.level = 2', $node->project_issue['pid']); } // To save workload, check here if either the anonymous role or the // authenticated role has the 'view uploaded files' permission, since // we only need to process each user's file access permission if this // is NOT the case. $check_file_perms = !db_result(db_query("SELECT COUNT(*) FROM {permission} WHERE perm LIKE '%view uploaded files%' AND rid IN (%d, %d)", DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID)); // We need to determine if node_access() checks are necessary. The // check will be needed if any of the following is true: // 1. The node is not published. // 2. There is at least on node access control module enabled. // 3. Both the anonymous and authenticated user do not have // the 'access project issues' permission. $allowed_roles = user_roles(FALSE, 'access project issues'); if (isset($allowed_roles[DRUPAL_ANONYMOUS_RID]) || isset($allowed_roles[DRUPAL_AUTHENTICATED_RID])) { $anon_auth_access = TRUE; } $grants = module_implements('node_grants'); $check_node_access = $node->status != 1 || empty($anon_auth_access) || !empty($grants); $params['node'] = $node; $params['project'] = $project; $params['history'] = $history; $sender->name = t('!name (!site)', array('!name' => $user->name, '!site' => variable_get('site_name', 'Drupal'))); $sender->mail = strtr(variable_get('project_issue_reply_to', variable_get('site_mail', ini_get('sendmail_from'))), array('%project' => $project->project['uri'])); // The sender name is enclosed by double quotes below // to satisfy RFC2822 <http://www.faqs.org/rfcs/rfc2822.html>, // which requires double quotes when special characters (including // some punctuation) are used. See example in Appendix A.1.2. $from = '"' . mime_header_encode($sender->name) . "\" <$sender->mail>"; while ($recipient = db_fetch_object($result)) { // To save work, only go through a user_load if we need it. if ($check_file_perms || $check_node_access) { $account = user_load(array('uid' => $recipient->uid)); $language = user_preferred_language($account); } else { $language = language_default(); } $can_access = $check_node_access ? node_access('view', $node, $account) : TRUE; if ($can_access) { $display_files = $check_file_perms ? user_access('view uploaded files', $account) : TRUE; $params['display_files'] = $display_files; drupal_mail('project_issue', 'project_issue_update_notification', $recipient->mail, $language, $params, $from); } } if (is_array($project->project_issue['mail_copy_filter']) && count(array_filter($project->project_issue['mail_copy_filter'])) && !$project->project_issue['mail_copy_filter'][$node->project_issue['category']]) { return; } if (is_array($project->project_issue['mail_copy_filter_state']) && count(array_filter($project->project_issue['mail_copy_filter_state'])) && !$project->project_issue['mail_copy_filter_state'][$node->project_issue['sid']]) { return; } if (!empty($project->project_issue['mail_copy'])) { $params['display_files'] = TRUE; $message['body'][] = $links; $message['body'][] = project_issue_mail_generate_followup_mail_body($node, $history, TRUE); drupal_mail('project_issue', 'project_issue_update_notification', $project->project_issue['mail_copy'], language_default(), $params, $from); } } /** * Implementation of hook_mail(). */ function _project_issue_mail($key, &$message, $params) { global $base_url; switch ($key) { case "project_issue_update_notification": // There could be stale data in the cached node, so reset the cache. $node = $params['node']; $project = $params['project']; $history = $params['history']; $fields = project_issue_field_labels('email'); $domain = preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url); $message['headers'] += array( 'Date' => date('r'), 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', 'List-Id' => "$project->title <". $project->project['uri'] ."-issues-$domain>", 'List-Archive' => '<'. url('project/issues/'. $project->project['uri'], array('absolute' => TRUE)) .'>', 'List-Subscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>', 'List-Unsubscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>' ); // Comments exist, set headers accordingly. if (count($history) > 1) { foreach ($history as $comment) { // We need the most recent cid and the next most recent cid for the // message headers. Instead of issuing another query, just keep track // of them here. $previous_cid = isset($cid) ? $cid : ''; $cid = isset($comment->cid) ? $comment->cid : 0; } $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&cid=$cid&host=@$domain>"; $message['headers']['In-Reply-To'] = "<type=project&nid=$node->nid&host=@$domain>"; $message['headers']['References'] = "<type=project&nid=$node->nid&host=@$domain> <type=project&nid=$node->nid&cid=$previous_cid&host=@$domain> <type=project&nid=$node->nid&revcount=1&host=@$domain>"; } else { // Only original issue in this email. $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&host=@$domain>"; } project_issue_mail_output($node->title, 0); $message['subject'] = t('[!short_name] [!category] !title', array('!short_name' => $project->project['uri'], '!category' => $node->project_issue['category'], '!title' => $node->title)); // Create link to related node $links = t('Issue status update for !link', array('!link' => "\n". url("node/$node->nid", array('absolute' => TRUE)))) ."\n"; $links .= t('Post a follow up: !link', array('!link' => "\n". url("comment/reply/$node->nid", array('fragment' => 'comment-form', 'absolute' => TRUE)))) ."\n"; $message['body'][] = $links; $message['body'][] = project_issue_mail_generate_followup_mail_body($node, $history, $params['display_files']); break; case 'project_issue_critical_summary': $project = $params['project']; $message['headers'] += array( 'Date' => date('r'), 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', 'List-Id' => "$project->title <". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'-project-issues-digest>', 'List-Archive' => '<'. url('project/issues', array('query' => array('priorities' => '1'), 'absolute' => TRUE)) .'>', ); $message['subject'] = t('Release critical bugs for !date', array('!date' => date('F d, Y', time()))); $message['body'][] = $params['body']; break; case 'project_issue_reminder': $sender->name = variable_get('site_name', ''); $sender->mail = variable_get('site_mail', ''); $message['headers'] += array( 'Return-Path' => "<$sender->mail;>", 'Date' => date('r'), 'From' => "$sender->name <$sender->mail>", 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', 'List-Id' => "$sender->name <project-reminder-". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'>', 'List-Archive' => '<'. url('project', array('absolute' => TRUE)) .'>', ); $message['subject'] = t('Your submitted bugs for !date', array('!date' => date('F d, Y', time()))); $message['body'][] = $params['body']; break; } } /** * Format the body of an issue followup email. * * @param $node * The issue node. * @param $history * An array containing the history of issue followups. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A string of the email body. */ function project_issue_mail_generate_followup_mail_body($node, $history, $display_files) { global $user; static $output_with_files = NULL, $output_without_files = NULL; // Return cached output if available. if ($display_files) { if (isset($output_with_files)) { return $output_with_files; } } else { if (isset($output_without_files)) { return $output_without_files; } } // Get most recent update. $entry = array_pop($history); $node->project_issue['updator'] = $entry->name ? $entry->name : $user->name; // Check if the latest entry is actually the initial issue. if (empty($history)) { $metadata_previous = new stdClass(); // Have to get the metadata into the entry object. $metadata_entry = $entry->original_issue_metadata; $content = $entry->body; } else { $metadata_previous = end($history); // If the previous was the original issue, then we need to pull // out the metadata from project_issue. if (isset($metadata_previous->original_issue_metadata)) { $metadata_previous = $metadata_previous->original_issue_metadata; } $metadata_entry = $entry; $content = $entry->comment; } $fields = project_issue_field_labels('email'); $comment_changes = project_issue_metadata_changes($node, $metadata_previous, $metadata_entry, $fields); // Since $node->name will always be the original issue author, and since // $node->project_issue['updator'] isn't a property of either $previous or // $entry, these two properties will never show up as being different when // project_issue_metadata_changes() is called, and therefore neither of // these will ever be elements of the $comment_changes array. Since we do // want them to be printed in issue emails, we just need to add their labels // back into the $comment_changes array here, so that // theme_project_issue_mail_summary_field() will know to print the data for // these two fields. $comment_changes['name'] = array( 'label' => $fields['name'], ); $comment_changes['updator'] = array( 'label' => $fields['updator'], ); $summary = theme('project_issue_mail_summary', $entry, $node, $comment_changes, $display_files); // Create main body content project_issue_mail_output($content, 1, $entry->format); $body = "$content\n$entry->name\n"; $hr = str_repeat('-', 72); if (count($history)) { $body .= "\n\n"; $body .= t('Original issue:') ."\n"; $body .= project_issue_mail_format_entry(array_shift($history), $display_files, TRUE); if (count($history)) { $body .= "\n". t('Previous comments (!count):', array('!count' => count($history))) ."\n"; foreach ($history as $entry) { $body .= project_issue_mail_format_entry($entry, $display_files); } } } $output = "$summary\n$body"; // Set cached output. if ($display_files) { $output_with_files = $output; } else { $output_without_files = $output; } return $output; } /** * Themes the display of the issue metadata summary * that is shown at the top of an issue email. * * @param $entry * The object representing the current entry. This will be a node object * if the current entry is the original issue node; otherwise this will be * a comment object. * @param $node * The original issue node object. * @param $changes * A nested array containing the metadata changes between the original * issue and the first comment, or two consecutive comments. This array * is the output of the project_issue_metadata_changes() function. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A string containing the themed text of the issue metadata table. */ function theme_project_issue_mail_summary($entry, $node, $changes, $display_files) { // Mail summary (status values). $summary = ''; foreach ($changes as $field => $change) { $summary .= theme('project_issue_mail_summary_field', $node, $field, $change); } $summary .= project_issue_mail_format_attachments($entry, $display_files); return $summary; } /** * Theme the email output of one project issue metadata field. * * @param $node * The project issue node object. * @param $field_name * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * A themed line or lines of text ready for inclusion into the email body. */ function theme_project_issue_mail_summary_field($node, $field_name, $change) { // We need to run the label name through strip_tags here so that // the spacing isn't messed up if there are HTML tags in $change['label']. $text = str_pad(strip_tags($change['label']). ':', 14); $summary_row = ''; if (!empty($change['label']) && isset($change['old']) && isset($change['new']) && $field_name != 'updator' && $field_name != 'name') { if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])) { foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { diff --git a/issue.inc b/issue.inc index d3776b3..cf21e91 100644 --- a/issue.inc +++ b/issue.inc @@ -1,368 +1,398 @@ <?php -// $Id: issue.inc,v 1.354 2009/06/18 03:28:55 dww Exp $ +// $Id: issue.inc,v 1.355 2010/04/24 01:58:18 dww Exp $ /** * JS callback method to return updated elements on the issue form. * This function is called when someone changes the "Project" selector. */ function project_issue_update_project() { $form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); // Rebuild the form and cache it again. $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); // These used to be path arguments. Now they arrive via form element. $issue_nid = $form['nid']['#value']; $pid = $form_state['values']['project_info']['pid']; $rid = isset($form_state['values']['project_info']['rid']) ? $form_state['values']['project_info']['rid'] : 0; $cid = $form_state['values']['cid']; $assigned_uid = $form_state['values']['project_info']['assigned']; $project_info = $form['original_issue']['project_info']; // Only generate release stuff if the project_release module is enabled. if (module_exists('project_release')) { $project->nid = $pid; if ($releases = project_release_get_releases($project, 0)) { $old_version = db_result(db_query("SELECT version FROM {project_release_nodes} WHERE nid = %d", $rid)); $releases = array(t('<none>')) + $releases; // Since the value of releases is by nid, try to match release // based on the label instead. $default = 0; foreach ($releases as $key => $label) { if ($old_version == $label) { $default = $key; } } // Element is tree'd here to match the original form layout. $project_info['#tree'] = TRUE; $project_info['rid']['#options'] = $releases; $project_info['rid']['#disabled'] = FALSE; if (!empty($default)) { $project_info['rid']['#value'] = $default; $project_info['rid']['#default_value'] = $default; } } else { $project_info['rid']['#disabled'] = TRUE; $project_info['rid']['#options'] = array(); } } // Assigned. if (is_numeric($issue_nid)) { $issue = node_load(array('nid' => $issue_nid, 'type' => 'project_issue')); } else { // @TODO: This case should not ever be hit until // http://drupal.org/node/197281 lands. $issue = new stdClass; } $issue->project_issue['pid'] = $pid; $assigned_choices = project_issue_assigned_choices($issue); $project_info['assigned']['#default_value'] = $assigned_uid; $project_info['assigned']['#options'] = $assigned_choices; // Components. $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $pid)); $components = array(); if ($project->components) { $components = array(t('<none>')); foreach (unserialize($project->components) as $component) { $component = check_plain($component); $components[$component] = $component; } } $project_info['component']['#default_value'] = $cid; $project_info['component']['#options'] = $components; // Build the HTML output for the component select. $output = theme('status_messages') . drupal_render($project_info); drupal_json(array('status' => TRUE, 'data' => $output)); exit; } /** * Build an array of users to whom an issue may be assigned. * * @param $issue * The fully loaded issue node object. * @return * A keyed array in the form uid => name containing users * to whom an issue may be assigned. */ function project_issue_assigned_choices($issue) { // Setup the array of choices for who the issue is assigned to. $assigned = array(); foreach (module_implements('project_issue_assignees') as $module) { $function = "{$module}_project_issue_assignees"; $function($assigned, $issue); } natcasesort($assigned); $assigned = array(0 => empty($issue->project_issue['assigned']) ? t('Unassigned') : t('Unassign')) + $assigned; return $assigned; } /** * Implementation of hook_project_issue_assignees(). * * This hook is used to modify the list of 'Assigned' users when creating or * commenting on an issue. * * @param $assigned * An array of key => value pairs in the format of uid => name that represents * the list of users that the issue may be assigned to. This parameter * is passed by reference so the hook may make changes, such as adding or * removing elements. * @param $node * The node object for the issue. */ function project_issue_project_issue_assignees(&$assigned, $node) { global $user; if ($user->uid) { if (isset($node->project_issue['assigned']) && $user->uid != $node->project_issue['assigned']) { // Assigned to someone else, add the currently assigned user. $account = user_load(array('uid' => $node->project_issue['assigned'])); $assigned[$node->project_issue['assigned']] = $account->name; } // Always let the person replying assign it to themselves. $assigned[$user->uid] = $user->name; } if (user_access('assign and be assigned project issues')) { // All users are included if either anon or auth user has the perm. if (db_result(db_query("SELECT rid FROM {permission} WHERE perm LIKE '%%%s%%' AND rid IN(%d, %d)", 'assign and be assigned project issues', DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $result = db_query("SELECT uid, name FROM {users}"); } else { $result = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {role} r ON ur.rid = r.rid INNER JOIN {permission} p ON p.rid = r.rid WHERE p.perm LIKE '%%%s%%'", 'assign and be assigned project issues'); } while ($assignee = db_fetch_object($result)) { $assigned[$assignee->uid] = $assignee->name; } } } // Support stuff /** * Return information about project issue state values. * * @param $sid * Integer state id to return information about, or 0 for all states. * @param $restrict * Boolean to determine if states should be restricted based on the * permissions of the current user or $account if that parameter * is provided. * @param $is_author * Boolean that indicates if the current user is the author of the * issue, which can potentially grant a wider selection of states. * @param $current_sid * The current integer state id for the issue. * @param $defaults * Boolean to request the states used for default issue queries. * @param $account * Account of a user to pass to user_access() for access checking. * This parameter will have no effect unless $restrict is also * set to TRUE. * * @return * An array of states (sid as key, name as value) that match the * given filters, or the name of the requested state. * NOTE: The state name returned is raw text, and should be filtered via * check_plain() or filter_xss() before being printed as HTML output. */ function project_issue_state($sid = 0, $restrict = false, $is_author = false, $current_sid = 0, $defaults = false, $account = NULL) { static $options; if (!$options) { $result = db_query('SELECT * FROM {project_issue_state} ORDER BY weight'); while ($state = db_fetch_object($result)) { $options[] = $state; } } foreach($options as $state) { if ($restrict) { // Check if user has access, // or if status is default status and therefore available to all, // or if user is original issue author and author has access, // or if the issue is already in a state, even if the user doesn't have // access to that state themselves. if (user_access('set issue status '. str_replace("'", "", $state->name), $account) || user_access('administer projects', $account) || ($state->sid == variable_get('project_issue_default_state', 1)) || ($state->author_has && $is_author) || ($state->sid == $current_sid) ) { $states[$state->sid] = $state->name; } } else if ($defaults) { if ($state->default_query) { $states[$state->sid] = $state->name; } } else { $states[$state->sid] = $state->name; } } return $sid ? $states[$sid] : $states; } /** * Return an array of state ids that should be used for default queries. */ function project_issue_default_states() { static $defaults; if (empty($defaults)) { $states = project_issue_state(0, false, false, 0, true); $defaults = !empty($states) ? array_keys($states) : array(1, 2, 4); } return $defaults; } -function project_issue_priority($priority = 0) { - $priorities = array(1 => t('critical'), t('normal'), t('minor')); - return $priority ? $priorities[$priority] : $priorities; +/** + * Return all available issue priorities, sorted by weight. + * + * @return + * An array of priorities keyed by id. + */ +function project_issue_priorities() { + static $priorities; + if (!isset($priorities)) { + $result = db_query('SELECT priority, name FROM {project_issue_priority} ORDER BY weight'); + while ($object = db_fetch_object($result)) { + $priorities[$object->priority] = $object->name; + } + } + return $priorities; +} + +/** + * Return the name of a priority for a given id. + * + * @param $priority + * The id of the priority. + * @return + * The name of the priority. + */ +function project_issue_priority($priority) { + $priorities = project_issue_priorities(); + if ($priority && array_key_exists($priority, $priorities)) { + return $priorities[$priority]; + } + else { + return t('[deleted priority]'); + } } function project_issue_category($category = 0, $plural = 1) { if ($plural) { $categories = array('bug' => t('bug reports'), 'task' => t('tasks'), 'feature' => t('feature requests'), 'support' => t('support requests')); } else { $categories = array('bug' => t('bug report'), 'task' => t('task'), 'feature' => t('feature request'), 'support' => t('support request')); } return $category ? $categories[$category] : $categories; } function project_issue_count($pid) { $state = array(); $result = db_query('SELECT p.sid, count(p.sid) AS count FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid WHERE n.status = 1 AND p.pid = %d GROUP BY p.sid', $pid); while ($data = db_fetch_object($result)) { $state[$data->sid] = $data->count; } return $state; } /** * Return the HTML to use for the links at the top of issue query pages. * * @param $links * Array of links, indexed by the action ('create', 'search', etc). * * @see project_issue_query_result() * @see theme_links() */ function theme_project_issue_query_result_links($links) { return theme('links', $links); } /** * Provide an array of project issue summary fields. * @param $context * The context in which the fields will be displayed. * 'web' for project_issue node and comment summary tables. * 'email' for project_issue notification e-mail messages. */ function project_issue_field_labels($context) { if ($context == 'web') { $labels = array('title' => t('Title')); } else { $labels = array(); } $labels += array( 'pid' => t('Project'), 'rid' => t('Version'), 'component' => t('Component'), 'category' => t('Category'), 'priority' => t('Priority'), 'assigned' => t('Assigned to'), 'sid' => t('Status'), ); if ($context == 'email') { $labels += array( 'name' => t('Reported by'), 'updator' => t('Updated by'), ); } return $labels; } /** * Provide the text displayed to a user for a specific metadata field. * * @param $field * Name of the field. * @param $value * Value of the field. * * @return * Text to display to user. NOTE: This is unfiltered text! If this output is * being sent over the web, you must use check_plain(). */ function project_issue_change_summary($field, $value) { switch ($field) { case 'pid': $project = node_load(array('nid' => $value, 'type' => 'project_project')); return $project->title; case 'category': return $value ? project_issue_category($value, 0) : t('<none>'); case 'priority': return $value ? project_issue_priority($value) : t('<none>'); case 'rid': if ($value) { $release->nid = $value; if (module_exists('project_release')) { $release = project_release_load($release); } else { $release->project_release['version'] = t('Unknown'); } return $release->project_release['version']; } return t('<none>'); case 'assigned': $user = user_load(array('uid' => $value)); return (int) $value === 0 ? variable_get('anonymous', t('Anonymous')) : $user->name; case 'sid': return $value ? project_issue_state($value) : t('<none>'); default: return $value; } } function theme_project_issue_create_forbidden($uri = '') { global $user; if ($user->uid) { return ''; } // We cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages. $destination = "destination=". drupal_urlencode("node/add/project-issue/$uri"); if (variable_get('user_register', 1)) { return t('<a href="@login">Login</a> or <a href="@register">register</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination)))); } else { return t('<a href="@login">Login</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)))); } } diff --git a/project_issue.install b/project_issue.install index 4c5d7bb..1222180 100644 --- a/project_issue.install +++ b/project_issue.install @@ -1,448 +1,538 @@ <?php -// $Id: project_issue.install,v 1.64 2009/08/21 22:51:31 dww Exp $ +// $Id: project_issue.install,v 1.65 2010/04/24 01:58:18 dww Exp $ /** * Implementation of hook_schema(). */ function project_issue_schema() { $schema['project_issue_projects'] = array( 'description' => 'Table containing per-project issue-related settings.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {project_projects}.nid of the project.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'issues' => array( 'description' => 'Boolean value indicating whether or not issue-tracking is enabled for this project.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'components' => array( 'description' => 'A serialized array defining the components for this project.', 'type' => 'text', 'not null' => FALSE, ), 'default_component' => array( 'description' => 'The default component for new issues of this project, or an empty string if the user needs to select a component.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'help' => array( 'description' => 'Submission guidelines for issues added to this project.', 'type' => 'text', 'not null' => FALSE, ), 'mail_digest' => array( 'description' => 'E-mail address for the weekly critical issues report.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy' => array( 'description' => 'E-mail address to send a copy of all issues to.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter' => array( 'description' => 'A serialized array containing the types of issues to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter_state' => array( 'description' => 'A serialized array containing the statuses to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_reminder' => array( 'description' => 'Boolean indicating whether or not users with open issues should receive a monthly reminder.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('nid'), ); $schema['project_issues'] = array( 'description' => 'The base table for issues.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {node}.nid of this project_issue node.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'category' => array( 'description' => 'Category of the issue.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'component' => array( 'description' => 'Component of the issue as defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( - 'description' => 'The priority for this issue.', + 'description' => 'Current {project_issue_priority}.priority of this issue.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), + 'priority_weight' => array( + 'description' => 'The denormalized weight from {project_issue_priority}.weight.', + 'type' => 'int', + 'size' => 'tiny', + 'not null' => TRUE, + 'default' => 0, + ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) for this issue (only used in conjunction with the project_release module).', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue is currently assigned.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'Current {project_issue_state}.sid of this issue.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'original_issue_data' => array( 'description' => 'A serialized object containing the original metadata values that were used when this issue was created.', 'type' => 'text', 'not null' => TRUE, ), 'last_comment_id' => array( 'description' => '{comments}.cid of the most recent comment added to the issue. 0 if no comment has been added yet.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'db_lock' => array( 'description' => 'Row-lock indicator to prevent race conditions when determining sequential comment number (http://drupal.org/node/180866).', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_issues_pid' => array('pid'), 'project_issues_sid' => array('sid'), 'project_issues_nid_assigned' => array('nid', 'assigned'), ), 'primary key' => array('nid'), ); $schema['project_issue_comments'] = array( 'description' => 'The base table for comments added to issues.', 'fields' => array( 'nid' => array( 'description' => 'References {project_issues}.nid, the issue to which this comment was added.', 'type' => 'int', 'not null' => FALSE, ), 'cid' => array( 'description' => 'Primary Key: The {comments}.cid for this comment.', 'type' => 'int', 'not null' => FALSE, ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) after this comment was made (only used in conjunction with the project_release module).', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'component' => array( 'description' => 'Component of the issue after this comment was made. Components are defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'category' => array( 'description' => 'Category of this issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( - 'description' => 'The priority for this issue after this comment was made.', + 'description' => 'The {project_issue_priority}.priority of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue was assigned after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'The {project_issue_state}.sid of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs after this comment was made.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'title' => array( 'description' => 'The title of the issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, ), 'timestamp' => array( 'description' => 'Timestamp for this comment.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, ), 'comment_number' => array( 'description' => 'The sequential number for this comment in the issue.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('cid'), 'indexes' => array( 'nid_timestamp' => array('nid', 'timestamp'), 'comment_number' => array('comment_number'), ), ); + $schema['project_issue_priority'] = array( + 'description' => 'The available options for the priority values for issues.', + 'fields' => array( + 'priority' => array( + 'description' => 'Primary Key: Unique id for this priority.', + 'type' => 'serial', + 'not null' => TRUE, + ), + 'name' => array( + 'description' => 'Display-friendly name for this priority.', + 'type' => 'varchar', + 'length' => 64, + 'not null' => TRUE, + 'default' => '', + ), + 'weight' => array( + 'description' => 'Weight for this priority, used when ordering issues by priority. Denormalized into {project_issues}.priority_weight.', + 'type' => 'int', + 'size' => 'tiny', + 'not null' => TRUE, + 'default' => 0, + ), + ), + 'primary key' => array('priority'), + ); + $schema['project_subscriptions'] = array( 'description' => 'Table keeping track of per-user project_issue subscriptions.', 'fields' => array( 'nid' => array( 'description' => '{project_projects}.nid of the project to which the user is subscribed.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'uid' => array( 'description' => 'The {users}.uid for this subscriber.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'level' => array( 'description' => 'The type of subscription for the project. Possible values are: 0 = not subscribed, 1 = subscribed to own issues or 2 = subscribed to all issues.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_subscriptions_nid_uid_level' => array('nid', 'uid', 'level'), ), ); $schema['project_issue_state'] = array( 'description' => 'Table that holds all possible values for issue statuses.', 'fields' => array( 'sid' => array( 'description' => 'Primary Key: Unique id for this status.', 'type' => 'serial', 'unsigned' => 1, 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this status.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this status, used when ordering statuses', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'author_has' => array( 'description' => 'Boolean indicating whether or not the author of an issue may use this issue status in that issue, regardless of the permissions controlling site-wide use of this status.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'default_query' => array( 'description' => 'Boolean indicating whether or not issues with this status are included in default queries.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('sid'), ); return $schema; } function project_issue_install() { // We need to check this before we try to create the table, so that // if it already exists, we don't attempt to insert our own values. $project_issue_state_existed = db_table_exists('project_issue_state'); // Create tables. drupal_install_schema('project_issue'); if (!$project_issue_state_existed) { // sid, name, weight, author-can-set, in-default-queries project_issue_init_state(1, 'active', -13, 0, 1); project_issue_init_state(2, 'fixed', 1, 0, 1); project_issue_init_state(3, 'duplicate', 4, 0, 0); project_issue_init_state(4, 'postponed', 6, 0, 1); project_issue_init_state(5, "won't fix", 9, 0, 0); project_issue_init_state(6, 'by design', 11, 0, 0); project_issue_init_state(7, 'closed', 13, 1, 0); project_issue_init_state(8, 'needs review', -8, 0, 0); project_issue_init_state(13, 'needs work', -6, 0, 0); project_issue_init_state(14, 'ready to commit', -2, 0, 0); // Since we're hacking in auto-increment values here, // update the sequence value for Postgres -- ugly but necessary for now. if ($GLOBALS['db_type'] == 'pgsql') { db_query("SELECT setval('project_issue_state_sid_seq', 14)"); } } project_issue_add_missing_projects(); db_query("UPDATE {system} SET weight = 2 WHERE name = 'project_issue'"); // Set up future followups to be read/write. if (module_exists('comment')) { variable_set('comment_project_issue', COMMENT_NODE_READ_WRITE); } // Enable file attachments for followups. variable_set('comment_upload_project_issue', 1); // Enable file attachments for issues. variable_set('upload_project_issue', 1); + db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (1, 'critical', 1)"); + db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (2, 'normal', 2)"); + db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (3, 'minor', 3)"); } /** * Implementation of hook_uninstall(). */ function project_issue_uninstall() { // Remove tables. drupal_uninstall_schema('project_issue'); $variables = array( 'project_issue_default_state', 'project_directory_issues', 'project_reply_to', 'project_issue_digest_last', 'project_issue_cockpit_categories', 'project_issue_digest_interval', 'project_issue_reminder_last', 'project_issue_reminder_interval', 'project_issue_show_comment_signatures', 'project_issue_site_help', 'project_issue_invalid_releases', 'project_issue_followup_user', 'project_issue_hook_cron', ); foreach ($variables as $variable) { variable_del($variable); } } function project_issue_enable() { project_issue_add_missing_projects(); } /** * Initialize a given issue state in the database. */ function project_issue_init_state($sid, $name, $weight, $author, $query) { db_query("INSERT INTO {project_issue_state} (sid, name, weight, author_has, default_query) VALUES (%d, '%s', %d, %d, %d)", $sid, $name, $weight, $author, $query); } /** * Check for existing project nodes that do not have an entry in the * {project_issue_projects} table, and add them. * */ function project_issue_add_missing_projects() { $projects = db_query("SELECT n.nid, pip.nid AS pip_nid FROM {node} n LEFT JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.type = 'project_project' AND pip.nid IS NULL"); while ($project = db_fetch_object($projects)) { db_query('INSERT INTO {project_issue_projects} (nid) VALUES (%d)', $project->nid); } } /** * Remove stale setting that's now provided by views. */ function project_issue_update_6000() { variable_del('project_issues_per_page'); return array(); } /** * Add the 'default_component' field to {project_issue_projects}. */ function project_issue_update_6001() { $ret = array(); db_add_field($ret, 'project_issue_projects', 'default_component', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '')); return $ret; } /** * Make {project_issue_comments}.cid the primary key for that table. */ function project_issue_update_6002() { $ret = array(); db_add_primary_key($ret, 'project_issue_comments', array('cid')); if (empty($ret[0]['success'])) { return array(array('success' => TRUE, 'query' => '<strong>' . t("It is safe to ignore warnings about 'Multiple primary key defined'.") . '</strong>')); } return $ret; } +/** + * Add table for project_issue_priority, and insert default values. + */ +function project_issue_update_6003() { + $ret = array(); + $table = array( + 'description' => 'The issue priorities.', + 'fields' => array( + 'priority' => array( + 'description' => 'Primary Key: Unique id for this priority.', + 'type' => 'serial', + 'not null' => TRUE, + ), + 'name' => array( + 'description' => 'Display-friendly name for this priority.', + 'type' => 'varchar', + 'length' => 64, + 'not null' => TRUE, + 'default' => '', + ), + 'weight' => array( + 'description' => 'Weight for this priority, used when ordering issues by priority. Denormalized into {project_issues}.priority_weight.', + 'type' => 'int', + 'size' => 'tiny', + 'not null' => TRUE, + 'default' => 0, + ), + ), + 'primary key' => array('priority'), + ); + db_create_table($ret, 'project_issue_priority', $table); + db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (1, 'critical', 1)"); + db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (2, 'normal', 2)"); + db_query("INSERT INTO {project_issue_priority} (priority, name, weight) VALUES (3, 'minor', 3)"); + + db_add_field($ret, 'project_issues', 'priority_weight', array('type' => 'int', 'not null' => TRUE, 'default' => '0', 'size' => 'tiny')); + return $ret; +} + +/** + * Update {project_issues} with denormalized priority weight. + */ +function project_issue_update_6004(&$sandbox) { + $ret = array(); + // Reconstruct a batch context. + $context = array('sandbox' => &$sandbox); + // Load the include. + require_once drupal_get_path('module', 'project_issue') .'/includes/admin.batch_confirm.inc'; + // Call the batch upgrade which will set its variables in the sandbox. + _project_issue_batch_update('UPDATE {project_issues} SET priority_weight = priority WHERE nid BETWEEN %d AND %d', array(), $context); + // Pass back progress. + $ret['#finished'] = $context['finished']; + return $ret; +} diff --git a/project_issue.module b/project_issue.module index 82ec909..a1f42b9 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,837 +1,864 @@ <?php -// $Id: project_issue.module,v 1.179 2010/04/22 09:34:54 dww Exp $ +// $Id: project_issue.module,v 1.180 2010/04/24 01:58:18 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); + // Administrative pages + $items['admin/project/project-issue-priority'] = array( + 'title' => 'Project issue priority options', + 'description' => 'Configure what issue priorities should be used on your site.', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('project_issue_admin_priority_form'), + 'access arguments' => array('administer projects'), + 'weight' => 1, + 'type' => MENU_NORMAL_ITEM, + 'file' => 'includes/admin.issue_priority.inc', + ); + $items['admin/project/project-issue-priority/delete'] = array( + 'title' => 'Delete', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('project_issue_delete_priority_confirm', 4), + 'access arguments' => array('administer projects'), + 'type' => MENU_CALLBACK, + 'file' => 'includes/admin.issue_priority.inc' + ); + + // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), + 'project_issue_admin_priority_form' => array( + 'file' => 'includes/admin.issue_priority.inc', + 'arguments' => array( + 'form' => NULL, + ), + ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = !empty($changes['uid']) ? $changes['uid'] : $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': module_load_include('inc', 'project_issue', 'includes/project_node'); project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implementation of hook_mail(). (stub function) */ function project_issue_mail($key, &$message, $params) { module_load_include('inc', 'project_issue', 'includes/mail'); return _project_issue_mail($key, $message, $params); } /** * Implementation of hook_mailhandler(). (stub function) */ function project_issue_mailhandler($node, $result, $i, $header, $mailbox) { module_load_include('inc', 'project_issue', 'includes/mail'); return _project_issue_mailhandler($node, $result, $i, $header, $mailbox); } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implement hook_delete() for project issue nodes. */ function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } /** * Implement hook_form() for project issue nodes. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_form($node, $form_state, $include_metadata_fields); } /** * Implement hook_validate() for project issue nodes. */ function project_issue_validate($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_validate($node); } /** * Implement hook_insert() for project issue nodes. */ function project_issue_insert($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_insert($node); } /** * Implement hook_view() for project issue nodes. */ function project_issue_view($node, $teaser = FALSE, $page = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_view'); return _project_issue_view($node, $teaser, $page); } /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * @@ -1261,513 +1288,512 @@ function project_issue_requirements($phase) { } /** * Implement hook_token_list() (from token.module). */ function project_issue_token_list($type) { if ($type == 'node') { $tokens['node'] = array( 'project_issue_pid' => t("The issue's project nid"), 'project_issue_project_title' => t("The issue's project title"), 'project_issue_project_title-raw' => t("The issue's project title raw"), 'project_issue_project_shortname' => t("The issue's project short name"), 'project_issue_category' => t("The issue's category (bug, feature)"), 'project_issue_component' => t("The issue's component"), 'project_issue_priority' => t("The issue's priority"), 'project_issue_version' => t("The issue's version (if any)"), 'project_issue_assigned' => t("The name of the user an issue is assigned to"), 'project_issue_status' => t("The issue's status"), ); return $tokens; } } /** * Implement hook_token_values() (from token.module). */ function project_issue_token_values($type = 'all', $object = NULL) { if ($type == 'node') { // Defaults in case it's not an issue or we can't load its parent project. $values = array( 'project_issue_pid' => '', 'project_issue_project_title' => '', 'project_issue_project_title-raw' => '', 'project_issue_project_shortname' => '', 'project_issue_category' => '', 'project_issue_component' => '', 'project_issue_priority' => '', 'project_issue_version' => '', 'project_issue_assigned' => '', 'project_issue_status' => '', ); if ($object->type == 'project_issue') { if (!empty($object->project_issue)) { // If $node->project_issue exists, use it. $issue = (object)$object->project_issue; } else { $issue = $object; } if ($project = node_load($issue->pid)) { $values['project_issue_pid'] = intval($issue->pid); $values['project_issue_project_title'] = check_plain($project->title); $values['project_issue_project_title-raw'] = $project->title; $values['project_issue_project_shortname'] = check_plain($project->project['uri']); } if (module_exists('project_release') && !empty($issue->rid) && $release = node_load($issue->rid)) { $values['project_issue_version'] = check_plain($release->project_release['version']); } if (!empty($issue->assigned)) { $account = user_load($issue->assigned); $values['project_issue_assigned'] = check_plain($account->name); } $values['project_issue_category'] = project_issue_category($issue->category, FALSE); $values['project_issue_component'] = check_plain($issue->component); $values['project_issue_priority'] = project_issue_priority($issue->priority); $values['project_issue_status'] = check_plain(project_issue_state($issue->sid)); } return $values; } } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } $variables['class'] .= " project-issue"; } } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( 'info' => t('Issue cockpit'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, ); return $form; } elseif ($op == 'save' && $delta == 'issue_cockpit') { variable_set('project_issue_cockpit_categories', $edit['project_issue_cockpit_categories']); // Invalidate the cache for this block since the categories might change. cache_clear_all('project_issue_cockpit_block:', 'cache', TRUE); } elseif ($op == 'view' && ($node = project_get_project_from_menu()) && !empty($node->project_issue['issues']) && node_access('view', $node)) { $cid = 'project_issue_cockpit_block:'. $node->nid; if (($cache = cache_get($cid))) { $block = $cache->data; } else { module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); $block = array( 'subject' => t('Issues for @project', array('@project' => $node->title)), 'content' => theme('project_issue_issue_cockpit', $node), ); cache_set($cid, $block); } return $block; } } /** * Implemenation of hook_project_page_link_alter(). * * Add project_issue-specific links to the array of project links. */ function project_issue_project_page_link_alter(&$links, $node) { // TODO: Assumes "patch" issue status values (http://drupal.org/node/27865). // Prepend a link to the development section to view pending patches. if (!empty($node->project['uri'])) { $patches['pending_patches'] = l(t('View pending patches'), 'project/issues/search/'. $node->project['uri'], array('query' => 'status[]=8&status[]=13&status[]=14')); $links['development']['links'] = $patches + $links['development']['links']; } } - diff --git a/project_issue.test b/project_issue.test index 910a573..32b165b 100644 --- a/project_issue.test +++ b/project_issue.test @@ -1,185 +1,377 @@ <?php -// $Id: project_issue.test,v 1.3 2010/04/20 22:22:06 dww Exp $ +// $Id: project_issue.test,v 1.4 2010/04/24 01:58:18 dww Exp $ include_once drupal_get_path('module', 'project') . '/project.test'; class ProjectIssueWebTestCase extends ProjectWebTestCase { function setUp() { // Setup the required modules for all tests. $modules = func_get_args(); $modules = array_merge(array('project_issue', 'views', 'comment', 'comment_upload', 'upload'), $modules); // We can't call parent::setUp() with a single array argument, so we need // this ugly call_user_func_array(). call_user_func_array(array($this, 'parent::setUp'), $modules); variable_set('comment_preview_project_issue', FALSE); } /** * Create an Issue node. * * @param stdClass $project * A project node. * @param array $edit * An array of form values, passed to drupalPost. Optional * @return * An issue node. */ function createIssue($project, $edit = array()) { // If people are lazy and don't want to specify any of these, provide a // default. $edit += array( 'title' => $this->randomName(8), 'body' => $this->randomName(64), 'component' => 'Code', 'category' => 'bug', ); $this->drupalPost('node/add/project-issue/' . $project->project['uri'], $edit, t('Save')); $this->assertRaw(t('!post %title has been created.', array('!post' => 'Issue', '%title' => $edit["title"])), t('Issue created.')); return $this->drupalGetNodeByTitle($edit['title']); } function createIssueComment($issue, $edit = array()) { $edit += array('comment' => $this->randomName(64)); $this->drupalPost('comment/reply/' . $issue->nid, $edit, t('Save')); return $edit; } /** * Make sure issue metadata matches up to what it's intended to be. * * @param array $metadata * Associative array of expected issue metadata field names and values. * @param $nid * Optional integer node ID of the issue to check metadata fields for. */ - function assertIssueMetadata($metadata, $nid = NULL) { + function assertIssueMetadata($metadata, $nid = NULL, $message = NULL) { $pass = TRUE; if ($nid) { $this->drupalGet('node/' . $nid); } + if (!$message) { + $message = t('Issue metadata matches'); + } foreach ($this->xpath("//div[@id='project-issue-summary-table']/table//tr") as $row) { $key = strtolower(trim((string)$row->td[0], ':')); if (isset($metadata[$key])) { if (strtolower($metadata[$key]) != strtolower((string)$row->td[1])) { $pass = FALSE; } } } if ($pass) { - $this->pass(t('Issue metadata matches')); + $this->pass($message); } else { - $this->fail(t('Issue metadata matches')); + $this->fail($message); } } } class ProjectIssueCreationTestCase extends ProjectIssueWebTestCase { protected $maintain_user; public static function getInfo() { return array( 'name' => 'Project issue creation', 'description' => 'Test creating an issue.', 'group' => 'Project Issue', ); } function setUp() { parent::setUp(); $this->maintain_user = $this->drupalCreateUser(array('maintain projects', 'create project issues', 'access project issues', 'access projects')); $this->drupalLogin($this->maintain_user); } /** * Test the creation of project issues and the display of issue properties. */ function testProjectIssueCreation() { $project = $this->createProject(); // Test project issue node form fields. $this->drupalGet('node/add/project-issue/' . $project->project['uri']); $this->assertText(t('Create Issue')); $issue = $this->createIssue($project, array( 'component' => 'Miscellaneous', 'category' => 'feature', 'priority' => 1, 'assigned' => $this->maintain_user->uid, )); $this->assertText($issue->title, t('Title found')); $this->assertText($issue->body, t('Body found')); $issue = $this->createIssue($project, array( 'component' => 'Miscellaneous', 'category' => 'feature', 'priority' => 1, 'assigned' => $this->maintain_user->uid, )); $this->assertIssueMetadata(array( 'component' => 'Miscellaneous', 'category' => 'feature request', 'priority' => 'critical', 'assigned' => $this->maintain_user->name, )); } } class ProjectIssueCommentTestCase extends ProjectIssueWebTestCase { public static function getInfo() { return array( 'name' => 'Project issue comment', 'description' => 'Test commenting on an issue.', 'group' => 'Project Issue', ); } function setUp() { parent::setUp(); $maintain_user = $this->drupalCreateUser(array('maintain projects', 'create project issues', 'access project issues', 'access projects')); $this->drupalLogin($maintain_user); } /** * Test the creation of issue metadata. */ function testProjectIssueMetadata() { $project = $this->createProject(); // Test project issue node form fields. $issue = $this->createIssue($project); $html = $this->drupalGet('comment/reply/' . $issue->nid); $this->parse(); // Let's iterate over all the forms. $forms = $this->xpath('//form'); $form = $forms[0]; // We try to set the fields of this form as specified in $edit. $post = $upload = $edit = array(); $this->handleForm($post, $edit, $upload, NULL, $form); $map = array( 'priority' => 'priority', 'category' => 'category', 'component' => 'project_info[component]', 'assigned' => 'project_info[assigned]', 'pid' => 'project_info[pid]', ); foreach ($map as $issue_key => $post_key) { - $this->assertEqual($issue->project_issue[$issue_key], $post[$post_key], t('Making sure comment form is correct')); + $this->assertEqual($issue->project_issue[$issue_key], $post[$post_key], t('Making sure comment form is correct.')); } } /** * Test the creation of issue comments. */ function testProjectIssueComment() { $project = $this->createProject(); // Test project issue node form fields. $issue = $this->createIssue($project); $comment = $this->createIssueComment($issue); $this->assertText($comment['comment'], t('Body found')); } } + +class ProjectIssuePriorityTestCase extends ProjectIssueWebTestCase { + /** + * A user who can maintain project issue administrative settings, projects, and create issues. + */ + protected $maintain_user; + + public static function getInfo() { + return array( + 'name' => 'Project issue priority', + 'description' => 'Test issue priority settings and functionality.', + 'group' => 'Project Issue', + ); + } + + function setUp() { + parent::setUp(); + + $this->maintain_user = $this->drupalCreateUser(array('administer projects', 'maintain projects', 'create project issues', 'access project issues', 'access projects')); + $this->drupalLogin($this->maintain_user); + } + + /** + * Assert that the priorities are stored and displayed correctly. + * + * This function will take an array of priorities keyed by their priority ID, + * with each item being an array with they keys 'name' and 'weight'. + */ + function assertAdminPrioritiesForm($values) { + $pass = TRUE; + $this->drupalGet('admin/project/project-issue-priority'); + $forms = $this->xpath('//form'); + $form = $forms[0]; + + $post = $edit = $upload = array(); + $this->handleForm($post, $edit, $upload, NULL, $form); + + foreach ($values as $key => $priority) { + $result = $this->assertEqual($post["priority[$key][name]"], $priority['name'], t('The name for the priority is correct.')); + $result = $this->assertEqual($post["priority[$key][weight]"], $priority['weight'], t('The weight for the priority is correct.')); + } + } + + /** + * Test the project issue priority admin form. + */ + function testProjectIssuePrioritySettings() { + // This matches the defaults setup in project_issue_install(). + $default_priority_order = array( + 1 => array( + 'name' => 'critical', + 'weight' => 1, + ), + 2 => array( + 'name' => 'normal', + 'weight' => 2, + ), + 3 => array( + 'name' => 'minor', + 'weight' => 3, + ), + ); + $this->assertAdminPrioritiesForm($default_priority_order); + + // Test reordering ability + $edit = array(); + $edit['priority[1][weight]'] = -2; + $edit['priority[2][weight]'] = -3; + $edit['priority[3][weight]'] = -1; + $this->drupalPost('admin/project/project-issue-priority', $edit, t('Save')); + + // Check new values + $priorities = array( + 1 => array( + 'name' => 'critical', + 'weight' => 1, + ), + 2 => array( + 'name' => 'normal', + 'weight' => 0, + ), + 3 => array( + 'name' => 'minor', + 'weight' => 2, + ), + ); + $this->assertAdminPrioritiesForm($priorities); + + // Add a new priority, and check the form results + $edit = array(); + $edit['priority[0][name]'] = $this->randomName(8); + $this->drupalPost('admin/project/project-issue-priority', $edit, t('Save')); + + // Check new values + $priorities = array( + 1 => array( + 'name' => 'critical', + 'weight' => 1, + ), + 2 => array( + 'name' => 'normal', + 'weight' => 0, + ), + 3 => array( + 'name' => 'minor', + 'weight' => 2, + ), + 4 => array( + 'name' => $edit['priority[0][name]'], + 'weight' => 3, + ), + ); + $this->assertAdminPrioritiesForm($priorities); + + // Test deleting a priority without any issues. + $this->drupalGet('admin/project/project-issue-priority/delete/4'); + $this->assertNoText('Reassign priority', t('Issue confirm form is displayed properly.')); + $this->drupalPost('admin/project/project-issue-priority/delete/4', array(), t('Delete')); + $this->assertText('Project issue priority '. $edit['priority[0][name]'] .' deleted.', t('Project issue priority has been deleted.')); + + // Test that a custom priority can be assinged to an issue and is displayed correctly. + $edit = array(); + $edit['priority[0][name]'] = $priority_name = $this->randomName(8); + $this->drupalPost('admin/project/project-issue-priority', $edit, t('Save')); + $project = $this->createProject(); + + $edit = array(); + $edit['priority'] = '5'; + $issue = $this->createIssue($project, $edit); + + // Check that the issue priority is displayed correctly. + $this->assertIssueMetadata(array('priority' => $priority_name), $issue->nid, t('Custom issue priority is displyed correctly')); + + // Delete the priority + $this->drupalGet('admin/project/project-issue-priority/delete/5'); + $this->assertText('Reassign priority', t('Issue confirm form is displayed properly.')); + + $edit = array(); + $edit['new_pid'] = 2; + $this->drupalPost(NULL, $edit, t('Delete')); + $this->assertText('Project issue priority '. $priority_name .' deleted.', t('Issue priority was deleted')); + + $this->assertIssueMetadata(array('priority' => 'normal'), $issue->nid); + + $edit = array(); + $edit['priority[1][weight]'] = -3; + $edit['priority[2][weight]'] = -2; + $edit['priority[3][weight]'] = -1; + $this->drupalPost('admin/project/project-issue-priority', $edit, t('Save')); + + $priorities = array( + 1 => array( + 'name' => 'critical', + 'weight' => 0, + ), + 2 => array( + 'name' => 'normal', + 'weight' => 1, + ), + 3 => array( + 'name' => 'minor', + 'weight' => 2, + ), + ); + $this->assertAdminPrioritiesForm($priorities); + + $edit = array(); + $edit['priority'] = 1; + $edit['title'] = $critical_title = $this->randomName(8); + $critical_issue = $this->createIssue($project, $edit); + + $edit = array(); + $edit['priority'] = 3; + $edit['title'] = $minor_title = $this->randomName(8); + $minor_issue = $this->createIssue($project, $edit); + + $this->drupalGet('project/issues/'. $project->project['uri']); + $this->clickLink(t('Priority')); + + // Check that views handler +// @TODO This code is not working yet but is quite important +// $rows = $this->xpath("//table[@class='project-issue']/tr"); +// debug((string)$rows[0]->td[0]); +// +// $this->assertEqual((string)$rows[0], $minor_issue->title); +// $this->assertEqual((string)$rows[1], $issue->title); +// $this->assertEqual((string)$rows[2], $critical_issue->title); + } +} diff --git a/views/handlers/project_issue_handler_field_issue_priority.inc b/views/handlers/project_issue_handler_field_issue_priority.inc index 8499b4b..596d876 100644 --- a/views/handlers/project_issue_handler_field_issue_priority.inc +++ b/views/handlers/project_issue_handler_field_issue_priority.inc @@ -1,14 +1,21 @@ <?php -// $Id: project_issue_handler_field_issue_priority.inc,v 1.2 2009/01/20 18:38:04 dww Exp $ +// $Id: project_issue_handler_field_issue_priority.inc,v 1.3 2010/04/24 01:58:18 dww Exp $ /** * Field handler to display the current priority of an issue. */ class project_issue_handler_field_issue_priority extends views_handler_field { function render($values) { module_load_include('inc', 'project_issue', 'issue'); return check_plain(project_issue_priority($values->{$this->field_alias})); } -} + function click_sort($order) { + // Reverse the sort order since more important priorities are weighted + // lighter. + $order = ($order == 'asc') ? 'desc' : 'asc'; + // Override the sort field, since we are storing denormalized weight. + $this->query->add_orderby($this->table, 'priority_weight', $order); + } +} diff --git a/views/handlers/project_issue_handler_filter_issue_priority.inc b/views/handlers/project_issue_handler_filter_issue_priority.inc index f6ddc4f..6b7e6a2 100644 --- a/views/handlers/project_issue_handler_filter_issue_priority.inc +++ b/views/handlers/project_issue_handler_filter_issue_priority.inc @@ -1,14 +1,14 @@ <?php -// $Id: project_issue_handler_filter_issue_priority.inc,v 1.2 2009/01/20 18:38:04 dww Exp $ +// $Id: project_issue_handler_filter_issue_priority.inc,v 1.3 2010/04/24 01:58:18 dww Exp $ /** * Filter issues based on their priority. */ class project_issue_handler_filter_issue_priority extends views_handler_filter_in_operator { function get_value_options() { module_load_include('inc', 'project_issue', 'issue'); - $this->value_options = project_issue_priority(); + $this->value_options = project_issue_priorities(); } } diff --git a/views/handlers/project_issue_handler_sort_issue_priority_weight.inc b/views/handlers/project_issue_handler_sort_issue_priority_weight.inc new file mode 100644 index 0000000..d2bd8dd --- /dev/null +++ b/views/handlers/project_issue_handler_sort_issue_priority_weight.inc @@ -0,0 +1,16 @@ +<?php +// $Id: project_issue_handler_sort_issue_priority_weight.inc,v 1.1 2010/04/24 01:58:18 dww Exp $ + +/** + * Sort handler for issue priority, using denormalized priority_weight column. + */ +class project_issue_handler_sort_issue_priority_weight extends views_handler_sort { + function query() { + $this->ensure_my_table(); + // Reverse the sort order since more important priorities are weighted + // lighter. + $order = ($this->options['order'] == 'asc') ? 'desc' : 'asc'; + // Override the field name, since we are storing a denormalized weight. + $this->query->add_orderby($this->table_alias, 'priority_weight', $order); + } +} diff --git a/views/project_issue.views.inc b/views/project_issue.views.inc index 4765a95..d0a99b9 100644 --- a/views/project_issue.views.inc +++ b/views/project_issue.views.inc @@ -1,258 +1,261 @@ <?php -// $Id: project_issue.views.inc,v 1.9 2009/06/18 03:48:53 dww Exp $ +// $Id: project_issue.views.inc,v 1.10 2010/04/24 01:58:18 dww Exp $ /** * @file * Provides support for Views integration. */ /** * Implementation of hook_views_data(). */ function project_issue_views_data() { $data = array(); $data['project_issues']['table']['group'] = t('Project issue'); $data['project_issues']['table']['join'] = array( 'node' => array( 'type' => 'INNER', 'left_field' => 'nid', 'field' => 'nid', ), 'project_projects' => array( 'type' => 'INNER', 'left_table' => 'project_projects', 'left_field' => 'nid', 'field' => 'pid', ), 'project_release_nodes' => array( 'type' => 'INNER', 'left_table' => 'project_release_nodes', 'left_field' => 'nid', 'field' => 'rid', ), ); $data['project_issues']['pid'] = array( 'title' => t('Project'), 'help' => t('The project an issue is tied to.'), 'field' => array( 'handler' => 'views_handler_field_node', 'click sortable' => TRUE, ), // Information for accepting a pid as an argument 'argument' => array( 'handler' => 'views_handler_argument_node_nid', 'name field' => 'title', 'numeric' => TRUE, 'validate type' => 'nid', ), // Information for accepting a pid as a filter 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_project', ), 'relationship' => array( 'base' => 'node', 'handler' => 'views_handler_relationship', 'label' => t('Project node'), ), ); $data['node']['project_issue_queue'] = array( 'title' => t('Project issue queue'), 'help' => t("Displays a link to the issue queue for the project this issue is assigned to."), 'field' => array( 'field' => 'title', 'group' => t('Project issue'), 'handler' => 'project_issue_handler_field_issue_queue_link', 'click sortable' => TRUE, ), ); $data['project_issues']['category'] = array( 'title' => t('Category'), 'help' => t("The issue's category (bug, task, feature, etc)."), 'field' => array( 'handler' => 'project_issue_handler_field_issue_category', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_category', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); $data['project_issues']['component'] = array( 'title' => t('Component'), 'help' => t("The issue's component (the options are controlled per-project)."), 'field' => array( 'handler' => 'views_handler_field_node', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_component', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); $data['project_issues']['priority'] = array( 'title' => t('Priority'), 'help' => t("The issue's priority (critical, normal, minor)."), 'field' => array( 'handler' => 'project_issue_handler_field_issue_priority', 'click sortable' => TRUE, ), 'sort' => array( - 'handler' => 'views_handler_sort', + 'handler' => 'project_issue_handler_sort_issue_priority_weight', 'help' => t("Sort by the issue's priority."), ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_priority', 'help' => t("Filter on each issue's status."), ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); $data['project_issues']['rid'] = array( 'title' => t('Version'), 'help' => t('The version associated with the issue (depends on project_release.module).'), 'field' => array( 'handler' => 'views_handler_field_node', 'click sortable' => TRUE, ), 'argument' => array( 'handler' => 'views_handler_argument_node_nid', 'name field' => 'title', 'numeric' => TRUE, 'validate type' => 'nid', ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_version', ), 'relationship' => array( 'base' => 'node', 'handler' => 'views_handler_relationship', 'label' => t('Project release node'), ), ); $data['project_issues']['assigned'] = array( 'title' => t('Assigned'), 'help' => t('The user the issue is assigned to.'), 'relationship' => array( 'base' => 'users', 'handler' => 'views_handler_relationship', 'label' => t('Assigned user'), ), ); $data['project_issues']['sid'] = array( 'title' => t('Status'), 'help' => t('The status of each issue'), 'field' => array( 'handler' => 'project_issue_handler_field_issue_status', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', 'help' => t("Sort by the issue's status."), ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_status', 'help' => t("Filter on each issue's status."), ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); return $data; } /** * Implementation of hook_views_handlers(). */ function project_issue_views_handlers() { return array( 'info' => array( 'path' => drupal_get_path('module', 'project_issue') .'/views/handlers', ), 'handlers' => array( 'project_issue_handler_field_issue_category' => array( 'parent' => 'views_handler_field', ), 'project_issue_handler_field_issue_priority' => array( 'parent' => 'views_handler_field', ), 'project_issue_handler_field_issue_queue_link' => array( 'parent' => 'views_handler_field', ), 'project_issue_handler_field_issue_status' => array( 'parent' => 'views_handler_field', ), 'project_issue_handler_filter_issue_category' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_component' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_priority' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_project' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_status' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_version' => array( 'parent' => 'views_handler_filter_in_operator', ), + 'project_issue_handler_sort_issue_priority_weight' => array( + 'parent' => 'views_handler_sort', + ), ), ); } function project_issue_views_plugins() { $path = drupal_get_path('module', 'project_issue') . '/views/plugins'; $views_path = drupal_get_path('module', 'views'); return array( 'style' => array( 'project_issue_table' => array( 'title' => t('Project issue table'), 'help' => t('Table with colored rows depending on issue status.'), 'handler' => 'project_issue_table_plugin_style', 'parent' => 'table', 'path' => $path, 'theme' => 'views_view_table', 'theme file' => 'theme.inc', 'theme path' => "$views_path/theme", 'uses row plugin' => FALSE, 'uses fields' => TRUE, 'uses options' => TRUE, 'type' => 'normal', ), ), 'access' => array( 'project_issue_access_per_user_queue' => array( 'title' => t('View per-user issue queues'), 'help' => t('Access will be granted if the user is requested in the URL or for users viewing their own per-user issue queues.'), 'handler' => 'project_issue_plugin_access_per_user_queue', 'uses options' => TRUE, 'path' => $path, ), ), ); }
Br3nda/drupal-module-project_issue
244329e72bc57afdf4503313259f0208e47f78af
#780338 by mikey_p, dww: Use format_plural() when deleting an issue status.
diff --git a/includes/admin.issue_status.inc b/includes/admin.issue_status.inc index 942dc48..744de90 100644 --- a/includes/admin.issue_status.inc +++ b/includes/admin.issue_status.inc @@ -1,193 +1,193 @@ <?php -// $Id: admin.issue_status.inc,v 1.1 2009/04/04 07:03:28 dww Exp $ +// $Id: admin.issue_status.inc,v 1.2 2010/04/24 01:13:33 dww Exp $ /** * @file * Code for the issue status admin configuration form. */ function theme_project_issue_admin_states_form($form) { drupal_add_tabledrag('project-issue-status-admin-table', 'order', 'self', 'project-issue-status-weight'); $header = array( array('data' => t('ID')), array('data' => t('Name')), array('data' => t('Weight')), array('data' => t('Author may set')), array('data' => t('In default queries')), array('data' => t('Default status')), array('data' => t('Operations')) ); foreach (element_children($form['status']) as $key) { $rows[] = array( 'class' => 'draggable', 'data' => array( drupal_render($form['status'][$key]['sid']), drupal_render($form['status'][$key]['name']), drupal_render($form['status'][$key]['weight']), drupal_render($form['status'][$key]['author_has']), drupal_render($form['status'][$key]['default_query']), drupal_render($form['default_state'][$key]), drupal_render($form['delete'][$key]), ), ); } $rows[] = array( 'class' => 'draggable', 'data' => array( NULL, drupal_render($form['status_add']['name']), drupal_render($form['status_add']['weight']), drupal_render($form['status_add']['author_has']), drupal_render($form['status_add']['default_query']), NULL, NULL, ), ); $output = '<div>' . theme('table', $header, $rows, array('id' => 'project-issue-status-admin-table')) . '</div>'; $output .= drupal_render($form); return $output; } function project_issue_admin_states_form(&$form_state) { $result = db_query('SELECT * FROM {project_issue_state} ORDER BY weight'); $default_state = variable_get('project_issue_default_state', 1); $default_states = project_issue_default_states(); $form['status']['#tree'] = TRUE; while ($state = db_fetch_object($result)) { $options[$state->sid] = ''; $form['status'][$state->sid]['sid'] = array( '#type' => 'markup', '#value' => $state->sid, ); $form['status'][$state->sid]['name'] = array( '#type' => 'textfield', '#default_value' => $state->name, '#size' => 20, '#maxlength' => 255, ); $form['status'][$state->sid]['weight'] = array( '#type' => 'weight', '#default_value' => $state->weight, '#delta' => 15, '#attributes' => array('class' => 'project-issue-status-weight'), ); $form['status'][$state->sid]['author_has'] = array( '#type' => 'checkbox', '#default_value' => $state->author_has, ); $form['status'][$state->sid]['default_query'] = array( '#type' => 'checkbox', '#default_value' => in_array($state->sid, $default_states), ); $del_link = ($state->sid != $default_state) ? l(t('Delete'), 'admin/project/project-issue-status/delete/'. $state->sid) : ''; $form['delete'][$state->sid] = array( '#type' => 'markup', '#value' => $del_link, ); } $form['default_state'] = array( '#type' => 'radios', '#options' => $options, '#default_value' => $default_state, ); $form['status_add']['name'] = array( '#type' => 'textfield', '#size' => 20, '#maxlength' => 255, ); $form['status_add']['weight'] = array( '#type' => 'weight', '#default_value' => 0, '#delta' => 15, '#attributes' => array('class' => 'project-issue-status-weight'), ); $form['status_add']['author_has'] = array( '#type' => 'checkbox', ); $form['status_add']['default_query'] = array( '#type' => 'checkbox', ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), ); $form['#tree'] = TRUE; return $form; } /** * Submit handler for project_issue_admin_states_form. */ function project_issue_admin_states_form_submit($form, &$form_state) { // Check for and apply changes or additions to project issue status options. if (isset($form_state['values']['default_state'])) { variable_set('project_issue_default_state', $form_state['values']['default_state']); } // Update existing status options. if($form_state['values']['status']) { foreach ($form_state['values']['status'] as $sid => $value) { $state = db_fetch_object(db_query('SELECT name, weight, author_has, default_query FROM {project_issue_state} WHERE sid = %d', $sid)); // Check to see whether the record needs updating. if (($state->name != $value['name']) || ($state->weight != $value['weight']) || ($state->author_has != $value['author_has']) || ($state->default_query != $value['default_query'])) { db_query("UPDATE {project_issue_state} SET name = '%s', weight = %d, author_has = %d, default_query = %d WHERE sid = %d", $value['name'], $value['weight'], $value['author_has'], $value['default_query'], $sid); } } } // Add any new status options. if (isset($form_state['values']['status_add']) && !empty($form_state['values']['status_add']['name'])) { // Check to see whether the state already exists: $issue_state = db_result(db_query("SELECT COUNT(*) FROM {project_issue_state} WHERE name = '%s'", $form_state['values']['status_add']['name'])); if (empty($issue_state)) { db_query("INSERT INTO {project_issue_state} (name, weight, author_has, default_query) VALUES ('%s', %d, %d, %d)", $form_state['values']['status_add']['name'], $form_state['values']['status_add']['weight'], $form_state['values']['status_add']['author_has'], $form_state['values']['status_add']['default_query']); } else { drupal_set_message(t('Status %status already exists.', array ('%status' => $form_state['values']['status_add']['name'])), 'error'); } } } function project_issue_delete_state_confirm(&$form_state, $sid) { $states = project_issue_state(); $name = $states[$sid]; $total = db_result(db_query('SELECT COUNT(nid) AS total FROM {project_issues} WHERE sid = %d', $sid)); if ($total > 0) { $form['new_sid'] = array( '#type' => 'select', '#title' => t('Reassign status'), '#default_value' => $sid, '#options' => $states, - '#description' => t('There are !total existing issues with the status of @name. Please select a new status for these issues.', array('!total' => $total, '@name' => $name)), + '#description' => format_plural($total, 'There is 1 existing issue assigned to @name status. Please select a new status for this issue.', 'There are @count existing issues assigned to @name status. Please select a new status for these issues.', array('@name' => $name)), ); } $form['sid'] = array( '#type' => 'value', '#value' => $sid, ); $form['name'] = array( '#type' => 'hidden', '#value' => $name, ); return confirm_form( $form, t('Are you sure you want to delete the status option %name?', array('%name' => $name)), 'admin/project/project-issue-status', t('This action cannot be undone.'), t('Delete'), t('Cancel') ); } function project_issue_delete_state_confirm_validate($form, &$form_state) { if ($form_state['values']['new_sid'] == $form_state['values']['sid']) { form_set_error('new_sid', t('Choose a new issue status for existing issues of status %name.', array('%name' => $form_state['values']['name']))); } } function project_issue_delete_state_confirm_submit($form, &$form_state) { if ($form_state['values']['new_sid']) { db_query('UPDATE {project_issues} SET sid = %d WHERE sid = %d', $form_state['values']['new_sid'], $form_state['values']['sid']); } db_query('DELETE FROM {project_issue_state} WHERE sid = %d', $form_state['values']['sid']); drupal_set_message(t('Project issue status %issue deleted.', array('%issue' => $form_state['values']['name']))); $form_state['redirect'] ='admin/project/project-issue-status'; }
Br3nda/drupal-module-project_issue
87497bcf1b3325897c51b224c7969334ce83d045
Removed trailing whitespace.
diff --git a/includes/comment.inc b/includes/comment.inc index 44e9040..3f8d393 100644 --- a/includes/comment.inc +++ b/includes/comment.inc @@ -1,598 +1,598 @@ <?php -// $Id: comment.inc,v 1.157 2010/02/18 00:19:27 dww Exp $ +// $Id: comment.inc,v 1.158 2010/04/22 09:34:54 dww Exp $ function project_issue_comment(&$arg, $op) { // $arg can be a comment object, or a form or form_values. if (is_object($arg)) { $nid = $arg->nid; } elseif (is_array($arg)) { $nid = is_array($arg['nid']) ? $arg['nid']['#value'] : $arg['nid']; } $node = node_load($nid); if ($node->type != 'project_issue') { return; } // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Maintain an array of project ids that are affected by this comment // operation. We'll use this to invalidate the "Issue cockpit" block cache // for any of these projects. $affected_projects = array(); switch ($op) { case 'insert': // Get a lock on the issue in order to generate the next comment ID. $tries = 20; $sleep_increment = 0; while ($tries) { $lock = db_query("UPDATE {project_issues} SET db_lock = 1 WHERE nid = %d AND db_lock = 0", $arg['nid']); if (db_affected_rows()) { $id = db_result(db_query("SELECT last_comment_id FROM {project_issues} WHERE nid = %d", $arg['nid'])) + 1; db_query("UPDATE {project_issues} SET last_comment_id = %d, db_lock = 0 WHERE nid = %d", $id, $arg['nid']); break; } // Wait a random and increasing amount of time before the next attempt. $sleep = rand(10000, 1000000) + $sleep_increment; usleep($sleep); $sleep_increment += 50000; $tries--; } if (isset($id)) { $rid = isset($arg['project_info']['rid']) ? $arg['project_info']['rid'] : 0; db_query("INSERT INTO {project_issue_comments} (nid, cid, pid, rid, component, category, priority, assigned, sid, title, timestamp, comment_number) VALUES (%d, %d, %d, %d, '%s', '%s', %d, %d, %d, '%s', %d, %d)", $arg['nid'], $arg['cid'], $arg['project_info']['pid'], $rid, $arg['project_info']['component'], $arg['category'], $arg['priority'], $arg['project_info']['assigned'], $arg['sid'], $arg['title'], $arg['timestamp'], $id); db_query("UPDATE {comments} SET subject = '%s' WHERE cid = %d", "#$id", $arg['cid']); project_issue_update_by_comment($arg, 'insert'); $affected_projects[$old_data->pid] = 1; $affected_projects[$arg['project_info']['pid']] = 1; } else { drupal_set_message(t('There was an error submitting your comment -- please try again. If the problem persists, contact the system administrator.'), 'error'); watchdog('project_issue', 'Error obtaining lock for project issue %nid', array('%nid' => $arg['nid']), WATCHDOG_ERROR, 'node/'. $arg['nid']); // This is a bit extreme, but we have to clean up the failed comment, // or it will appear on the issue. _comment_delete_thread((object) $arg); _comment_update_node_statistics($arg['nid']); cache_clear_all(); // The hard redirect prevents any bogus data from being inserted for the failed comment. drupal_goto('node/'. $arg['nid']); } break; case 'update': project_issue_update_by_comment($arg, 'update'); // Updating a comment can't change anything relevant about the issue for // the purposes of the issue blocks, so we don't need to touch // $affected_projects here. break; case 'delete': // Save the project that's specified in this comment so we can // invalidate its issue block cache. $deleted_comment_project_id = db_result(db_query("SELECT pid FROM {project_issue_comments} WHERE cid = %d", $arg->cid)); $affected_projects[$deleted_comment_project_id] = 1; // Actually delete the comment db_query("DELETE FROM {project_issue_comments} WHERE cid = %d", $arg->cid); $current_data = project_issue_update_by_comment($arg, 'delete'); // We should also invalidate the block cache for whatever project is now // used for this issue, since we might be deleting a comment that moved // an issue from one project to another. - $affected_projects[$current_data->pid] = 1; + $affected_projects[$current_data->pid] = 1; break; case 'view': if (isset($arg->cid)) { $project_issue_table = project_issue_comment_view($original_node, $arg); } else { // Previewing a comment. $test = drupal_clone($arg); $test->pid = $arg->project_info['pid']; $test->component = $arg->project_info['component']; $test->assigned = $arg->project_info['assigned']; // Add a dummy rid if necessary -- prevents incorrect change data. $test->rid = isset($arg->project_info['rid']) ? $arg->project_info['rid'] : 0; $comment_changes = project_issue_metadata_changes($node, $old_data, $test, project_issue_field_labels('web')); $project_issue_table = theme('project_issue_comment_table', $comment_changes); } if ($project_issue_table) { $arg->comment = '<div class="project-issue"><div class="summary">'. $project_issue_table .'</div></div>' . $arg->comment; } break; } // If there are any affected projects, invalidate the block cache for those. if (!empty($affected_projects)) { foreach ($affected_projects as $pid => $value) { $cid = 'project_issue_cockpit_block:'. $pid; cache_clear_all($cid, 'cache'); } } } /** * Add project issue metadata to the comment form. * * @param $form * Reference to form structure. * @param $form_state * Current form state. */ function project_issue_form_comment_form_alter(&$form, &$form_state) { $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Comment body is not required since we validate that ourselves. unset($form['comment_filter']['comment']['#required']); // The 'your name' item just wastes screen estate. unset($form['_author']); // For existing comments, we want to preserve the comment subject, // Even if the subject field is disabled. if ($cid = $form['cid']['#value']) { $subject = db_result(db_query('SELECT subject FROM {comments} WHERE cid = %d', $cid)); } // For new comments, show the expected next number for previews. // This is only for show, the number will be generated when the comment // is posted. else { $next_id = db_result(db_query('SELECT last_comment_id FROM {project_issues} WHERE nid = %d', $form['nid']['#value'])) + 1; $subject = "#$next_id"; // Clobber the comment signature for new followups if necessary. // TODO: Revamp this for Drupal 6. if (!variable_get('project_issue_show_comment_signatures', 0)) { $form['comment_filter']['comment']['#default_value'] = ''; } } $form['subject'] = array( '#type' => 'value', '#value' => $subject, ); // Any time we're on a reply page, show the full issue below the reply. if (project_issue_is_comment_reply()) { $form['#pre_render'][] = 'project_issue_comment_pre_render'; } // Make sure project is current here -- it may have changed when posted. if (!empty($form_state['values']['project_info']['pid'])) { $node->project_issue['pid'] = $form_state['values']['project_info']['pid']; } $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); project_issue_set_breadcrumb($node, $project); // Only allow metadata changes on new followups. if (isset($form['cid']['#value'])) { return; } // We have to set $form['#action'] to prevent AHAH nastiness. if (!empty($form['pid']['#value'])) { $form['#action'] = url('comment/reply/' . $nid . '/' . $form['pid']['#value']); } else { $form['#action'] = url('comment/reply/' . $nid); } // We need to ask for almost the same metadata as project issue itself // so let's reuse the form. $form += project_issue_form($node, $form_state, TRUE); // comment.module is basically still FAPI v1. It sets the preview button to // #type 'button', so FAPI doesn't really consider that a form submission. // However, we depend on the form being rebuilt on preview to do our magic. // Thanks to a change in 6.14 core, form.inc will only rebuild the form if // $form_state['submitted'] is TRUE. So, we set the preview button to // actually be a 'submit' button so that the form is rebuilt on preview and // our comment preview code can kick in. $form['preview']['#type'] = 'submit'; // We need this otherwise pid collides with comment. $form['project_info']['#tree'] = TRUE; $form['project_info']['#weight'] = -2; // Remove the form item that displays the current project, and // replace the static single project value with a select list // of all projects to make swapping simpler. unset($form['project_info']['project_display']); $uris = NULL; if (variable_get('project_issue_autocomplete', 0) == 1) { $form['project_info']['project_title'] = array( '#type' => 'textfield', '#title' => t('Project'), '#default_value' => $project->title, '#required' => TRUE, '#weight' => -1, '#size' => 35, '#autocomplete_path' => 'project/autocomplete/issue/project', '#attributes' => array( 'onFocus' => 'project_issue_autocomplete_handler()', ), '#ahah' => array( 'progress' => array( 'type' => 'none', ), 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', ), ); } else { $projects = project_projects_select_options($uris); $form['project_info']['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#default_value' => $project->nid, '#options' => $projects, '#required' => TRUE, '#weight' => -1, '#ahah' => array( 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', 'event' => 'change', ), ); } $form['issue_info']['#weight'] = -1; $form['#prefix'] = '<div class="project-issue"><div class="node-form"><div class="standard">'; $form['#suffix'] = '</div></div></div>'; $form['original_issue'] = array( '#type' => 'fieldset', '#title' => t('Edit issue settings'), '#description' => t('Note: changing any of these items will update the issue\'s overall values.'), '#collapsible' => TRUE, '#weight' => -10, ); $form['original_issue']['title'] = array( '#type' => 'textfield', '#title' => t('Issue title'), '#maxlength' => 128, '#default_value' => $node->title, '#weight' => -30, '#required' => TRUE, ); $form['project_info']['assigned'] = $form['issue_info']['assigned']; unset($form['issue_info']['assigned']); $form['project_info']['#prefix'] = '<div id="project-info-wrapper" class="inline-options">'; $form['project_info']['#suffix'] = '</div>'; // Remove the 'Project information' and 'Issue information' fieldsets, // since we'll move everything inside the 'Edit issue settings' fieldset. unset($form['project_info']['#type'], $form['project_info']['#title']); unset($form['issue_info']['#type'], $form['issue_info']['#title']); // Restructure the UI to de-emphasize the original project form inputs. $form['original_issue']['project_info'] = $form['project_info']; $form['original_issue']['issue_info'] = $form['issue_info']; unset($form['project_info'], $form['issue_info']); unset($form['issue_details'], $form['project_help']); drupal_add_js(drupal_get_path('module', 'project_issue') .'/project_issue.js'); } /** * Validate issue metadata on the comment form. * * @param $form * The Drupal form structure. * @param $form_state * The current state of the form. */ function project_issue_form_comment_validate($form, &$form_state) { if (empty($form['cid']['#value']) && variable_get('project_issue_autocomplete', 0) == 1) { if (empty($form_state['values']['project_info']['project_title'])) { form_set_error('project_title', t('You must enter a project to navigate to.')); } else { $pid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_info']['project_title'], 'project_project')); if (empty($pid)) { form_set_error('project_info][project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_info']['project_title']))); } else { $form_state['values']['project_info']['pid'] = $pid; } } } if (!empty($form_state['rebuild'])) { return; } // Only validate metadata changes on new followups. if (isset($form_state['values']['cid'])) { return; } $values = $form_state['values']; $project_info = $form_state['values']['project_info']; $nid = $values['nid']; $node = node_load($nid); // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Adjust new file attachments to go to the issues directory. // We have to do this during validate, otherwise we might miss // adjusting the filename before comment upload saves it (module weighting) // TODO: is this still true? project_issue_change_comment_upload_path($values); // Make sure project is current here -- it may have changed when posted. if (isset($project_info['pid'])) { $node->project_issue['pid'] = $project_info['pid']; } $project = node_load($node->project_issue['pid']); if (!empty($project) && $project->type == 'project_project') { // Force all comments to be a child of the main issue, to match the // flat display, and also to prevent accidentally deleting a thread. $form_state['values']['pid'] = 0; // Validate version. if (module_exists('project_release') && isset($project_info['rid']) && ($releases = project_release_get_releases($project, 0, 'version', 'all', array($project_info['rid'])))) { $rid = $project_info['rid']; if ($rid && !in_array($rid, array_keys($releases))) { $rid = 0; } // Check to make sure this release is not marked as an invalid // release node for user selection. $invalid_rids = variable_get('project_issue_invalid_releases', array()); if (!empty($invalid_rids) && ((empty($rid) && in_array($node->project_issue['rid'], $invalid_rids)) || in_array($rid, $invalid_rids))) { form_set_error('project_info][rid', t('%version is not a valid version, please select a different value.', array('%version' => $releases[$node->project_issue['rid']]))); } elseif (empty($rid)) { form_set_error('project_info][rid', t('You have to specify a valid version.')); } } // Add a dummy rid if necessary -- prevents incorrect change data. else { $rid = 0; } // Validate component. $component = $project_info['component']; if ($component && !in_array($component, $project->project_issue['components'])) { $component = 0; } empty($component) && form_set_error('project_info][component', t('You have to specify a valid component.')); } else { form_set_error('project_info][pid', t('You have to specify a valid project.')); } empty($values['category']) && form_set_error('category', t('You have to specify a valid category.')); // Now, make sure the comment changes *something* about the issue. // If the user uploaded a file, so long as it's not marked for removal, // we consider that a valid change to the issue, too. $has_file = FALSE; $files = isset($values['files']) ? $values['files'] : array(); foreach ($files as $number => $data) { if (empty($data['remove'])) { $has_file = TRUE; break; } } if (!$has_file && empty($values['comment'])) { $comment = drupal_clone((object) $values); $comment->pid = $project_info['pid']; $comment->component = $component; $comment->rid = $rid; $comment->assigned = $project_info['assigned']; $comment_changes = project_issue_metadata_changes($node, $old_data, $comment, project_issue_field_labels('web')); // If the PID changed, rebuild the form if (isset($comment_changes['pid']['new']) && $comment_changes['pid']['new'] === TRUE) { $form_state['rebuild'] = TRUE; } $has_change = FALSE; foreach ($comment_changes as $field => $changes) { if (isset($changes['new'])) { $has_change = TRUE; break; } } if (!$has_change) { form_set_error('comment', t('You must either add a comment, upload a file, or change something about this issue.')); } } } /** * Theme a project issue metadata table. * * @param $comment_changes * Array containing metadata differences between comments * as returned by project_issue_metadata_changes(). * @return * The themed metadata table. */ function theme_project_issue_comment_table($comment_changes) { $rows = array(); foreach ($comment_changes as $field => $change) { if (!empty($change['label']) && isset($change['old']) && isset($change['new'])) { $rows[] = theme('project_issue_comment_table_row', $field, $change); } } return $rows ? theme('table', array(), $rows) : ''; } /** * Theme a single row of the project issue metadata changes table. * * @param $field * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * An array representing one row of the table. * * NOTE: If you override this theme function, you *must* make sure * that you sanitize all output from this function that is displayed * to the user. No further escaping/filtering of the data in this * table will take place after this function. In most cases * this means that you need to run the $change['label'], $change['old'], * and $change['new'] values through either the check_plain() or * filter_xss() function to prevent XSS and other types * of problems due to any malicious input in these * field values. */ function theme_project_issue_comment_table_row($field, $change) { // Allow anchor, emphasis, and strong tags in metadata tables. $allowed_tags = array('a', 'em', 'strong'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])){ foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { $added[] = '+'. $item; } } elseif (!empty($change['new'])) { $added[] = '+'. $change['new']; } return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(implode(', ', $removed), $allowed_tags), filter_xss(implode(', ', $added), $allowed_tags), ); } elseif (in_array($field, $plain_fields)) { return array( filter_xss($change['label'], $allowed_tags) .':', check_plain(project_issue_change_summary($field, $change['old'])), '&raquo; '. check_plain(project_issue_change_summary($field, $change['new'])), ); } else { return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(project_issue_change_summary($field, $change['old']), $allowed_tags), '&raquo; '. filter_xss(project_issue_change_summary($field, $change['new']), $allowed_tags), ); } } /** * Returns the issue metadata table for a comment. * * @param $node * The corresponding node. * @param $comment * The comment, if it's set then metadata will be returned. If it's not * set then metadata will be precalculated. * @return * A themed table of issue metadata. */ function project_issue_comment_view(&$node, $comment = NULL) { static $project_issue_tables; if (isset($comment)) { return isset($project_issue_tables[$comment->cid]) ? $project_issue_tables[$comment->cid] : ''; } if (!empty($node->comment_count)) { $old = unserialize(db_result(db_query('SELECT original_issue_data FROM {project_issues} WHERE nid = %d', $node->nid))); $labels = project_issue_field_labels('web'); $result = db_query('SELECT p.cid, p.title, p.pid, p.rid, p.component, p.category, p.priority, p.assigned, p.sid FROM {project_issue_comments} p INNER JOIN {comments} c ON p.cid = c.cid WHERE p.nid = %d AND c.status = %d ORDER BY p.timestamp ASC', $node->nid, COMMENT_PUBLISHED); while ($followup = db_fetch_object($result)) { $followup_changes = project_issue_metadata_changes($node, $old, $followup, project_issue_field_labels('web')); $project_issue_tables[$followup->cid] = theme('project_issue_comment_table', $followup_changes); $old = $followup; } } } /** * Updates the project issue based on the comment inserted/updated/deleted. * * @param $comment_data * The comment data that's been submitted. * @param $op * The comment operation performed, 'insert', 'update', 'delete'. * @return * An object representing the comment data used to update the issue. */ function project_issue_update_by_comment($comment_data, $op) { switch ($op) { case 'insert': // Massage the incoming data so the structure is consistent throughout the function. $comment_data['component'] = $comment_data['project_info']['component']; $comment_data['pid'] = $comment_data['project_info']['pid']; $comment_data['rid'] = isset($comment_data['project_info']['rid']) ? $comment_data['project_info']['rid'] : 0; unset ($comment_data['project_info']); $comment_data = (object) $comment_data; // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. if (!isset($comment_data->followup_no_mail)) { // Temporary hack to get around sending of auto-close emails. project_issue_set_mail_notify($comment_data->nid); } break; case 'update': $comment_data = (object) $comment_data; break; } // In order to deal with deleted/unpublished comments, make sure that we're performing // the updates to the issue with the latest available published comment. $comment_data = project_issue_get_newest_comment($comment_data); // Update the issue data to reflect the new final states. db_query("UPDATE {project_issues} SET pid = %d, category = '%s', component = '%s', priority = %d, rid = %d, assigned = %d, sid = %d WHERE nid = %d", $comment_data->pid, $comment_data->category, $comment_data->component, $comment_data->priority, $comment_data->rid, $comment_data->assigned, $comment_data->sid, $comment_data->nid); // Update the issue title. $node = node_load($comment_data->nid, NULL, TRUE); // Don't use cached since we changed data above. $node->title = $comment_data->title; // This also updates the changed date of the issue. node_save($node); // Return the object of comment data we used to update the issue. return $comment_data; } /** * Adjusts the filepath of issue followups so files are saved to * the correct issues directory. * * @param $comment * An array of the submitted comment values. */ function project_issue_change_comment_upload_path(&$comment) { static $run = NULL; // Only for new comments with attachments. diff --git a/includes/project_node.inc b/includes/project_node.inc index f5d1c45..eeba8de 100644 --- a/includes/project_node.inc +++ b/includes/project_node.inc @@ -1,71 +1,71 @@ <?php -// $Id: project_node.inc,v 1.1 2009/06/18 03:30:22 dww Exp $ +// $Id: project_node.inc,v 1.2 2010/04/22 09:34:54 dww Exp $ /** * hook_nodeapi implementation specific to "project_project" nodes * (from the project.module) * @see project_issue_nodeapi(). */ function project_issue_project_nodeapi(&$node, $op, $arg) { switch ($op) { case 'load': project_issue_project_load($node, $arg); break; case 'insert': project_issue_project_insert($node); break; case 'delete': project_issue_project_delete($node); break; } } function project_issue_project_load(&$node, $arg) { $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $node->nid)); // If nothing loaded, bail immediately if (!$project) { return $node; } $node->project_issue = array(); $node->project_issue['components'] = unserialize($project->components); $node->project_issue['default_component'] = $project->default_component; $node->project_issue['mail_copy_filter'] = unserialize($project->mail_copy_filter); $node->project_issue['mail_copy_filter_state'] = unserialize($project->mail_copy_filter_state); foreach (array('issues', 'help', 'mail_digest', 'mail_copy', 'mail_reminder') as $field) { $node->project_issue[$field] = $project->$field; } return $node; } function project_issue_project_insert($node) { // Setup reasonable defaults: enable issue tracker and standard // components. If maintainers want to change these, (or any of the // other issue-related project settings, like the email notifications) // they'd use the "issues" subtab of the project edit tab (since none // of these fields are present on the initial project add form). $node->project_issue['issues'] = 1; // Default components are saved in the variables table as a plain // string instead of as a serialized array since they come out of // a textarea on a system settings form. Convert here to the more // desirable serialized array for storage per-project. $defaults = array(t('Code'), t('Documentation'), t('Miscellaneous'), t('User interface')); - $components = variable_get('project_issue_default_components', implode("\n", $defaults)); + $components = variable_get('project_issue_default_components', implode("\n", $defaults)); $default_components = explode("\n", str_replace("\r", '', $components)); $node->project_issue['components'] = serialize($default_components); db_query("INSERT INTO {project_issue_projects} (nid, issues, components) VALUES (%d, %d, '%s')", $node->nid, $node->project_issue['issues'], $node->project_issue['components']); } function project_issue_project_delete($node) { // Delete all associated issues. $issues = db_query('SELECT nid FROM {project_issues} WHERE pid = %d', $node->nid); while ($issue = db_fetch_object($issues)) { node_delete($issue->nid); } db_query('DELETE FROM {project_issue_projects} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_subscriptions} WHERE nid = %d', $node->nid); } diff --git a/project_issue.module b/project_issue.module index 7963b6a..82ec909 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,1134 +1,1134 @@ <?php -// $Id: project_issue.module,v 1.178 2010/02/08 18:02:59 bdragon Exp $ +// $Id: project_issue.module,v 1.179 2010/04/22 09:34:54 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { - $item = trim($item); + $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = !empty($changes['uid']) ? $changes['uid'] : $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return - * TRUE if the comment was successfully added to the requested issue, + * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': module_load_include('inc', 'project_issue', 'includes/project_node'); project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implementation of hook_mail(). (stub function) */ function project_issue_mail($key, &$message, $params) { module_load_include('inc', 'project_issue', 'includes/mail'); return _project_issue_mail($key, $message, $params); } /** * Implementation of hook_mailhandler(). (stub function) */ function project_issue_mailhandler($node, $result, $i, $header, $mailbox) { module_load_include('inc', 'project_issue', 'includes/mail'); return _project_issue_mailhandler($node, $result, $i, $header, $mailbox); } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implement hook_delete() for project issue nodes. */ function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } /** * Implement hook_form() for project issue nodes. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_form($node, $form_state, $include_metadata_fields); } /** * Implement hook_validate() for project issue nodes. */ function project_issue_validate($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_validate($node); } /** * Implement hook_insert() for project issue nodes. */ function project_issue_insert($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_insert($node); } /** * Implement hook_view() for project issue nodes. */ function project_issue_view($node, $teaser = FALSE, $page = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_view'); return _project_issue_view($node, $teaser, $page); } /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { module_load_include('inc', 'project_issue', 'includes/mail'); foreach ($nids as $nid) { project_issue_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes));
Br3nda/drupal-module-project_issue
c0d70dece72e652720c0f031a0d39a96a46dcb64
#776128 by dmitrig01, dww: Added assertions about the issue metadata fields.
diff --git a/project_issue.test b/project_issue.test index b868572..910a573 100644 --- a/project_issue.test +++ b/project_issue.test @@ -1,139 +1,185 @@ <?php -// $Id: project_issue.test,v 1.2 2010/04/20 18:56:01 dww Exp $ +// $Id: project_issue.test,v 1.3 2010/04/20 22:22:06 dww Exp $ include_once drupal_get_path('module', 'project') . '/project.test'; class ProjectIssueWebTestCase extends ProjectWebTestCase { function setUp() { // Setup the required modules for all tests. $modules = func_get_args(); $modules = array_merge(array('project_issue', 'views', 'comment', 'comment_upload', 'upload'), $modules); // We can't call parent::setUp() with a single array argument, so we need // this ugly call_user_func_array(). call_user_func_array(array($this, 'parent::setUp'), $modules); variable_set('comment_preview_project_issue', FALSE); } /** * Create an Issue node. * * @param stdClass $project * A project node. * @param array $edit * An array of form values, passed to drupalPost. Optional * @return * An issue node. */ function createIssue($project, $edit = array()) { - if (empty($edit)) { - $edit['title'] = $this->randomName(8); - $edit['body'] = $this->randomName(64); - $edit['component'] = 'Code'; - $edit['category'] = 'bug'; - } + // If people are lazy and don't want to specify any of these, provide a + // default. + $edit += array( + 'title' => $this->randomName(8), + 'body' => $this->randomName(64), + 'component' => 'Code', + 'category' => 'bug', + ); $this->drupalPost('node/add/project-issue/' . $project->project['uri'], $edit, t('Save')); $this->assertRaw(t('!post %title has been created.', array('!post' => 'Issue', '%title' => $edit["title"])), t('Issue created.')); return $this->drupalGetNodeByTitle($edit['title']); } function createIssueComment($issue, $edit = array()) { - if (empty($edit)) { - $edit['comment'] = $this->randomName(64); - } + $edit += array('comment' => $this->randomName(64)); $this->drupalPost('comment/reply/' . $issue->nid, $edit, t('Save')); return $edit; } + + /** + * Make sure issue metadata matches up to what it's intended to be. + * + * @param array $metadata + * Associative array of expected issue metadata field names and values. + * @param $nid + * Optional integer node ID of the issue to check metadata fields for. + */ + function assertIssueMetadata($metadata, $nid = NULL) { + $pass = TRUE; + if ($nid) { + $this->drupalGet('node/' . $nid); + } + foreach ($this->xpath("//div[@id='project-issue-summary-table']/table//tr") as $row) { + $key = strtolower(trim((string)$row->td[0], ':')); + if (isset($metadata[$key])) { + if (strtolower($metadata[$key]) != strtolower((string)$row->td[1])) { + $pass = FALSE; + } + } + } + if ($pass) { + $this->pass(t('Issue metadata matches')); + } + else { + $this->fail(t('Issue metadata matches')); + } + } } class ProjectIssueCreationTestCase extends ProjectIssueWebTestCase { + protected $maintain_user; + public static function getInfo() { return array( 'name' => 'Project issue creation', 'description' => 'Test creating an issue.', 'group' => 'Project Issue', ); } function setUp() { parent::setUp(); - $maintain_user = $this->drupalCreateUser(array('maintain projects', 'create project issues', 'access project issues', 'access projects')); - $this->drupalLogin($maintain_user); + $this->maintain_user = $this->drupalCreateUser(array('maintain projects', 'create project issues', 'access project issues', 'access projects')); + $this->drupalLogin($this->maintain_user); } /** * Test the creation of project issues and the display of issue properties. */ function testProjectIssueCreation() { $project = $this->createProject(); // Test project issue node form fields. $this->drupalGet('node/add/project-issue/' . $project->project['uri']); $this->assertText(t('Create Issue')); - $issue = $this->createIssue($project); + $issue = $this->createIssue($project, array( + 'component' => 'Miscellaneous', + 'category' => 'feature', + 'priority' => 1, + 'assigned' => $this->maintain_user->uid, + )); $this->assertText($issue->title, t('Title found')); $this->assertText($issue->body, t('Body found')); - /// @todo We need to assert the other issue metadata fields here, too. + $issue = $this->createIssue($project, array( + 'component' => 'Miscellaneous', + 'category' => 'feature', + 'priority' => 1, + 'assigned' => $this->maintain_user->uid, + )); + $this->assertIssueMetadata(array( + 'component' => 'Miscellaneous', + 'category' => 'feature request', + 'priority' => 'critical', + 'assigned' => $this->maintain_user->name, + )); } } class ProjectIssueCommentTestCase extends ProjectIssueWebTestCase { public static function getInfo() { return array( 'name' => 'Project issue comment', 'description' => 'Test commenting on an issue.', 'group' => 'Project Issue', ); } function setUp() { parent::setUp(); $maintain_user = $this->drupalCreateUser(array('maintain projects', 'create project issues', 'access project issues', 'access projects')); $this->drupalLogin($maintain_user); } /** * Test the creation of issue metadata. */ function testProjectIssueMetadata() { $project = $this->createProject(); // Test project issue node form fields. $issue = $this->createIssue($project); $html = $this->drupalGet('comment/reply/' . $issue->nid); $this->parse(); // Let's iterate over all the forms. $forms = $this->xpath('//form'); $form = $forms[0]; // We try to set the fields of this form as specified in $edit. $post = $upload = $edit = array(); $this->handleForm($post, $edit, $upload, NULL, $form); $map = array( 'priority' => 'priority', 'category' => 'category', 'component' => 'project_info[component]', 'assigned' => 'project_info[assigned]', 'pid' => 'project_info[pid]', ); foreach ($map as $issue_key => $post_key) { $this->assertEqual($issue->project_issue[$issue_key], $post[$post_key], t('Making sure comment form is correct')); } } /** * Test the creation of issue comments. */ function testProjectIssueComment() { $project = $this->createProject(); // Test project issue node form fields. $issue = $this->createIssue($project); $comment = $this->createIssueComment($issue); - $this->assertText($comment['comment'], t('Body found')); } }
Br3nda/drupal-module-project_issue
f608dbfd89cf4609b0a1a3484688946eb6531a39
#775102 by dmitrig01, dww: Added initial tests for issue comments.
diff --git a/project_issue.test b/project_issue.test index 2b51734..b868572 100644 --- a/project_issue.test +++ b/project_issue.test @@ -1,78 +1,139 @@ <?php -// $Id: project_issue.test,v 1.1 2010/04/20 18:33:06 dww Exp $ +// $Id: project_issue.test,v 1.2 2010/04/20 18:56:01 dww Exp $ include_once drupal_get_path('module', 'project') . '/project.test'; class ProjectIssueWebTestCase extends ProjectWebTestCase { function setUp() { // Setup the required modules for all tests. $modules = func_get_args(); $modules = array_merge(array('project_issue', 'views', 'comment', 'comment_upload', 'upload'), $modules); // We can't call parent::setUp() with a single array argument, so we need // this ugly call_user_func_array(). call_user_func_array(array($this, 'parent::setUp'), $modules); + variable_set('comment_preview_project_issue', FALSE); } /** * Create an Issue node. * * @param stdClass $project * A project node. * @param array $edit * An array of form values, passed to drupalPost. Optional * @return * An issue node. */ function createIssue($project, $edit = array()) { if (empty($edit)) { $edit['title'] = $this->randomName(8); $edit['body'] = $this->randomName(64); $edit['component'] = 'Code'; $edit['category'] = 'bug'; } $this->drupalPost('node/add/project-issue/' . $project->project['uri'], $edit, t('Save')); $this->assertRaw(t('!post %title has been created.', array('!post' => 'Issue', '%title' => $edit["title"])), t('Issue created.')); return $this->drupalGetNodeByTitle($edit['title']); } - function createIssueFollowup() { - + function createIssueComment($issue, $edit = array()) { + if (empty($edit)) { + $edit['comment'] = $this->randomName(64); + } + $this->drupalPost('comment/reply/' . $issue->nid, $edit, t('Save')); + return $edit; } } class ProjectIssueCreationTestCase extends ProjectIssueWebTestCase { public static function getInfo() { return array( 'name' => 'Project issue creation', 'description' => 'Test creating an issue.', 'group' => 'Project Issue', ); } function setUp() { parent::setUp(); $maintain_user = $this->drupalCreateUser(array('maintain projects', 'create project issues', 'access project issues', 'access projects')); $this->drupalLogin($maintain_user); } /** * Test the creation of project issues and the display of issue properties. */ function testProjectIssueCreation() { $project = $this->createProject(); // Test project issue node form fields. $this->drupalGet('node/add/project-issue/' . $project->project['uri']); $this->assertText(t('Create Issue')); $issue = $this->createIssue($project); $this->assertText($issue->title, t('Title found')); $this->assertText($issue->body, t('Body found')); /// @todo We need to assert the other issue metadata fields here, too. } } + +class ProjectIssueCommentTestCase extends ProjectIssueWebTestCase { + public static function getInfo() { + return array( + 'name' => 'Project issue comment', + 'description' => 'Test commenting on an issue.', + 'group' => 'Project Issue', + ); + } + + function setUp() { + parent::setUp(); + + $maintain_user = $this->drupalCreateUser(array('maintain projects', 'create project issues', 'access project issues', 'access projects')); + $this->drupalLogin($maintain_user); + } + + /** + * Test the creation of issue metadata. + */ + function testProjectIssueMetadata() { + $project = $this->createProject(); + // Test project issue node form fields. + $issue = $this->createIssue($project); + $html = $this->drupalGet('comment/reply/' . $issue->nid); + $this->parse(); + // Let's iterate over all the forms. + $forms = $this->xpath('//form'); + $form = $forms[0]; + // We try to set the fields of this form as specified in $edit. + $post = $upload = $edit = array(); + $this->handleForm($post, $edit, $upload, NULL, $form); + $map = array( + 'priority' => 'priority', + 'category' => 'category', + 'component' => 'project_info[component]', + 'assigned' => 'project_info[assigned]', + 'pid' => 'project_info[pid]', + ); + foreach ($map as $issue_key => $post_key) { + $this->assertEqual($issue->project_issue[$issue_key], $post[$post_key], t('Making sure comment form is correct')); + } + } + + /** + * Test the creation of issue comments. + */ + function testProjectIssueComment() { + $project = $this->createProject(); + // Test project issue node form fields. + $issue = $this->createIssue($project); + $comment = $this->createIssueComment($issue); + + $this->assertText($comment['comment'], t('Body found')); + } +}
Br3nda/drupal-module-project_issue
91d99b66d095144fc0fe77b395921eefeec5ab9c
#776128 by mikey_p, dmitrig01, dww: Added initial tests for project_issue. For now, we're just testing initial issue creation.
diff --git a/project_issue.test b/project_issue.test new file mode 100644 index 0000000..2b51734 --- /dev/null +++ b/project_issue.test @@ -0,0 +1,78 @@ +<?php +// $Id: project_issue.test,v 1.1 2010/04/20 18:33:06 dww Exp $ + +include_once drupal_get_path('module', 'project') . '/project.test'; + +class ProjectIssueWebTestCase extends ProjectWebTestCase { + + function setUp() { + // Setup the required modules for all tests. + $modules = func_get_args(); + $modules = array_merge(array('project_issue', 'views', 'comment', 'comment_upload', 'upload'), $modules); + // We can't call parent::setUp() with a single array argument, so we need + // this ugly call_user_func_array(). + call_user_func_array(array($this, 'parent::setUp'), $modules); + } + + /** + * Create an Issue node. + * + * @param stdClass $project + * A project node. + * @param array $edit + * An array of form values, passed to drupalPost. Optional + * @return + * An issue node. + */ + function createIssue($project, $edit = array()) { + if (empty($edit)) { + $edit['title'] = $this->randomName(8); + $edit['body'] = $this->randomName(64); + $edit['component'] = 'Code'; + $edit['category'] = 'bug'; + } + + $this->drupalPost('node/add/project-issue/' . $project->project['uri'], $edit, t('Save')); + $this->assertRaw(t('!post %title has been created.', array('!post' => 'Issue', '%title' => $edit["title"])), t('Issue created.')); + + return $this->drupalGetNodeByTitle($edit['title']); + } + + function createIssueFollowup() { + + } +} + +class ProjectIssueCreationTestCase extends ProjectIssueWebTestCase { + public static function getInfo() { + return array( + 'name' => 'Project issue creation', + 'description' => 'Test creating an issue.', + 'group' => 'Project Issue', + ); + } + + function setUp() { + parent::setUp(); + + $maintain_user = $this->drupalCreateUser(array('maintain projects', 'create project issues', 'access project issues', 'access projects')); + $this->drupalLogin($maintain_user); + } + + /** + * Test the creation of project issues and the display of issue properties. + */ + function testProjectIssueCreation() { + $project = $this->createProject(); + + // Test project issue node form fields. + $this->drupalGet('node/add/project-issue/' . $project->project['uri']); + $this->assertText(t('Create Issue')); + + $issue = $this->createIssue($project); + + $this->assertText($issue->title, t('Title found')); + $this->assertText($issue->body, t('Body found')); + /// @todo We need to assert the other issue metadata fields here, too. + } +}
Br3nda/drupal-module-project_issue
2ded3335161e7fb2e66b5015a8d975ce748a9dc7
#776128 by dww: Fixed a PHP notice when creating issues when project_release is not enabled (uncovered while writing tests).
diff --git a/includes/issue_node_form.inc b/includes/issue_node_form.inc index affeb56..0c87c1e 100644 --- a/includes/issue_node_form.inc +++ b/includes/issue_node_form.inc @@ -1,484 +1,484 @@ <?php -// $Id: issue_node_form.inc,v 1.5 2009/10/08 23:36:16 dww Exp $ +// $Id: issue_node_form.inc,v 1.6 2010/04/20 07:05:25 dww Exp $ /** * @file * Code required for the issue node form. */ /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects (nid => title, grouped by project type // categories if any), and also get an array of project shortnames. $short_names = array(); $projects = project_projects_select_options($short_names); if (empty($projects)) { drupal_set_message(t('You do not have access to any projects.'), 'error'); // No reason to return a project selector form with no elements, so just // return an empty array for the form. return array(); } // See if there's only one project the user has access to, and if so, // redirect directly to the issue form for that project. if (count($short_names) == 1) { drupal_goto('node/add/project-issue/' . key($short_names)); } // Otherwise, return a form to select which project to submit an issue for. $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => array(t('<none>')) + $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Private helper to implement hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function _project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => check_markup($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => check_markup($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); - if ($releases) { + if (!empty($releases)) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'value', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } else { // If we're not allowing issue metadata changes, add all of these values // into the form so they show up in the $node->project_issue array during // validation and submit, so we're consistent with where they live. $form['project_issue'] = array('#tree' => TRUE); $form['project_issue']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if (isset($node->project_issue['rid'])) { $form['project_issue']['rid'] = array( '#type' => 'value', '#value' => $node->project_issue['rid'], ); } $form['project_issue']['component'] = array( '#type' => 'value', '#value' => $node->project_issue['component'], ); $form['project_issue']['category'] = array( '#type' => 'value', '#value' => $node->project_issue['category'], ); $form['project_issue']['priority'] = array( '#type' => 'value', '#value' => $node->project_issue['priority'], ); $form['project_issue']['assigned'] = array( '#type' => 'value', '#value' => $node->project_issue['assigned'], ); $form['project_issue']['sid'] = array( '#type' => 'value', '#value' => $node->project_issue['sid'], ); } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Private helper to implement hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function _project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } /** * Private helper to implement hook_insert(). * * @param $node * Object containing form values from the project_issue node form. This is * NOT a fully loaded $node object, so the issue-related values are directly * in $node, not in the $node->project_issue array. */ function _project_issue_insert($node) { // Permanently store the original issue states in a serialized array. This // is a bit yucky, but we need them for proper handling of states workflow. // The current states need to be stored in {project_issues} as well for // query efficiency in issue queue searches, and it seems too messy to add a // bunch of new columns to the {project_issues} table for the original // states. $original_issue_data = new stdClass(); $fields = array( 'pid' => 0, 'rid' => 0, 'component' => '', 'category' => '', 'priority' => 0, 'assigned' => 0, 'sid' => 0, 'title' => '', ); foreach ($fields as $field => $default) { // Some of the incoming data may not have the correct default. if (empty($node->$field)) { $node->$field = $default; } $original_issue_data->$field = $node->$field; } db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); // Invalidate the "Issue cockpit" block cache for this project, since the // new issue will have altered the summary totals. cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); }
Br3nda/drupal-module-project_issue
355e5c6b476d419a5b2f28859863b718f943ea4b
#448004 by yhager, hunmonk: Subscription mails sent for unpublished nodes.
diff --git a/includes/mail.inc b/includes/mail.inc index fa082d4..20097b3 100644 --- a/includes/mail.inc +++ b/includes/mail.inc @@ -1,684 +1,690 @@ <?php -// $Id: mail.inc,v 1.124 2010/02/08 18:02:59 bdragon Exp $ +// $Id: mail.inc,v 1.125 2010/04/17 22:04:49 thehunmonkgroup Exp $ /** * @file * Project issue tracking email notifications system. */ /** * Implementation of hook_mailhandler(). */ function _project_issue_mailhandler($node, $result, $i, $header, $mailbox) { if ($node->type == 'project') { if (node_access('create', 'project_issue')) { $node->nid = preg_replace('/@.+/', '', $node->nid); if ($node->nid) { /* ** Base the new entry on the node it belongs to, this ensures all ** values are initially correct. */ $entry = node_load(array('nid' => $node->nid, 'type' => 'project_issue')); } // Possible attributes $fields = array( 'pid' => t('Project'), 'category' => t('Category'), 'component' => t('Component'), 'priority' => t('Priority'), 'rid' => t('Version'), 'assigned' => t('Assigned to'), 'sid' => t('Status') ); /* ** Only change the title if it doesn't have the old title in it. ** This should prevent the title from changing due to added ** prefixes. It may on occasion make false positives, but if ** a title change is that minor who cares? */ $entry->title = (strpos($node->title, $entry->title)) ? $entry->title : $node->title; $entry->teaser = $node->teaser; $entry->body = $node->body; $entry->uid = $node->uid; foreach ($fields as $var => $text) { $text = strtolower(str_replace(' ', '_', $text)); if (isset($node->project_issue[$text])) { $node->project_issue[$text] = trim($node->project_issue[$text]); switch ($var) { case 'pid': $project = node_load($node->project_issue[$text]); if ($project->nid) { $entry->project_issue['pid'] = $project->nid; } break; case 'category': if (($category = array_search($node->project_issue[$text], project_issue_category(0, 0)))) { $entry->project_issue['category'] = $category; } break; case 'priority': if (($priority = array_search($node->project_issue[$text], project_issue_priority()))) { $entry->project_issue['priority'] = $priority; } break; case 'rid': if ($entry->project_issue['pid'] && ($nid = db_result(db_query("SELECT nid FROM {project_release_nodes} WHERE pid = %d AND version = '%s'", $entry->project_issue['pid'], $node->project_issue[$text]), 0))) { $entry->project_issue['rid'] = $nid; } break; case 'assigned': if ($user = user_load(array('name' => $node->project_issue[$text]))) { $entry->project_issue['assigned'] = $user->uid; } break; case 'sid': if (($state = array_search($node->project_issue[$text], project_issue_state()))) { $entry->project_issue['sid'] = $state; } break; case 'component': if ($entry->project_issue['pid'] && ($project = node_load(array('nid' => $entry->project_issue['pid'], 'type' => 'project_project')))) { if ($project && in_array($node->project_issue[$text], $project->project_issue['components'])) { $entry->project_issue['component'] = $node->project_issue[$text]; } } break; } } } if (empty($entry->nid)) { $entry->sid = variable_get('project_issue_default_state', 1); $entry->type = 'project_issue'; $entry = node_validate($entry, $error); $error or ($entry->nid = node_save($entry)); } else { $error = project_comment_validate($entry); $error or project_comment_save($entry); } } else { $error['user'] = t('You are not authorized to access this page.'); } if ($error && $mailbox['replies']) { // Send the user his errors $mailto = mailhandler_get_fromaddress($header, $mailbox); $mailfrom = variable_get('site_mail', ini_get('sendmail_from')); $headers = array( 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', ); $body = t('You had some errors in your submission:'); foreach ($error as $field => $text) { $body .= "\n * $field: $text"; } drupal_mail('project_issue_mailhandler_error', $mailto, t('E-mail submission to !sn failed - !subj', array('!sn' => variable_get('site_name', 'Drupal'), '!subj' => $header->subject)), $body, $mailfrom, $headers); } // Return a NULL result so mailhandler doesn't save the node using the default methods. return NULL; } else { return $node; } } /** * preg_replace_callback() callback used for capturing URLs and transforming links * into footer links. */ function _project_issue_mail_url_callback($match = FALSE) { static $urls = array(); if (!empty($match) && is_array($match)) { $url = $match[2]; // If $url was an internal link, we need to strip the base_path // off before passing it to url(), to avoid doubling up on the base_path. // @todo Check that this actually works when using language specific url rewriting. $base_path = base_path(); $base_length = strlen($base_path); if (substr($url, 0, $base_length) == $base_path) { $url = substr($url, $base_length); } $urls[] = url($url, array('absolute' => TRUE)); return $match[3] .' ['. count($urls) .']'; } return $urls; } /** * Add a section to the email body. * Note: URL link numbers are not reset between calls to this function. */ function project_issue_mail_output(&$body, $html = 1, $format = FILTER_FORMAT_DEFAULT) { static $i = 0; if ($html) { $body = check_markup($body, $format, FALSE); // Convert inline links into footer links. //$pattern = '@<a +([^ >]+ )*?href *= *"([^>"]+?)"[^>]*>([^<]+?)</a>@i'; $pattern = '@<a[^>]*\shref\s*=\s*([\'"])([^>]+?)\1[^>]*>(.+?)</a>@is'; $body = preg_replace_callback($pattern, '_project_issue_mail_url_callback', $body); $urls = _project_issue_mail_url_callback(); if (count($urls)) { $body .= "\n"; for ($max = count($urls); $i < $max; $i++) { $body .= '['. ($i + 1) .'] '. $urls[$i] ."\n"; } } $body = preg_replace('!</?blockquote>!i', '"', $body); $body = preg_replace('!</?(em|i)>!i', '/', $body); $body = preg_replace('!</?(b|strong)>!i', '*', $body); $body = preg_replace("@<br />(?!\n)@i", "\n", $body); $body = preg_replace("@</p>(?!\n\n)@i", "\n\n", $body); $body = preg_replace("@<li>@i", "* ", $body); $body = preg_replace("@</li>\n?@i", "\n", $body); $body = strip_tags($body); $body = decode_entities($body); $body = wordwrap($body, 72); } else { $body = decode_entities($body); } } /** * Send mail notifications. */ function project_issue_mail_notify($nid) { global $user; if (defined('PROJECT_NOMAIL')) { return; } $node = node_load($nid, NULL, TRUE); + + // We don't want any notifications for unpublished nodes. + if (empty($node) || !$node->status) { + return; + } + $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); // Store a copy of the issue, so we can load the original issue values // below. $issue = drupal_clone($node); // Load in the original issue data here, since we want a running // reverse history. $original_issue_data = unserialize($node->project_issue['original_issue_data']); $fields = project_issue_field_labels('email'); foreach ($fields as $field => $label) { if ($field != 'name' && $field != 'updator') { $issue->original_issue_metadata->$field = $original_issue_data->$field; } } // Record users that are connected to this issue. $uids = array(); if (!empty($node->uid)) { $uids[$node->uid] = $node->uid; } if (!empty($node->project_issue['assigned'])) { $uids[$node->project_issue['assigned']] = $node->project_issue['assigned']; } // Create complete history of the bug report. $history = array($issue); $result = db_query('SELECT u.name, c.cid, c.nid, c.subject, c.comment, c.uid, c.format, pic.* FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid INNER JOIN {users} u ON u.uid = c.uid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp', $node->nid, COMMENT_PUBLISHED); while ($comment = db_fetch_object($result)) { $comment->comment = db_decode_blob($comment->comment); $comment->files = comment_upload_load_files($comment->cid); $history[] = $comment; // Record users that are connected to this issue. if ($comment->uid) { $uids[$comment->uid] = $comment->uid; } } if (count($uids)) { $placeholders = implode(',', array_fill(0, count($uids), '%d')); array_unshift($uids, $node->project_issue['pid']); $result = db_query("SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND (p.level = 2 OR (p.level = 1 AND u.uid IN ($placeholders)))", $uids); } else { $result = db_query('SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND p.level = 2', $node->project_issue['pid']); } // To save workload, check here if either the anonymous role or the // authenticated role has the 'view uploaded files' permission, since // we only need to process each user's file access permission if this // is NOT the case. $check_file_perms = !db_result(db_query("SELECT COUNT(*) FROM {permission} WHERE perm LIKE '%view uploaded files%' AND rid IN (%d, %d)", DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID)); // We need to determine if node_access() checks are necessary. The // check will be needed if any of the following is true: // 1. The node is not published. // 2. There is at least on node access control module enabled. // 3. Both the anonymous and authenticated user do not have // the 'access project issues' permission. $allowed_roles = user_roles(FALSE, 'access project issues'); if (isset($allowed_roles[DRUPAL_ANONYMOUS_RID]) || isset($allowed_roles[DRUPAL_AUTHENTICATED_RID])) { $anon_auth_access = TRUE; } $grants = module_implements('node_grants'); $check_node_access = $node->status != 1 || empty($anon_auth_access) || !empty($grants); $params['node'] = $node; $params['project'] = $project; $params['history'] = $history; $sender->name = t('!name (!site)', array('!name' => $user->name, '!site' => variable_get('site_name', 'Drupal'))); $sender->mail = strtr(variable_get('project_issue_reply_to', variable_get('site_mail', ini_get('sendmail_from'))), array('%project' => $project->project['uri'])); // The sender name is enclosed by double quotes below // to satisfy RFC2822 <http://www.faqs.org/rfcs/rfc2822.html>, // which requires double quotes when special characters (including // some punctuation) are used. See example in Appendix A.1.2. $from = '"' . mime_header_encode($sender->name) . "\" <$sender->mail>"; while ($recipient = db_fetch_object($result)) { // To save work, only go through a user_load if we need it. if ($check_file_perms || $check_node_access) { $account = user_load(array('uid' => $recipient->uid)); $language = user_preferred_language($account); } else { $language = language_default(); } $can_access = $check_node_access ? node_access('view', $node, $account) : TRUE; if ($can_access) { $display_files = $check_file_perms ? user_access('view uploaded files', $account) : TRUE; $params['display_files'] = $display_files; drupal_mail('project_issue', 'project_issue_update_notification', $recipient->mail, $language, $params, $from); } } if (is_array($project->project_issue['mail_copy_filter']) && count(array_filter($project->project_issue['mail_copy_filter'])) && !$project->project_issue['mail_copy_filter'][$node->project_issue['category']]) { return; } if (is_array($project->project_issue['mail_copy_filter_state']) && count(array_filter($project->project_issue['mail_copy_filter_state'])) && !$project->project_issue['mail_copy_filter_state'][$node->project_issue['sid']]) { return; } if (!empty($project->project_issue['mail_copy'])) { $params['display_files'] = TRUE; $message['body'][] = $links; $message['body'][] = project_issue_mail_generate_followup_mail_body($node, $history, TRUE); drupal_mail('project_issue', 'project_issue_update_notification', $project->project_issue['mail_copy'], language_default(), $params, $from); } } /** * Implementation of hook_mail(). */ function _project_issue_mail($key, &$message, $params) { global $base_url; switch ($key) { case "project_issue_update_notification": // There could be stale data in the cached node, so reset the cache. $node = $params['node']; $project = $params['project']; $history = $params['history']; $fields = project_issue_field_labels('email'); $domain = preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url); $message['headers'] += array( 'Date' => date('r'), 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', 'List-Id' => "$project->title <". $project->project['uri'] ."-issues-$domain>", 'List-Archive' => '<'. url('project/issues/'. $project->project['uri'], array('absolute' => TRUE)) .'>', 'List-Subscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>', 'List-Unsubscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>' ); // Comments exist, set headers accordingly. if (count($history) > 1) { foreach ($history as $comment) { // We need the most recent cid and the next most recent cid for the // message headers. Instead of issuing another query, just keep track // of them here. $previous_cid = isset($cid) ? $cid : ''; $cid = isset($comment->cid) ? $comment->cid : 0; } $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&cid=$cid&host=@$domain>"; $message['headers']['In-Reply-To'] = "<type=project&nid=$node->nid&host=@$domain>"; $message['headers']['References'] = "<type=project&nid=$node->nid&host=@$domain> <type=project&nid=$node->nid&cid=$previous_cid&host=@$domain> <type=project&nid=$node->nid&revcount=1&host=@$domain>"; } else { // Only original issue in this email. $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&host=@$domain>"; } project_issue_mail_output($node->title, 0); $message['subject'] = t('[!short_name] [!category] !title', array('!short_name' => $project->project['uri'], '!category' => $node->project_issue['category'], '!title' => $node->title)); // Create link to related node $links = t('Issue status update for !link', array('!link' => "\n". url("node/$node->nid", array('absolute' => TRUE)))) ."\n"; $links .= t('Post a follow up: !link', array('!link' => "\n". url("comment/reply/$node->nid", array('fragment' => 'comment-form', 'absolute' => TRUE)))) ."\n"; $message['body'][] = $links; $message['body'][] = project_issue_mail_generate_followup_mail_body($node, $history, $params['display_files']); break; case 'project_issue_critical_summary': $project = $params['project']; $message['headers'] += array( 'Date' => date('r'), 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', 'List-Id' => "$project->title <". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'-project-issues-digest>', 'List-Archive' => '<'. url('project/issues', array('query' => array('priorities' => '1'), 'absolute' => TRUE)) .'>', ); $message['subject'] = t('Release critical bugs for !date', array('!date' => date('F d, Y', time()))); $message['body'][] = $params['body']; break; case 'project_issue_reminder': $sender->name = variable_get('site_name', ''); $sender->mail = variable_get('site_mail', ''); $message['headers'] += array( 'Return-Path' => "<$sender->mail;>", 'Date' => date('r'), 'From' => "$sender->name <$sender->mail>", 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', 'List-Id' => "$sender->name <project-reminder-". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'>', 'List-Archive' => '<'. url('project', array('absolute' => TRUE)) .'>', ); $message['subject'] = t('Your submitted bugs for !date', array('!date' => date('F d, Y', time()))); $message['body'][] = $params['body']; break; } } /** * Format the body of an issue followup email. * * @param $node * The issue node. * @param $history * An array containing the history of issue followups. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A string of the email body. */ function project_issue_mail_generate_followup_mail_body($node, $history, $display_files) { global $user; static $output_with_files = NULL, $output_without_files = NULL; // Return cached output if available. if ($display_files) { if (isset($output_with_files)) { return $output_with_files; } } else { if (isset($output_without_files)) { return $output_without_files; } } // Get most recent update. $entry = array_pop($history); $node->project_issue['updator'] = $entry->name ? $entry->name : $user->name; // Check if the latest entry is actually the initial issue. if (empty($history)) { $metadata_previous = new stdClass(); // Have to get the metadata into the entry object. $metadata_entry = $entry->original_issue_metadata; $content = $entry->body; } else { $metadata_previous = end($history); // If the previous was the original issue, then we need to pull // out the metadata from project_issue. if (isset($metadata_previous->original_issue_metadata)) { $metadata_previous = $metadata_previous->original_issue_metadata; } $metadata_entry = $entry; $content = $entry->comment; } $fields = project_issue_field_labels('email'); $comment_changes = project_issue_metadata_changes($node, $metadata_previous, $metadata_entry, $fields); // Since $node->name will always be the original issue author, and since // $node->project_issue['updator'] isn't a property of either $previous or // $entry, these two properties will never show up as being different when // project_issue_metadata_changes() is called, and therefore neither of // these will ever be elements of the $comment_changes array. Since we do // want them to be printed in issue emails, we just need to add their labels // back into the $comment_changes array here, so that // theme_project_issue_mail_summary_field() will know to print the data for // these two fields. $comment_changes['name'] = array( 'label' => $fields['name'], ); $comment_changes['updator'] = array( 'label' => $fields['updator'], ); $summary = theme('project_issue_mail_summary', $entry, $node, $comment_changes, $display_files); // Create main body content project_issue_mail_output($content, 1, $entry->format); $body = "$content\n$entry->name\n"; $hr = str_repeat('-', 72); if (count($history)) { $body .= "\n\n"; $body .= t('Original issue:') ."\n"; $body .= project_issue_mail_format_entry(array_shift($history), $display_files, TRUE); if (count($history)) { $body .= "\n". t('Previous comments (!count):', array('!count' => count($history))) ."\n"; foreach ($history as $entry) { $body .= project_issue_mail_format_entry($entry, $display_files); } } } $output = "$summary\n$body"; // Set cached output. if ($display_files) { $output_with_files = $output; } else { $output_without_files = $output; } return $output; } /** * Themes the display of the issue metadata summary * that is shown at the top of an issue email. * * @param $entry * The object representing the current entry. This will be a node object * if the current entry is the original issue node; otherwise this will be * a comment object. * @param $node * The original issue node object. * @param $changes * A nested array containing the metadata changes between the original * issue and the first comment, or two consecutive comments. This array * is the output of the project_issue_metadata_changes() function. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A string containing the themed text of the issue metadata table. */ function theme_project_issue_mail_summary($entry, $node, $changes, $display_files) { // Mail summary (status values). $summary = ''; foreach ($changes as $field => $change) { $summary .= theme('project_issue_mail_summary_field', $node, $field, $change); } $summary .= project_issue_mail_format_attachments($entry, $display_files); return $summary; } /** * Theme the email output of one project issue metadata field. * * @param $node * The project issue node object. * @param $field_name * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * A themed line or lines of text ready for inclusion into the email body. */ function theme_project_issue_mail_summary_field($node, $field_name, $change) { // We need to run the label name through strip_tags here so that // the spacing isn't messed up if there are HTML tags in $change['label']. $text = str_pad(strip_tags($change['label']). ':', 14); $summary_row = ''; if (!empty($change['label']) && isset($change['old']) && isset($change['new']) && $field_name != 'updator' && $field_name != 'name') { if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])) { foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { $added[] = '+'. $item; } } elseif (!empty($change['new'])) { $added[] = '+'. $change['new']; } $summary_row = " $text". trim(implode(', ', $removed). ' ' .implode(', ', $added)) ."\n"; } else { $summary_row .= "-$text". project_issue_change_summary($field_name, $change['old']) ."\n"; $summary_row .= "+$text". project_issue_change_summary($field_name, $change['new']) ."\n"; } } elseif (!empty($change['label'])) { if (!empty($change['new'])) { // This condition is necessary when building the first email message of an // issue, since in this case $change['old'] should not exist. if (is_array($change['new'])) { $summary_row .= " $text". implode(', ', $change['new']) ."\n"; } else { $summary_row .= " $text". project_issue_change_summary($field_name, $change['new']) ."\n"; } } else { // This condition is where fields that are stored in the $node object and // which haven't changed but should be printed anyway get processed. // For example, the project, category, etc. are printed in each email // whether or not they have changed. // @TODO: Should we really assume the field in is $node->project_issue[]? if (isset($node->project_issue[$field_name])) { $summary_row .= " $text". project_issue_change_summary($field_name, $node->project_issue[$field_name]) ."\n"; } } } // HTML tags in the email will make it hard to read, so pass // this output through strip_tags(). return strip_tags($summary_row); } /** * Formats attachments for issue notification e-mails. * * @param $entry * An issue or followup object containing the file data. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A formatted string of file attachments. */ function project_issue_mail_format_attachments($entry, $display_files) { $output = ''; if ($display_files && is_array($entry->files)) { foreach ($entry->files as $file) { // Comment upload has it's files in an array, so cast to an object // for consistency. $file = (object) $file; $output .= ' '. str_pad(t('Attachment') .':', 14) . file_create_url($file->filepath) .' ('. format_size($file->filesize) .")\n"; } } return $output; } /** * Format an issue entry for display in an email. * * @param entry * The entry to the formatted. * @param $display_files * Boolean indicating if file attachments should be displayed. * @param is_original * Whether this entry is the original issue or a followup. Followup issues * will be automatically numbered. * @return * Formatted text for the entry. */ function project_issue_mail_format_entry($entry, $display_files, $is_original = FALSE) { static $history_count = 1; $hr = str_repeat('-', 72); $output = "$hr\n"; // Nodes and comments have different stamp fields. $timestamp = isset($entry->created) ? $entry->created : $entry->timestamp; if (!$is_original) { $output .= "$entry->subject -- "; } $output .= format_date($timestamp, 'large') ." : $entry->name\n"; if (!$is_original) { $output .= url("node/$entry->nid", array('fragment' => "comment-$entry->cid", 'absolute' => TRUE)) ."\n"; } $output .= project_issue_mail_format_attachments($entry, $display_files); // Must distinguish between nodes and comments -- here we do it // by looking for a revision ID. if (empty($entry->vid)) { $content = $entry->comment; } else { $content = $entry->body; } project_issue_mail_output($content, 1, $entry->format); if ($content) { $output .= "\n$content"; } return $output; }
Br3nda/drupal-module-project_issue
0ae998ce69e3350b3fd5cb72a712268199faf50e
#708474, #716756 by bdragon, dww: Fixed bug where Views go missing if hook_views_default_views() is called multiple times (which seems to happen regularly in Views 6.x-2.* after 6.x-2.8).
diff --git a/views/project_issue.views_default.inc b/views/project_issue.views_default.inc index 333bc9d..9e17ec1 100644 --- a/views/project_issue.views_default.inc +++ b/views/project_issue.views_default.inc @@ -1,70 +1,72 @@ <?php -// $Id: project_issue.views_default.inc,v 1.48 2009/09/23 00:21:36 dww Exp $ +// $Id: project_issue.views_default.inc,v 1.49 2010/02/18 00:34:30 dww Exp $ /** * @file * Provides default views on behalf of the project_issue module. */ /** * Implementation of hook_views_default_views(). */ function project_issue_views_default_views() { // Search the "default_views" directory for files ending in .view.php. $files = file_scan_directory(drupal_get_path('module', 'project_issue'). '/views/default_views', 'view.php'); foreach ($files as $absolute => $file) { - require_once $absolute; + // This is not require_once because it's possible that + // hook_views_default_views() gets called more than once. + require $absolute; if (isset($view)) { // $file->name has the ".php" stripped off, but still has the ".view". $view_name = substr($file->name, 0, strrpos($file->name, '.')); $views[$view_name] = $view; } } return $views; } /** * Add exposed filters for every taxonomy vocabulary for project_issue nodes. * * This is a helper function used by a few of the default view definitions. */ function _project_issue_views_add_taxonomy_filters(&$filters) { if (!module_exists('taxonomy')) { return; } $issue_vocabularies = taxonomy_get_vocabularies('project_issue'); $i = 0; foreach ($issue_vocabularies as $vid => $vocab) { $view_key = 'tid'; if ($i) { $view_key .= "_$i"; } $i++; $identifier = project_issue_views_filter_identifier($vocab->name); $filters[$view_key] = array( 'operator' => 'or', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 1, 'operator' => $identifier . '_op', 'identifier' => $identifier, 'label' => check_plain($vocab->name), 'optional' => 1, 'single' => 1, 'remember' => 0, ), 'type' => 'textfield', 'vid' => $vid, 'id' => 'tid', 'table' => 'term_node', 'field' => 'tid', 'hierarchy' => 0, 'relationship' => 'none', 'reduce_duplicates' => 1, ); } }
Br3nda/drupal-module-project_issue
4f0b11559d58b3d61fad04027020eb676e71d1c7
#710996 by dww: Fixed a PHP notice when editing issue followup comments.
diff --git a/includes/comment.inc b/includes/comment.inc index dbf9495..44e9040 100644 --- a/includes/comment.inc +++ b/includes/comment.inc @@ -1,673 +1,674 @@ <?php -// $Id: comment.inc,v 1.156 2010/01/17 00:26:58 dww Exp $ +// $Id: comment.inc,v 1.157 2010/02/18 00:19:27 dww Exp $ function project_issue_comment(&$arg, $op) { // $arg can be a comment object, or a form or form_values. if (is_object($arg)) { $nid = $arg->nid; } elseif (is_array($arg)) { $nid = is_array($arg['nid']) ? $arg['nid']['#value'] : $arg['nid']; } $node = node_load($nid); if ($node->type != 'project_issue') { return; } // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Maintain an array of project ids that are affected by this comment // operation. We'll use this to invalidate the "Issue cockpit" block cache // for any of these projects. $affected_projects = array(); switch ($op) { case 'insert': // Get a lock on the issue in order to generate the next comment ID. $tries = 20; $sleep_increment = 0; while ($tries) { $lock = db_query("UPDATE {project_issues} SET db_lock = 1 WHERE nid = %d AND db_lock = 0", $arg['nid']); if (db_affected_rows()) { $id = db_result(db_query("SELECT last_comment_id FROM {project_issues} WHERE nid = %d", $arg['nid'])) + 1; db_query("UPDATE {project_issues} SET last_comment_id = %d, db_lock = 0 WHERE nid = %d", $id, $arg['nid']); break; } // Wait a random and increasing amount of time before the next attempt. $sleep = rand(10000, 1000000) + $sleep_increment; usleep($sleep); $sleep_increment += 50000; $tries--; } if (isset($id)) { $rid = isset($arg['project_info']['rid']) ? $arg['project_info']['rid'] : 0; db_query("INSERT INTO {project_issue_comments} (nid, cid, pid, rid, component, category, priority, assigned, sid, title, timestamp, comment_number) VALUES (%d, %d, %d, %d, '%s', '%s', %d, %d, %d, '%s', %d, %d)", $arg['nid'], $arg['cid'], $arg['project_info']['pid'], $rid, $arg['project_info']['component'], $arg['category'], $arg['priority'], $arg['project_info']['assigned'], $arg['sid'], $arg['title'], $arg['timestamp'], $id); db_query("UPDATE {comments} SET subject = '%s' WHERE cid = %d", "#$id", $arg['cid']); project_issue_update_by_comment($arg, 'insert'); $affected_projects[$old_data->pid] = 1; $affected_projects[$arg['project_info']['pid']] = 1; } else { drupal_set_message(t('There was an error submitting your comment -- please try again. If the problem persists, contact the system administrator.'), 'error'); watchdog('project_issue', 'Error obtaining lock for project issue %nid', array('%nid' => $arg['nid']), WATCHDOG_ERROR, 'node/'. $arg['nid']); // This is a bit extreme, but we have to clean up the failed comment, // or it will appear on the issue. _comment_delete_thread((object) $arg); _comment_update_node_statistics($arg['nid']); cache_clear_all(); // The hard redirect prevents any bogus data from being inserted for the failed comment. drupal_goto('node/'. $arg['nid']); } break; case 'update': project_issue_update_by_comment($arg, 'update'); // Updating a comment can't change anything relevant about the issue for // the purposes of the issue blocks, so we don't need to touch // $affected_projects here. break; case 'delete': // Save the project that's specified in this comment so we can // invalidate its issue block cache. $deleted_comment_project_id = db_result(db_query("SELECT pid FROM {project_issue_comments} WHERE cid = %d", $arg->cid)); $affected_projects[$deleted_comment_project_id] = 1; // Actually delete the comment db_query("DELETE FROM {project_issue_comments} WHERE cid = %d", $arg->cid); $current_data = project_issue_update_by_comment($arg, 'delete'); // We should also invalidate the block cache for whatever project is now // used for this issue, since we might be deleting a comment that moved // an issue from one project to another. $affected_projects[$current_data->pid] = 1; break; case 'view': if (isset($arg->cid)) { $project_issue_table = project_issue_comment_view($original_node, $arg); } else { // Previewing a comment. $test = drupal_clone($arg); $test->pid = $arg->project_info['pid']; $test->component = $arg->project_info['component']; $test->assigned = $arg->project_info['assigned']; // Add a dummy rid if necessary -- prevents incorrect change data. $test->rid = isset($arg->project_info['rid']) ? $arg->project_info['rid'] : 0; $comment_changes = project_issue_metadata_changes($node, $old_data, $test, project_issue_field_labels('web')); $project_issue_table = theme('project_issue_comment_table', $comment_changes); } if ($project_issue_table) { $arg->comment = '<div class="project-issue"><div class="summary">'. $project_issue_table .'</div></div>' . $arg->comment; } break; } // If there are any affected projects, invalidate the block cache for those. if (!empty($affected_projects)) { foreach ($affected_projects as $pid => $value) { $cid = 'project_issue_cockpit_block:'. $pid; cache_clear_all($cid, 'cache'); } } } /** * Add project issue metadata to the comment form. * * @param $form * Reference to form structure. * @param $form_state * Current form state. */ function project_issue_form_comment_form_alter(&$form, &$form_state) { $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Comment body is not required since we validate that ourselves. unset($form['comment_filter']['comment']['#required']); // The 'your name' item just wastes screen estate. unset($form['_author']); // For existing comments, we want to preserve the comment subject, // Even if the subject field is disabled. if ($cid = $form['cid']['#value']) { $subject = db_result(db_query('SELECT subject FROM {comments} WHERE cid = %d', $cid)); } // For new comments, show the expected next number for previews. // This is only for show, the number will be generated when the comment // is posted. else { $next_id = db_result(db_query('SELECT last_comment_id FROM {project_issues} WHERE nid = %d', $form['nid']['#value'])) + 1; $subject = "#$next_id"; // Clobber the comment signature for new followups if necessary. // TODO: Revamp this for Drupal 6. if (!variable_get('project_issue_show_comment_signatures', 0)) { $form['comment_filter']['comment']['#default_value'] = ''; } } $form['subject'] = array( '#type' => 'value', '#value' => $subject, ); // Any time we're on a reply page, show the full issue below the reply. if (project_issue_is_comment_reply()) { $form['#pre_render'][] = 'project_issue_comment_pre_render'; } // Make sure project is current here -- it may have changed when posted. if (!empty($form_state['values']['project_info']['pid'])) { $node->project_issue['pid'] = $form_state['values']['project_info']['pid']; } $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); project_issue_set_breadcrumb($node, $project); // Only allow metadata changes on new followups. if (isset($form['cid']['#value'])) { return; } // We have to set $form['#action'] to prevent AHAH nastiness. if (!empty($form['pid']['#value'])) { $form['#action'] = url('comment/reply/' . $nid . '/' . $form['pid']['#value']); } else { $form['#action'] = url('comment/reply/' . $nid); } // We need to ask for almost the same metadata as project issue itself // so let's reuse the form. $form += project_issue_form($node, $form_state, TRUE); // comment.module is basically still FAPI v1. It sets the preview button to // #type 'button', so FAPI doesn't really consider that a form submission. // However, we depend on the form being rebuilt on preview to do our magic. // Thanks to a change in 6.14 core, form.inc will only rebuild the form if // $form_state['submitted'] is TRUE. So, we set the preview button to // actually be a 'submit' button so that the form is rebuilt on preview and // our comment preview code can kick in. $form['preview']['#type'] = 'submit'; // We need this otherwise pid collides with comment. $form['project_info']['#tree'] = TRUE; $form['project_info']['#weight'] = -2; // Remove the form item that displays the current project, and // replace the static single project value with a select list // of all projects to make swapping simpler. unset($form['project_info']['project_display']); $uris = NULL; if (variable_get('project_issue_autocomplete', 0) == 1) { $form['project_info']['project_title'] = array( '#type' => 'textfield', '#title' => t('Project'), '#default_value' => $project->title, '#required' => TRUE, '#weight' => -1, '#size' => 35, '#autocomplete_path' => 'project/autocomplete/issue/project', '#attributes' => array( 'onFocus' => 'project_issue_autocomplete_handler()', ), '#ahah' => array( 'progress' => array( 'type' => 'none', ), 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', ), ); } else { $projects = project_projects_select_options($uris); $form['project_info']['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#default_value' => $project->nid, '#options' => $projects, '#required' => TRUE, '#weight' => -1, '#ahah' => array( 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', 'event' => 'change', ), ); } $form['issue_info']['#weight'] = -1; $form['#prefix'] = '<div class="project-issue"><div class="node-form"><div class="standard">'; $form['#suffix'] = '</div></div></div>'; $form['original_issue'] = array( '#type' => 'fieldset', '#title' => t('Edit issue settings'), '#description' => t('Note: changing any of these items will update the issue\'s overall values.'), '#collapsible' => TRUE, '#weight' => -10, ); $form['original_issue']['title'] = array( '#type' => 'textfield', '#title' => t('Issue title'), '#maxlength' => 128, '#default_value' => $node->title, '#weight' => -30, '#required' => TRUE, ); $form['project_info']['assigned'] = $form['issue_info']['assigned']; unset($form['issue_info']['assigned']); $form['project_info']['#prefix'] = '<div id="project-info-wrapper" class="inline-options">'; $form['project_info']['#suffix'] = '</div>'; // Remove the 'Project information' and 'Issue information' fieldsets, // since we'll move everything inside the 'Edit issue settings' fieldset. unset($form['project_info']['#type'], $form['project_info']['#title']); unset($form['issue_info']['#type'], $form['issue_info']['#title']); // Restructure the UI to de-emphasize the original project form inputs. $form['original_issue']['project_info'] = $form['project_info']; $form['original_issue']['issue_info'] = $form['issue_info']; unset($form['project_info'], $form['issue_info']); unset($form['issue_details'], $form['project_help']); drupal_add_js(drupal_get_path('module', 'project_issue') .'/project_issue.js'); } /** * Validate issue metadata on the comment form. * * @param $form * The Drupal form structure. * @param $form_state * The current state of the form. */ function project_issue_form_comment_validate($form, &$form_state) { if (empty($form['cid']['#value']) && variable_get('project_issue_autocomplete', 0) == 1) { if (empty($form_state['values']['project_info']['project_title'])) { form_set_error('project_title', t('You must enter a project to navigate to.')); } else { $pid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_info']['project_title'], 'project_project')); if (empty($pid)) { form_set_error('project_info][project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_info']['project_title']))); } else { $form_state['values']['project_info']['pid'] = $pid; } } } if (!empty($form_state['rebuild'])) { return; } + + // Only validate metadata changes on new followups. + if (isset($form_state['values']['cid'])) { + return; + } + $values = $form_state['values']; $project_info = $form_state['values']['project_info']; $nid = $values['nid']; $node = node_load($nid); // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Adjust new file attachments to go to the issues directory. // We have to do this during validate, otherwise we might miss // adjusting the filename before comment upload saves it (module weighting) // TODO: is this still true? project_issue_change_comment_upload_path($values); - // Only validate metadata changes on new followups. - if (isset($values['cid'])) { - return; - } - // Make sure project is current here -- it may have changed when posted. if (isset($project_info['pid'])) { $node->project_issue['pid'] = $project_info['pid']; } $project = node_load($node->project_issue['pid']); if (!empty($project) && $project->type == 'project_project') { // Force all comments to be a child of the main issue, to match the // flat display, and also to prevent accidentally deleting a thread. $form_state['values']['pid'] = 0; // Validate version. if (module_exists('project_release') && isset($project_info['rid']) && ($releases = project_release_get_releases($project, 0, 'version', 'all', array($project_info['rid'])))) { $rid = $project_info['rid']; if ($rid && !in_array($rid, array_keys($releases))) { $rid = 0; } // Check to make sure this release is not marked as an invalid // release node for user selection. $invalid_rids = variable_get('project_issue_invalid_releases', array()); if (!empty($invalid_rids) && ((empty($rid) && in_array($node->project_issue['rid'], $invalid_rids)) || in_array($rid, $invalid_rids))) { form_set_error('project_info][rid', t('%version is not a valid version, please select a different value.', array('%version' => $releases[$node->project_issue['rid']]))); } elseif (empty($rid)) { form_set_error('project_info][rid', t('You have to specify a valid version.')); } } // Add a dummy rid if necessary -- prevents incorrect change data. else { $rid = 0; } // Validate component. $component = $project_info['component']; if ($component && !in_array($component, $project->project_issue['components'])) { $component = 0; } empty($component) && form_set_error('project_info][component', t('You have to specify a valid component.')); } else { form_set_error('project_info][pid', t('You have to specify a valid project.')); } empty($values['category']) && form_set_error('category', t('You have to specify a valid category.')); // Now, make sure the comment changes *something* about the issue. // If the user uploaded a file, so long as it's not marked for removal, // we consider that a valid change to the issue, too. $has_file = FALSE; $files = isset($values['files']) ? $values['files'] : array(); foreach ($files as $number => $data) { if (empty($data['remove'])) { $has_file = TRUE; break; } } if (!$has_file && empty($values['comment'])) { $comment = drupal_clone((object) $values); $comment->pid = $project_info['pid']; $comment->component = $component; $comment->rid = $rid; $comment->assigned = $project_info['assigned']; $comment_changes = project_issue_metadata_changes($node, $old_data, $comment, project_issue_field_labels('web')); // If the PID changed, rebuild the form if (isset($comment_changes['pid']['new']) && $comment_changes['pid']['new'] === TRUE) { $form_state['rebuild'] = TRUE; } $has_change = FALSE; foreach ($comment_changes as $field => $changes) { if (isset($changes['new'])) { $has_change = TRUE; break; } } if (!$has_change) { form_set_error('comment', t('You must either add a comment, upload a file, or change something about this issue.')); } } } /** * Theme a project issue metadata table. * * @param $comment_changes * Array containing metadata differences between comments * as returned by project_issue_metadata_changes(). * @return * The themed metadata table. */ function theme_project_issue_comment_table($comment_changes) { $rows = array(); foreach ($comment_changes as $field => $change) { if (!empty($change['label']) && isset($change['old']) && isset($change['new'])) { $rows[] = theme('project_issue_comment_table_row', $field, $change); } } return $rows ? theme('table', array(), $rows) : ''; } /** * Theme a single row of the project issue metadata changes table. * * @param $field * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * An array representing one row of the table. * * NOTE: If you override this theme function, you *must* make sure * that you sanitize all output from this function that is displayed * to the user. No further escaping/filtering of the data in this * table will take place after this function. In most cases * this means that you need to run the $change['label'], $change['old'], * and $change['new'] values through either the check_plain() or * filter_xss() function to prevent XSS and other types * of problems due to any malicious input in these * field values. */ function theme_project_issue_comment_table_row($field, $change) { // Allow anchor, emphasis, and strong tags in metadata tables. $allowed_tags = array('a', 'em', 'strong'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])){ foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { $added[] = '+'. $item; } } elseif (!empty($change['new'])) { $added[] = '+'. $change['new']; } return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(implode(', ', $removed), $allowed_tags), filter_xss(implode(', ', $added), $allowed_tags), ); } elseif (in_array($field, $plain_fields)) { return array( filter_xss($change['label'], $allowed_tags) .':', check_plain(project_issue_change_summary($field, $change['old'])), '&raquo; '. check_plain(project_issue_change_summary($field, $change['new'])), ); } else { return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(project_issue_change_summary($field, $change['old']), $allowed_tags), '&raquo; '. filter_xss(project_issue_change_summary($field, $change['new']), $allowed_tags), ); } } /** * Returns the issue metadata table for a comment. * * @param $node * The corresponding node. * @param $comment * The comment, if it's set then metadata will be returned. If it's not * set then metadata will be precalculated. * @return * A themed table of issue metadata. */ function project_issue_comment_view(&$node, $comment = NULL) { static $project_issue_tables; if (isset($comment)) { return isset($project_issue_tables[$comment->cid]) ? $project_issue_tables[$comment->cid] : ''; } if (!empty($node->comment_count)) { $old = unserialize(db_result(db_query('SELECT original_issue_data FROM {project_issues} WHERE nid = %d', $node->nid))); $labels = project_issue_field_labels('web'); $result = db_query('SELECT p.cid, p.title, p.pid, p.rid, p.component, p.category, p.priority, p.assigned, p.sid FROM {project_issue_comments} p INNER JOIN {comments} c ON p.cid = c.cid WHERE p.nid = %d AND c.status = %d ORDER BY p.timestamp ASC', $node->nid, COMMENT_PUBLISHED); while ($followup = db_fetch_object($result)) { $followup_changes = project_issue_metadata_changes($node, $old, $followup, project_issue_field_labels('web')); $project_issue_tables[$followup->cid] = theme('project_issue_comment_table', $followup_changes); $old = $followup; } } } /** * Updates the project issue based on the comment inserted/updated/deleted. * * @param $comment_data * The comment data that's been submitted. * @param $op * The comment operation performed, 'insert', 'update', 'delete'. * @return * An object representing the comment data used to update the issue. */ function project_issue_update_by_comment($comment_data, $op) { switch ($op) { case 'insert': // Massage the incoming data so the structure is consistent throughout the function. $comment_data['component'] = $comment_data['project_info']['component']; $comment_data['pid'] = $comment_data['project_info']['pid']; $comment_data['rid'] = isset($comment_data['project_info']['rid']) ? $comment_data['project_info']['rid'] : 0; unset ($comment_data['project_info']); $comment_data = (object) $comment_data; // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. if (!isset($comment_data->followup_no_mail)) { // Temporary hack to get around sending of auto-close emails. project_issue_set_mail_notify($comment_data->nid); } break; case 'update': $comment_data = (object) $comment_data; break; } // In order to deal with deleted/unpublished comments, make sure that we're performing // the updates to the issue with the latest available published comment. $comment_data = project_issue_get_newest_comment($comment_data); // Update the issue data to reflect the new final states. db_query("UPDATE {project_issues} SET pid = %d, category = '%s', component = '%s', priority = %d, rid = %d, assigned = %d, sid = %d WHERE nid = %d", $comment_data->pid, $comment_data->category, $comment_data->component, $comment_data->priority, $comment_data->rid, $comment_data->assigned, $comment_data->sid, $comment_data->nid); // Update the issue title. $node = node_load($comment_data->nid, NULL, TRUE); // Don't use cached since we changed data above. $node->title = $comment_data->title; // This also updates the changed date of the issue. node_save($node); // Return the object of comment data we used to update the issue. return $comment_data; } /** * Adjusts the filepath of issue followups so files are saved to * the correct issues directory. * * @param $comment * An array of the submitted comment values. */ function project_issue_change_comment_upload_path(&$comment) { static $run = NULL; // Only for new comments with attachments. if (empty($comment['cid']) && isset($comment['files']) && !isset($run)) { $run = TRUE; // Make sure this only gets run once. project_issue_rewrite_issue_filepath($comment['files']); } } /** * Retrieves the newest published comment for an issue. * * @param $comment_data * An object representing the current comment being edited * @return * An object representing the most recent published comment for the issue. */ function project_issue_get_newest_comment($comment_data) { // Get the cid of the most recent comment. $latest_cid = db_result(db_query_range('SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp DESC', $comment_data->nid, COMMENT_PUBLISHED, 0, 1)); if ($latest_cid) { $comment_data = db_fetch_object(db_query('SELECT * FROM {project_issue_comments} WHERE cid = %d', $latest_cid)); } // No more comments on the issue -- use the original issue metadata. else { // nid isn't stored in the original issue data, so capture it here and pass back // into the object. $nid = $comment_data->nid; $comment_data = unserialize(db_result(db_query("SELECT original_issue_data FROM {project_issues} WHERE nid = %d", $comment_data->nid))); $comment_data->nid = $nid; } return $comment_data; } /** * Test to determine if the active page is the comment reply form. * * @return * TRUE if the active page is the comment reply form, FALSE otherwise. */ function project_issue_is_comment_reply() { return arg(0) == 'comment' && arg(1) == 'reply'; } /** * Test to determine if the active page is the comment edit form. * * @return * TRUE if the active page is the comment edit form, FALSE otherwise. */ function project_issue_is_comment_edit() { return arg(0) == 'comment' && arg(1) == 'edit'; } /** * Appends the comment thread to the comment reply form. */ function project_issue_comment_pre_render($form) { // Force the correct formatting. $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; $suffix = empty($form['#suffix']) ? '' : $form['#suffix']; $node = node_load($form['nid']['#value']); // Unfortunately, the comment module blindly puts the node view // after the comment form on preview, in the case where the comment // parent is 0. If we want our issue previews to be consistent, this // ugly hack is necessary. if (isset($form['#parameters'][1]['values']['op']) && $form['#parameters'][1]['values']['op'] == t('Preview')) { $preview = comment_render($node, 0); } else { $preview = node_show($node, 0); } $form['#suffix'] = $suffix . $preview; return $form; }
Br3nda/drupal-module-project_issue
3db7ca82108df31bf637a6b6cd764088e6a2fdb0
#405478 by bdragon: Clean up mail.inc and only include it when necessary.
diff --git a/includes/mail.inc b/includes/mail.inc index 73b71b1..fa082d4 100644 --- a/includes/mail.inc +++ b/includes/mail.inc @@ -1,660 +1,684 @@ <?php -// $Id: mail.inc,v 1.123 2010/01/17 00:16:15 dww Exp $ +// $Id: mail.inc,v 1.124 2010/02/08 18:02:59 bdragon Exp $ -function project_issue_mailhandler($node, $result, $i, $header, $mailbox) { +/** + * @file + * Project issue tracking email notifications system. + */ + +/** + * Implementation of hook_mailhandler(). + */ +function _project_issue_mailhandler($node, $result, $i, $header, $mailbox) { if ($node->type == 'project') { if (node_access('create', 'project_issue')) { $node->nid = preg_replace('/@.+/', '', $node->nid); if ($node->nid) { /* ** Base the new entry on the node it belongs to, this ensures all ** values are initially correct. */ $entry = node_load(array('nid' => $node->nid, 'type' => 'project_issue')); } // Possible attributes $fields = array( 'pid' => t('Project'), 'category' => t('Category'), 'component' => t('Component'), 'priority' => t('Priority'), 'rid' => t('Version'), 'assigned' => t('Assigned to'), 'sid' => t('Status') ); /* ** Only change the title if it doesn't have the old title in it. ** This should prevent the title from changing due to added ** prefixes. It may on occasion make false positives, but if ** a title change is that minor who cares? */ $entry->title = (strpos($node->title, $entry->title)) ? $entry->title : $node->title; $entry->teaser = $node->teaser; $entry->body = $node->body; $entry->uid = $node->uid; foreach ($fields as $var => $text) { $text = strtolower(str_replace(' ', '_', $text)); if (isset($node->project_issue[$text])) { $node->project_issue[$text] = trim($node->project_issue[$text]); switch ($var) { case 'pid': $project = node_load($node->project_issue[$text]); if ($project->nid) { $entry->project_issue['pid'] = $project->nid; } break; case 'category': if (($category = array_search($node->project_issue[$text], project_issue_category(0, 0)))) { $entry->project_issue['category'] = $category; } break; case 'priority': if (($priority = array_search($node->project_issue[$text], project_issue_priority()))) { $entry->project_issue['priority'] = $priority; } break; case 'rid': if ($entry->project_issue['pid'] && ($nid = db_result(db_query("SELECT nid FROM {project_release_nodes} WHERE pid = %d AND version = '%s'", $entry->project_issue['pid'], $node->project_issue[$text]), 0))) { $entry->project_issue['rid'] = $nid; } break; case 'assigned': if ($user = user_load(array('name' => $node->project_issue[$text]))) { $entry->project_issue['assigned'] = $user->uid; } break; case 'sid': if (($state = array_search($node->project_issue[$text], project_issue_state()))) { $entry->project_issue['sid'] = $state; } break; case 'component': if ($entry->project_issue['pid'] && ($project = node_load(array('nid' => $entry->project_issue['pid'], 'type' => 'project_project')))) { if ($project && in_array($node->project_issue[$text], $project->project_issue['components'])) { $entry->project_issue['component'] = $node->project_issue[$text]; } } break; } } } if (empty($entry->nid)) { $entry->sid = variable_get('project_issue_default_state', 1); $entry->type = 'project_issue'; $entry = node_validate($entry, $error); $error or ($entry->nid = node_save($entry)); } else { $error = project_comment_validate($entry); $error or project_comment_save($entry); } } else { $error['user'] = t('You are not authorized to access this page.'); } if ($error && $mailbox['replies']) { // Send the user his errors $mailto = mailhandler_get_fromaddress($header, $mailbox); $mailfrom = variable_get('site_mail', ini_get('sendmail_from')); $headers = array( 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', ); $body = t('You had some errors in your submission:'); foreach ($error as $field => $text) { $body .= "\n * $field: $text"; } drupal_mail('project_issue_mailhandler_error', $mailto, t('E-mail submission to !sn failed - !subj', array('!sn' => variable_get('site_name', 'Drupal'), '!subj' => $header->subject)), $body, $mailfrom, $headers); } // Return a NULL result so mailhandler doesn't save the node using the default methods. return NULL; } else { return $node; } } -function project_mail_urls($url = 0) { +/** + * preg_replace_callback() callback used for capturing URLs and transforming links + * into footer links. + */ +function _project_issue_mail_url_callback($match = FALSE) { static $urls = array(); - if ($url) { - // If $url is an internal link (eg. '/project/project'), such - // as might be returned from the url() function with the - // $absolute parameter set to FALSE, we must remove - // the leading slash before passing this path through the url() - // function again, or otherwise we'll get two slashes in a row - // and thus a bad URL. - if (substr($url, 0, 1) == '/') { - $url = substr($url, 1); + if (!empty($match) && is_array($match)) { + $url = $match[2]; + + // If $url was an internal link, we need to strip the base_path + // off before passing it to url(), to avoid doubling up on the base_path. + // @todo Check that this actually works when using language specific url rewriting. + $base_path = base_path(); + $base_length = strlen($base_path); + if (substr($url, 0, $base_length) == $base_path) { + $url = substr($url, $base_length); } - $urls[] = strpos($url, '://') ? $url : url($url, array('absolute' => TRUE)); - return count($urls); + + $urls[] = url($url, array('absolute' => TRUE)); + return $match[3] .' ['. count($urls) .']'; } return $urls; } -function project_mail_output(&$body, $html = 1, $format = FILTER_FORMAT_DEFAULT) { +/** + * Add a section to the email body. + * Note: URL link numbers are not reset between calls to this function. + */ +function project_issue_mail_output(&$body, $html = 1, $format = FILTER_FORMAT_DEFAULT) { static $i = 0; if ($html) { $body = check_markup($body, $format, FALSE); - $pattern = '@<a +([^ >]+ )*?href *= *"([^>"]+?)"[^>]*>([^<]+?)</a>@ei'; - $body = preg_replace($pattern, "'\\3 ['. project_mail_urls('\\2') .']'", $body); - $urls = project_mail_urls(); + + // Convert inline links into footer links. + //$pattern = '@<a +([^ >]+ )*?href *= *"([^>"]+?)"[^>]*>([^<]+?)</a>@i'; + $pattern = '@<a[^>]*\shref\s*=\s*([\'"])([^>]+?)\1[^>]*>(.+?)</a>@is'; + $body = preg_replace_callback($pattern, '_project_issue_mail_url_callback', $body); + $urls = _project_issue_mail_url_callback(); + if (count($urls)) { $body .= "\n"; for ($max = count($urls); $i < $max; $i++) { $body .= '['. ($i + 1) .'] '. $urls[$i] ."\n"; } } $body = preg_replace('!</?blockquote>!i', '"', $body); $body = preg_replace('!</?(em|i)>!i', '/', $body); $body = preg_replace('!</?(b|strong)>!i', '*', $body); $body = preg_replace("@<br />(?!\n)@i", "\n", $body); $body = preg_replace("@</p>(?!\n\n)@i", "\n\n", $body); $body = preg_replace("@<li>@i", "* ", $body); $body = preg_replace("@</li>\n?@i", "\n", $body); $body = strip_tags($body); $body = decode_entities($body); $body = wordwrap($body, 72); } else { $body = decode_entities($body); } } -function project_mail_notify($nid) { +/** + * Send mail notifications. + */ +function project_issue_mail_notify($nid) { global $user; if (defined('PROJECT_NOMAIL')) { return; } $node = node_load($nid, NULL, TRUE); $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); // Store a copy of the issue, so we can load the original issue values // below. $issue = drupal_clone($node); // Load in the original issue data here, since we want a running // reverse history. $original_issue_data = unserialize($node->project_issue['original_issue_data']); $fields = project_issue_field_labels('email'); foreach ($fields as $field => $label) { if ($field != 'name' && $field != 'updator') { $issue->original_issue_metadata->$field = $original_issue_data->$field; } } // Record users that are connected to this issue. $uids = array(); if (!empty($node->uid)) { $uids[$node->uid] = $node->uid; } if (!empty($node->project_issue['assigned'])) { $uids[$node->project_issue['assigned']] = $node->project_issue['assigned']; } // Create complete history of the bug report. $history = array($issue); $result = db_query('SELECT u.name, c.cid, c.nid, c.subject, c.comment, c.uid, c.format, pic.* FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid INNER JOIN {users} u ON u.uid = c.uid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp', $node->nid, COMMENT_PUBLISHED); while ($comment = db_fetch_object($result)) { $comment->comment = db_decode_blob($comment->comment); $comment->files = comment_upload_load_files($comment->cid); $history[] = $comment; // Record users that are connected to this issue. if ($comment->uid) { $uids[$comment->uid] = $comment->uid; } } if (count($uids)) { $placeholders = implode(',', array_fill(0, count($uids), '%d')); array_unshift($uids, $node->project_issue['pid']); $result = db_query("SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND (p.level = 2 OR (p.level = 1 AND u.uid IN ($placeholders)))", $uids); } else { $result = db_query('SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND p.level = 2', $node->project_issue['pid']); } // To save workload, check here if either the anonymous role or the // authenticated role has the 'view uploaded files' permission, since // we only need to process each user's file access permission if this // is NOT the case. $check_file_perms = !db_result(db_query("SELECT COUNT(*) FROM {permission} WHERE perm LIKE '%view uploaded files%' AND rid IN (%d, %d)", DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID)); // We need to determine if node_access() checks are necessary. The // check will be needed if any of the following is true: // 1. The node is not published. // 2. There is at least on node access control module enabled. // 3. Both the anonymous and authenticated user do not have // the 'access project issues' permission. $allowed_roles = user_roles(FALSE, 'access project issues'); if (isset($allowed_roles[DRUPAL_ANONYMOUS_RID]) || isset($allowed_roles[DRUPAL_AUTHENTICATED_RID])) { $anon_auth_access = TRUE; } $grants = module_implements('node_grants'); $check_node_access = $node->status != 1 || empty($anon_auth_access) || !empty($grants); $params['node'] = $node; $params['project'] = $project; $params['history'] = $history; $sender->name = t('!name (!site)', array('!name' => $user->name, '!site' => variable_get('site_name', 'Drupal'))); $sender->mail = strtr(variable_get('project_issue_reply_to', variable_get('site_mail', ini_get('sendmail_from'))), array('%project' => $project->project['uri'])); // The sender name is enclosed by double quotes below // to satisfy RFC2822 <http://www.faqs.org/rfcs/rfc2822.html>, // which requires double quotes when special characters (including // some punctuation) are used. See example in Appendix A.1.2. $from = '"' . mime_header_encode($sender->name) . "\" <$sender->mail>"; while ($recipient = db_fetch_object($result)) { // To save work, only go through a user_load if we need it. if ($check_file_perms || $check_node_access) { $account = user_load(array('uid' => $recipient->uid)); $language = user_preferred_language($account); } else { $language = language_default(); } $can_access = $check_node_access ? node_access('view', $node, $account) : TRUE; if ($can_access) { $display_files = $check_file_perms ? user_access('view uploaded files', $account) : TRUE; $params['display_files'] = $display_files; drupal_mail('project_issue', 'project_issue_update_notification', $recipient->mail, $language, $params, $from); } } if (is_array($project->project_issue['mail_copy_filter']) && count(array_filter($project->project_issue['mail_copy_filter'])) && !$project->project_issue['mail_copy_filter'][$node->project_issue['category']]) { return; } if (is_array($project->project_issue['mail_copy_filter_state']) && count(array_filter($project->project_issue['mail_copy_filter_state'])) && !$project->project_issue['mail_copy_filter_state'][$node->project_issue['sid']]) { return; } if (!empty($project->project_issue['mail_copy'])) { $params['display_files'] = TRUE; $message['body'][] = $links; - $message['body'][] = project_mail_generate_followup_mail_body($node, $history, TRUE); + $message['body'][] = project_issue_mail_generate_followup_mail_body($node, $history, TRUE); drupal_mail('project_issue', 'project_issue_update_notification', $project->project_issue['mail_copy'], language_default(), $params, $from); } } -/* - * Implementation of hook_mail() +/** + * Implementation of hook_mail(). */ -function project_issue_mail($key, &$message, $params) { +function _project_issue_mail($key, &$message, $params) { global $base_url; switch ($key) { case "project_issue_update_notification": // There could be stale data in the cached node, so reset the cache. $node = $params['node']; $project = $params['project']; $history = $params['history']; $fields = project_issue_field_labels('email'); $domain = preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url); $message['headers'] += array( 'Date' => date('r'), 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', 'List-Id' => "$project->title <". $project->project['uri'] ."-issues-$domain>", 'List-Archive' => '<'. url('project/issues/'. $project->project['uri'], array('absolute' => TRUE)) .'>', 'List-Subscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>', 'List-Unsubscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>' ); // Comments exist, set headers accordingly. if (count($history) > 1) { foreach ($history as $comment) { // We need the most recent cid and the next most recent cid for the // message headers. Instead of issuing another query, just keep track // of them here. $previous_cid = isset($cid) ? $cid : ''; $cid = isset($comment->cid) ? $comment->cid : 0; } $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&cid=$cid&host=@$domain>"; $message['headers']['In-Reply-To'] = "<type=project&nid=$node->nid&host=@$domain>"; $message['headers']['References'] = "<type=project&nid=$node->nid&host=@$domain> <type=project&nid=$node->nid&cid=$previous_cid&host=@$domain> <type=project&nid=$node->nid&revcount=1&host=@$domain>"; } else { // Only original issue in this email. $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&host=@$domain>"; } - project_mail_output($node->title, 0); + project_issue_mail_output($node->title, 0); $message['subject'] = t('[!short_name] [!category] !title', array('!short_name' => $project->project['uri'], '!category' => $node->project_issue['category'], '!title' => $node->title)); // Create link to related node $links = t('Issue status update for !link', array('!link' => "\n". url("node/$node->nid", array('absolute' => TRUE)))) ."\n"; $links .= t('Post a follow up: !link', array('!link' => "\n". url("comment/reply/$node->nid", array('fragment' => 'comment-form', 'absolute' => TRUE)))) ."\n"; $message['body'][] = $links; - $message['body'][] = project_mail_generate_followup_mail_body($node, $history, $params['display_files']); + $message['body'][] = project_issue_mail_generate_followup_mail_body($node, $history, $params['display_files']); break; case 'project_issue_critical_summary': $project = $params['project']; $message['headers'] += array( 'Date' => date('r'), 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', 'List-Id' => "$project->title <". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'-project-issues-digest>', 'List-Archive' => '<'. url('project/issues', array('query' => array('priorities' => '1'), 'absolute' => TRUE)) .'>', ); $message['subject'] = t('Release critical bugs for !date', array('!date' => date('F d, Y', time()))); $message['body'][] = $params['body']; break; case 'project_issue_reminder': $sender->name = variable_get('site_name', ''); $sender->mail = variable_get('site_mail', ''); $message['headers'] += array( 'Return-Path' => "<$sender->mail;>", 'Date' => date('r'), 'From' => "$sender->name <$sender->mail>", 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', 'List-Id' => "$sender->name <project-reminder-". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'>', 'List-Archive' => '<'. url('project', array('absolute' => TRUE)) .'>', ); $message['subject'] = t('Your submitted bugs for !date', array('!date' => date('F d, Y', time()))); $message['body'][] = $params['body']; break; } } /** * Format the body of an issue followup email. * * @param $node * The issue node. * @param $history * An array containing the history of issue followups. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A string of the email body. */ -function project_mail_generate_followup_mail_body($node, $history, $display_files) { +function project_issue_mail_generate_followup_mail_body($node, $history, $display_files) { global $user; static $output_with_files = NULL, $output_without_files = NULL; // Return cached output if available. if ($display_files) { if (isset($output_with_files)) { return $output_with_files; } } else { if (isset($output_without_files)) { return $output_without_files; } } // Get most recent update. $entry = array_pop($history); $node->project_issue['updator'] = $entry->name ? $entry->name : $user->name; // Check if the latest entry is actually the initial issue. if (empty($history)) { $metadata_previous = new stdClass(); // Have to get the metadata into the entry object. $metadata_entry = $entry->original_issue_metadata; $content = $entry->body; } else { $metadata_previous = end($history); // If the previous was the original issue, then we need to pull // out the metadata from project_issue. if (isset($metadata_previous->original_issue_metadata)) { $metadata_previous = $metadata_previous->original_issue_metadata; } $metadata_entry = $entry; $content = $entry->comment; } $fields = project_issue_field_labels('email'); $comment_changes = project_issue_metadata_changes($node, $metadata_previous, $metadata_entry, $fields); // Since $node->name will always be the original issue author, and since // $node->project_issue['updator'] isn't a property of either $previous or // $entry, these two properties will never show up as being different when // project_issue_metadata_changes() is called, and therefore neither of // these will ever be elements of the $comment_changes array. Since we do // want them to be printed in issue emails, we just need to add their labels // back into the $comment_changes array here, so that // theme_project_issue_mail_summary_field() will know to print the data for // these two fields. $comment_changes['name'] = array( 'label' => $fields['name'], ); $comment_changes['updator'] = array( 'label' => $fields['updator'], ); $summary = theme('project_issue_mail_summary', $entry, $node, $comment_changes, $display_files); // Create main body content - project_mail_output($content, 1, $entry->format); + project_issue_mail_output($content, 1, $entry->format); $body = "$content\n$entry->name\n"; $hr = str_repeat('-', 72); if (count($history)) { $body .= "\n\n"; $body .= t('Original issue:') ."\n"; - $body .= project_mail_format_entry(array_shift($history), $display_files, TRUE); + $body .= project_issue_mail_format_entry(array_shift($history), $display_files, TRUE); if (count($history)) { $body .= "\n". t('Previous comments (!count):', array('!count' => count($history))) ."\n"; foreach ($history as $entry) { - $body .= project_mail_format_entry($entry, $display_files); + $body .= project_issue_mail_format_entry($entry, $display_files); } } } $output = "$summary\n$body"; // Set cached output. if ($display_files) { $output_with_files = $output; } else { $output_without_files = $output; } return $output; } /** * Themes the display of the issue metadata summary - * that is shown at the top of an issue emai. + * that is shown at the top of an issue email. * * @param $entry * The object representing the current entry. This will be a node object * if the current entry is the original issue node; otherwise this will be * a comment object. * @param $node * The original issue node object. * @param $changes * A nested array containing the metadata changes between the original * issue and the first comment, or two consecutive comments. This array * is the output of the project_issue_metadata_changes() function. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A string containing the themed text of the issue metadata table. */ function theme_project_issue_mail_summary($entry, $node, $changes, $display_files) { // Mail summary (status values). $summary = ''; foreach ($changes as $field => $change) { $summary .= theme('project_issue_mail_summary_field', $node, $field, $change); } - $summary .= project_mail_format_attachments($entry, $display_files); + $summary .= project_issue_mail_format_attachments($entry, $display_files); return $summary; } /** * Theme the email output of one project issue metadata field. * * @param $node * The project issue node object. * @param $field_name * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * A themed line or lines of text ready for inclusion into the email body. */ function theme_project_issue_mail_summary_field($node, $field_name, $change) { // We need to run the label name through strip_tags here so that // the spacing isn't messed up if there are HTML tags in $change['label']. $text = str_pad(strip_tags($change['label']). ':', 14); $summary_row = ''; if (!empty($change['label']) && isset($change['old']) && isset($change['new']) && $field_name != 'updator' && $field_name != 'name') { if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])) { foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { $added[] = '+'. $item; } } elseif (!empty($change['new'])) { $added[] = '+'. $change['new']; } $summary_row = " $text". trim(implode(', ', $removed). ' ' .implode(', ', $added)) ."\n"; } else { $summary_row .= "-$text". project_issue_change_summary($field_name, $change['old']) ."\n"; $summary_row .= "+$text". project_issue_change_summary($field_name, $change['new']) ."\n"; } } elseif (!empty($change['label'])) { if (!empty($change['new'])) { // This condition is necessary when building the first email message of an // issue, since in this case $change['old'] should not exist. if (is_array($change['new'])) { $summary_row .= " $text". implode(', ', $change['new']) ."\n"; } else { $summary_row .= " $text". project_issue_change_summary($field_name, $change['new']) ."\n"; } } else { // This condition is where fields that are stored in the $node object and // which haven't changed but should be printed anyway get processed. // For example, the project, category, etc. are printed in each email // whether or not they have changed. // @TODO: Should we really assume the field in is $node->project_issue[]? if (isset($node->project_issue[$field_name])) { $summary_row .= " $text". project_issue_change_summary($field_name, $node->project_issue[$field_name]) ."\n"; } } } // HTML tags in the email will make it hard to read, so pass // this output through strip_tags(). return strip_tags($summary_row); } /** * Formats attachments for issue notification e-mails. * * @param $entry * An issue or followup object containing the file data. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A formatted string of file attachments. */ -function project_mail_format_attachments($entry, $display_files) { +function project_issue_mail_format_attachments($entry, $display_files) { $output = ''; if ($display_files && is_array($entry->files)) { foreach ($entry->files as $file) { // Comment upload has it's files in an array, so cast to an object // for consistency. $file = (object) $file; $output .= ' '. str_pad(t('Attachment') .':', 14) . file_create_url($file->filepath) .' ('. format_size($file->filesize) .")\n"; } } return $output; } /** * Format an issue entry for display in an email. * * @param entry * The entry to the formatted. * @param $display_files * Boolean indicating if file attachments should be displayed. * @param is_original * Whether this entry is the original issue or a followup. Followup issues * will be automatically numbered. * @return * Formatted text for the entry. */ -function project_mail_format_entry($entry, $display_files, $is_original = FALSE) { +function project_issue_mail_format_entry($entry, $display_files, $is_original = FALSE) { static $history_count = 1; $hr = str_repeat('-', 72); $output = "$hr\n"; // Nodes and comments have different stamp fields. $timestamp = isset($entry->created) ? $entry->created : $entry->timestamp; if (!$is_original) { $output .= "$entry->subject -- "; } $output .= format_date($timestamp, 'large') ." : $entry->name\n"; if (!$is_original) { $output .= url("node/$entry->nid", array('fragment' => "comment-$entry->cid", 'absolute' => TRUE)) ."\n"; } - $output .= project_mail_format_attachments($entry, $display_files); + $output .= project_issue_mail_format_attachments($entry, $display_files); // Must distinguish between nodes and comments -- here we do it // by looking for a revision ID. if (empty($entry->vid)) { $content = $entry->comment; } else { $content = $entry->body; } - project_mail_output($content, 1, $entry->format); + project_issue_mail_output($content, 1, $entry->format); if ($content) { $output .= "\n$content"; } return $output; } - diff --git a/project_issue.module b/project_issue.module index da306e7..7963b6a 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,1368 +1,1383 @@ <?php -// $Id: project_issue.module,v 1.177 2010/01/30 19:01:33 dww Exp $ +// $Id: project_issue.module,v 1.178 2010/02/08 18:02:59 bdragon Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); - foreach (array('comment', 'mail') as $file) { - module_load_include('inc', 'project_issue', "includes/$file"); - } + module_load_include('inc', 'project_issue', 'includes/comment'); /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = !empty($changes['uid']) ? $changes['uid'] : $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': module_load_include('inc', 'project_issue', 'includes/project_node'); project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } +/** + * Implementation of hook_mail(). (stub function) + */ +function project_issue_mail($key, &$message, $params) { + module_load_include('inc', 'project_issue', 'includes/mail'); + return _project_issue_mail($key, $message, $params); +} + +/** + * Implementation of hook_mailhandler(). (stub function) + */ +function project_issue_mailhandler($node, $result, $i, $header, $mailbox) { + module_load_include('inc', 'project_issue', 'includes/mail'); + return _project_issue_mailhandler($node, $result, $i, $header, $mailbox); +} + /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implement hook_delete() for project issue nodes. */ function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } /** * Implement hook_form() for project issue nodes. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_form($node, $form_state, $include_metadata_fields); } /** * Implement hook_validate() for project issue nodes. */ function project_issue_validate($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_validate($node); } /** * Implement hook_insert() for project issue nodes. */ function project_issue_insert($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_insert($node); } /** * Implement hook_view() for project issue nodes. */ function project_issue_view($node, $teaser = FALSE, $page = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_view'); return _project_issue_view($node, $teaser, $page); } /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { + module_load_include('inc', 'project_issue', 'includes/mail'); foreach ($nids as $nid) { - project_mail_notify($nid); + project_issue_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes)); } $output = '<span class="project-issue-status-'. $node->project_issue['sid'] .' project-issue-status-info">'. $link; if ($include_assigned && !empty($username)) { $output .= ' <span class="project-issue-assigned-user">'. t('Assigned to: @username', array('@username' => $username)) .'</span>'; } $output .= '</span>'; return $output; } /** * Implementation of hook_form_filter_tips(). * @ingroup project_issue_filter */ function project_issue_filter_tips($delta, $format, $long = FALSE) { if ($long) { return t("References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically, with the title of the issue appended. The status of the issue is shown on hover. If '@' is appended (e.g. [#1234@]), the user the issue is assigned to will also be printed."); } else { return t('Project issue numbers (ex. [#12345]) turn into links automatically.'); } } /** * Implementation of hook_filter(). * @ingroup project_issue_filter */ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { switch ($op) { case 'list': return array(0 => t('Project Issue to link filter')); case 'description': return t('Converts references to project issues (in the form of [#12345]) into links. Caching should be disabled if node access control modules are used.'); case 'no cache': return FALSE; case 'prepare': return $text; case 'process': $regex = '(?:(?<!\w)\[#\d+(?:-\d+)?(@)?\](?!\w))|<pre>.*?<\/pre>|<code>.*?<\/code>|<a(?:[^>"\']|"[^"]*"|\'[^\']*\')*>.*?<\/a>'; $text = preg_replace_callback("/$regex/", 'project_issue_link_filter_callback', $text); return $text; } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); $allowed_roles = user_roles(FALSE, 'access project issues'); $conflict_anonymous = empty($allowed_roles[DRUPAL_ANONYMOUS_RID]); foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if (!empty($grants) && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Implement hook_token_list() (from token.module). */ function project_issue_token_list($type) { if ($type == 'node') { $tokens['node'] = array( 'project_issue_pid' => t("The issue's project nid"), 'project_issue_project_title' => t("The issue's project title"), 'project_issue_project_title-raw' => t("The issue's project title raw"), 'project_issue_project_shortname' => t("The issue's project short name"), 'project_issue_category' => t("The issue's category (bug, feature)"), 'project_issue_component' => t("The issue's component"), 'project_issue_priority' => t("The issue's priority"), 'project_issue_version' => t("The issue's version (if any)"), 'project_issue_assigned' => t("The name of the user an issue is assigned to"), 'project_issue_status' => t("The issue's status"), ); return $tokens; } } /** * Implement hook_token_values() (from token.module). */ function project_issue_token_values($type = 'all', $object = NULL) { if ($type == 'node') { // Defaults in case it's not an issue or we can't load its parent project. $values = array( 'project_issue_pid' => '', 'project_issue_project_title' => '', 'project_issue_project_title-raw' => '', 'project_issue_project_shortname' => '', 'project_issue_category' => '', 'project_issue_component' => '', 'project_issue_priority' => '', 'project_issue_version' => '', 'project_issue_assigned' => '', 'project_issue_status' => '', ); if ($object->type == 'project_issue') { if (!empty($object->project_issue)) { // If $node->project_issue exists, use it. $issue = (object)$object->project_issue; } else { $issue = $object; } if ($project = node_load($issue->pid)) { $values['project_issue_pid'] = intval($issue->pid); $values['project_issue_project_title'] = check_plain($project->title); $values['project_issue_project_title-raw'] = $project->title; $values['project_issue_project_shortname'] = check_plain($project->project['uri']); } if (module_exists('project_release') && !empty($issue->rid) && $release = node_load($issue->rid)) { $values['project_issue_version'] = check_plain($release->project_release['version']); } if (!empty($issue->assigned)) { $account = user_load($issue->assigned); $values['project_issue_assigned'] = check_plain($account->name); } $values['project_issue_category'] = project_issue_category($issue->category, FALSE); $values['project_issue_component'] = check_plain($issue->component); $values['project_issue_priority'] = project_issue_priority($issue->priority); $values['project_issue_status'] = check_plain(project_issue_state($issue->sid)); } return $values; } } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } }
Br3nda/drupal-module-project_issue
e50f30ad791354942fd99441615c36b61e7554f3
#699978 by dww: Fixed bug where the 'project-issue' class was incorrectly applied to all views tables, not just the ones using the issue table style.
diff --git a/project_issue.module b/project_issue.module index b537b65..da306e7 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,514 +1,514 @@ <?php -// $Id: project_issue.module,v 1.176 2010/01/17 00:38:19 dww Exp $ +// $Id: project_issue.module,v 1.177 2010/01/30 19:01:33 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); foreach (array('comment', 'mail') as $file) { module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); @@ -1005,754 +1005,754 @@ function project_issue_my_projects_table() { $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes)); } $output = '<span class="project-issue-status-'. $node->project_issue['sid'] .' project-issue-status-info">'. $link; if ($include_assigned && !empty($username)) { $output .= ' <span class="project-issue-assigned-user">'. t('Assigned to: @username', array('@username' => $username)) .'</span>'; } $output .= '</span>'; return $output; } /** * Implementation of hook_form_filter_tips(). * @ingroup project_issue_filter */ function project_issue_filter_tips($delta, $format, $long = FALSE) { if ($long) { return t("References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically, with the title of the issue appended. The status of the issue is shown on hover. If '@' is appended (e.g. [#1234@]), the user the issue is assigned to will also be printed."); } else { return t('Project issue numbers (ex. [#12345]) turn into links automatically.'); } } /** * Implementation of hook_filter(). * @ingroup project_issue_filter */ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { switch ($op) { case 'list': return array(0 => t('Project Issue to link filter')); case 'description': return t('Converts references to project issues (in the form of [#12345]) into links. Caching should be disabled if node access control modules are used.'); case 'no cache': return FALSE; case 'prepare': return $text; case 'process': $regex = '(?:(?<!\w)\[#\d+(?:-\d+)?(@)?\](?!\w))|<pre>.*?<\/pre>|<code>.*?<\/code>|<a(?:[^>"\']|"[^"]*"|\'[^\']*\')*>.*?<\/a>'; $text = preg_replace_callback("/$regex/", 'project_issue_link_filter_callback', $text); return $text; } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); $allowed_roles = user_roles(FALSE, 'access project issues'); $conflict_anonymous = empty($allowed_roles[DRUPAL_ANONYMOUS_RID]); foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if (!empty($grants) && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Implement hook_token_list() (from token.module). */ function project_issue_token_list($type) { if ($type == 'node') { $tokens['node'] = array( 'project_issue_pid' => t("The issue's project nid"), 'project_issue_project_title' => t("The issue's project title"), 'project_issue_project_title-raw' => t("The issue's project title raw"), 'project_issue_project_shortname' => t("The issue's project short name"), 'project_issue_category' => t("The issue's category (bug, feature)"), 'project_issue_component' => t("The issue's component"), 'project_issue_priority' => t("The issue's priority"), 'project_issue_version' => t("The issue's version (if any)"), 'project_issue_assigned' => t("The name of the user an issue is assigned to"), 'project_issue_status' => t("The issue's status"), ); return $tokens; } } /** * Implement hook_token_values() (from token.module). */ function project_issue_token_values($type = 'all', $object = NULL) { if ($type == 'node') { // Defaults in case it's not an issue or we can't load its parent project. $values = array( 'project_issue_pid' => '', 'project_issue_project_title' => '', 'project_issue_project_title-raw' => '', 'project_issue_project_shortname' => '', 'project_issue_category' => '', 'project_issue_component' => '', 'project_issue_priority' => '', 'project_issue_version' => '', 'project_issue_assigned' => '', 'project_issue_status' => '', ); if ($object->type == 'project_issue') { if (!empty($object->project_issue)) { // If $node->project_issue exists, use it. $issue = (object)$object->project_issue; } else { $issue = $object; } if ($project = node_load($issue->pid)) { $values['project_issue_pid'] = intval($issue->pid); $values['project_issue_project_title'] = check_plain($project->title); $values['project_issue_project_title-raw'] = $project->title; $values['project_issue_project_shortname'] = check_plain($project->project['uri']); } if (module_exists('project_release') && !empty($issue->rid) && $release = node_load($issue->rid)) { $values['project_issue_version'] = check_plain($release->project_release['version']); } if (!empty($issue->assigned)) { $account = user_load($issue->assigned); $values['project_issue_assigned'] = check_plain($account->name); } $values['project_issue_category'] = project_issue_category($issue->category, FALSE); $values['project_issue_component'] = check_plain($issue->component); $values['project_issue_priority'] = project_issue_priority($issue->priority); $values['project_issue_status'] = check_plain(project_issue_state($issue->sid)); } return $values; } } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } + $variables['class'] .= " project-issue"; } - $variables['class'] .= " project-issue"; } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( 'info' => t('Issue cockpit'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, ); return $form; } elseif ($op == 'save' && $delta == 'issue_cockpit') { variable_set('project_issue_cockpit_categories', $edit['project_issue_cockpit_categories']); // Invalidate the cache for this block since the categories might change. cache_clear_all('project_issue_cockpit_block:', 'cache', TRUE); } elseif ($op == 'view' && ($node = project_get_project_from_menu()) && !empty($node->project_issue['issues']) && node_access('view', $node)) { $cid = 'project_issue_cockpit_block:'. $node->nid; if (($cache = cache_get($cid))) { $block = $cache->data; } else { module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); $block = array( 'subject' => t('Issues for @project', array('@project' => $node->title)), 'content' => theme('project_issue_issue_cockpit', $node), ); cache_set($cid, $block); } return $block; } } /** * Implemenation of hook_project_page_link_alter(). * * Add project_issue-specific links to the array of project links. */ function project_issue_project_page_link_alter(&$links, $node) { // TODO: Assumes "patch" issue status values (http://drupal.org/node/27865). // Prepend a link to the development section to view pending patches. if (!empty($node->project['uri'])) { $patches['pending_patches'] = l(t('View pending patches'), 'project/issues/search/'. $node->project['uri'], array('query' => 'status[]=8&status[]=13&status[]=14')); $links['development']['links'] = $patches + $links['development']['links']; } }
Br3nda/drupal-module-project_issue
25b6e0d545feb69aacef1c94dddd7ca84ba3f4a7
#656918 by jennifer.chang, dww: Fixed PHP notices in requirements check for if the [#xxxx] issue link filter is properly configured.
diff --git a/project_issue.module b/project_issue.module index 360a94e..b537b65 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,514 +1,514 @@ <?php -// $Id: project_issue.module,v 1.175 2010/01/17 00:10:23 dww Exp $ +// $Id: project_issue.module,v 1.176 2010/01/17 00:38:19 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); foreach (array('comment', 'mail') as $file) { module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); @@ -690,1036 +690,1031 @@ function project_issue_add_followup($changes) { } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': module_load_include('inc', 'project_issue', 'includes/project_node'); project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implement hook_delete() for project issue nodes. */ function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } /** * Implement hook_form() for project issue nodes. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_form($node, $form_state, $include_metadata_fields); } /** * Implement hook_validate() for project issue nodes. */ function project_issue_validate($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_validate($node); } /** * Implement hook_insert() for project issue nodes. */ function project_issue_insert($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_insert($node); } /** * Implement hook_view() for project issue nodes. */ function project_issue_view($node, $teaser = FALSE, $page = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_view'); return _project_issue_view($node, $teaser, $page); } /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { foreach ($nids as $nid) { project_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes)); } $output = '<span class="project-issue-status-'. $node->project_issue['sid'] .' project-issue-status-info">'. $link; if ($include_assigned && !empty($username)) { $output .= ' <span class="project-issue-assigned-user">'. t('Assigned to: @username', array('@username' => $username)) .'</span>'; } $output .= '</span>'; return $output; } /** * Implementation of hook_form_filter_tips(). * @ingroup project_issue_filter */ function project_issue_filter_tips($delta, $format, $long = FALSE) { if ($long) { return t("References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically, with the title of the issue appended. The status of the issue is shown on hover. If '@' is appended (e.g. [#1234@]), the user the issue is assigned to will also be printed."); } else { return t('Project issue numbers (ex. [#12345]) turn into links automatically.'); } } /** * Implementation of hook_filter(). * @ingroup project_issue_filter */ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { switch ($op) { case 'list': return array(0 => t('Project Issue to link filter')); case 'description': return t('Converts references to project issues (in the form of [#12345]) into links. Caching should be disabled if node access control modules are used.'); case 'no cache': return FALSE; case 'prepare': return $text; case 'process': $regex = '(?:(?<!\w)\[#\d+(?:-\d+)?(@)?\](?!\w))|<pre>.*?<\/pre>|<code>.*?<\/code>|<a(?:[^>"\']|"[^"]*"|\'[^\']*\')*>.*?<\/a>'; $text = preg_replace_callback("/$regex/", 'project_issue_link_filter_callback', $text); return $text; } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); - if (!empty($grants)) { - $conflict_grants = TRUE; - } $allowed_roles = user_roles(FALSE, 'access project issues'); - if (!isset($allowed_roles[DRUPAL_ANONYMOUS_RID])) { - $conflict_anonymous = TRUE; - } + $conflict_anonymous = empty($allowed_roles[DRUPAL_ANONYMOUS_RID]); foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { - if ($conflict_grants && filter_format_allowcache($format)) { + if (!empty($grants) && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Implement hook_token_list() (from token.module). */ function project_issue_token_list($type) { if ($type == 'node') { $tokens['node'] = array( 'project_issue_pid' => t("The issue's project nid"), 'project_issue_project_title' => t("The issue's project title"), 'project_issue_project_title-raw' => t("The issue's project title raw"), 'project_issue_project_shortname' => t("The issue's project short name"), 'project_issue_category' => t("The issue's category (bug, feature)"), 'project_issue_component' => t("The issue's component"), 'project_issue_priority' => t("The issue's priority"), 'project_issue_version' => t("The issue's version (if any)"), 'project_issue_assigned' => t("The name of the user an issue is assigned to"), 'project_issue_status' => t("The issue's status"), ); return $tokens; } } /** * Implement hook_token_values() (from token.module). */ function project_issue_token_values($type = 'all', $object = NULL) { if ($type == 'node') { // Defaults in case it's not an issue or we can't load its parent project. $values = array( 'project_issue_pid' => '', 'project_issue_project_title' => '', 'project_issue_project_title-raw' => '', 'project_issue_project_shortname' => '', 'project_issue_category' => '', 'project_issue_component' => '', 'project_issue_priority' => '', 'project_issue_version' => '', 'project_issue_assigned' => '', 'project_issue_status' => '', ); if ($object->type == 'project_issue') { if (!empty($object->project_issue)) { // If $node->project_issue exists, use it. $issue = (object)$object->project_issue; } else { $issue = $object; } if ($project = node_load($issue->pid)) { $values['project_issue_pid'] = intval($issue->pid); $values['project_issue_project_title'] = check_plain($project->title); $values['project_issue_project_title-raw'] = $project->title; $values['project_issue_project_shortname'] = check_plain($project->project['uri']); } if (module_exists('project_release') && !empty($issue->rid) && $release = node_load($issue->rid)) { $values['project_issue_version'] = check_plain($release->project_release['version']); } if (!empty($issue->assigned)) { $account = user_load($issue->assigned); $values['project_issue_assigned'] = check_plain($account->name); } $values['project_issue_category'] = project_issue_category($issue->category, FALSE); $values['project_issue_component'] = check_plain($issue->component); $values['project_issue_priority'] = project_issue_priority($issue->priority); $values['project_issue_status'] = check_plain(project_issue_state($issue->sid)); } return $values; } } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } } $variables['class'] .= " project-issue"; } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( 'info' => t('Issue cockpit'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, );
Br3nda/drupal-module-project_issue
3795f1fe1be4e1fd724eabc0765faf525a8f117b
#679344 by carlos8f: Removed empty tables in comments with no metadata changes.
diff --git a/includes/comment.inc b/includes/comment.inc index 2a3f689..dbf9495 100644 --- a/includes/comment.inc +++ b/includes/comment.inc @@ -1,673 +1,673 @@ <?php -// $Id: comment.inc,v 1.155 2009/09/23 00:27:05 dww Exp $ +// $Id: comment.inc,v 1.156 2010/01/17 00:26:58 dww Exp $ function project_issue_comment(&$arg, $op) { // $arg can be a comment object, or a form or form_values. if (is_object($arg)) { $nid = $arg->nid; } elseif (is_array($arg)) { $nid = is_array($arg['nid']) ? $arg['nid']['#value'] : $arg['nid']; } $node = node_load($nid); if ($node->type != 'project_issue') { return; } // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Maintain an array of project ids that are affected by this comment // operation. We'll use this to invalidate the "Issue cockpit" block cache // for any of these projects. $affected_projects = array(); switch ($op) { case 'insert': // Get a lock on the issue in order to generate the next comment ID. $tries = 20; $sleep_increment = 0; while ($tries) { $lock = db_query("UPDATE {project_issues} SET db_lock = 1 WHERE nid = %d AND db_lock = 0", $arg['nid']); if (db_affected_rows()) { $id = db_result(db_query("SELECT last_comment_id FROM {project_issues} WHERE nid = %d", $arg['nid'])) + 1; db_query("UPDATE {project_issues} SET last_comment_id = %d, db_lock = 0 WHERE nid = %d", $id, $arg['nid']); break; } // Wait a random and increasing amount of time before the next attempt. $sleep = rand(10000, 1000000) + $sleep_increment; usleep($sleep); $sleep_increment += 50000; $tries--; } if (isset($id)) { $rid = isset($arg['project_info']['rid']) ? $arg['project_info']['rid'] : 0; db_query("INSERT INTO {project_issue_comments} (nid, cid, pid, rid, component, category, priority, assigned, sid, title, timestamp, comment_number) VALUES (%d, %d, %d, %d, '%s', '%s', %d, %d, %d, '%s', %d, %d)", $arg['nid'], $arg['cid'], $arg['project_info']['pid'], $rid, $arg['project_info']['component'], $arg['category'], $arg['priority'], $arg['project_info']['assigned'], $arg['sid'], $arg['title'], $arg['timestamp'], $id); db_query("UPDATE {comments} SET subject = '%s' WHERE cid = %d", "#$id", $arg['cid']); project_issue_update_by_comment($arg, 'insert'); $affected_projects[$old_data->pid] = 1; $affected_projects[$arg['project_info']['pid']] = 1; } else { drupal_set_message(t('There was an error submitting your comment -- please try again. If the problem persists, contact the system administrator.'), 'error'); watchdog('project_issue', 'Error obtaining lock for project issue %nid', array('%nid' => $arg['nid']), WATCHDOG_ERROR, 'node/'. $arg['nid']); // This is a bit extreme, but we have to clean up the failed comment, // or it will appear on the issue. _comment_delete_thread((object) $arg); _comment_update_node_statistics($arg['nid']); cache_clear_all(); // The hard redirect prevents any bogus data from being inserted for the failed comment. drupal_goto('node/'. $arg['nid']); } break; case 'update': project_issue_update_by_comment($arg, 'update'); // Updating a comment can't change anything relevant about the issue for // the purposes of the issue blocks, so we don't need to touch // $affected_projects here. break; case 'delete': // Save the project that's specified in this comment so we can // invalidate its issue block cache. $deleted_comment_project_id = db_result(db_query("SELECT pid FROM {project_issue_comments} WHERE cid = %d", $arg->cid)); $affected_projects[$deleted_comment_project_id] = 1; // Actually delete the comment db_query("DELETE FROM {project_issue_comments} WHERE cid = %d", $arg->cid); $current_data = project_issue_update_by_comment($arg, 'delete'); // We should also invalidate the block cache for whatever project is now // used for this issue, since we might be deleting a comment that moved // an issue from one project to another. $affected_projects[$current_data->pid] = 1; break; case 'view': if (isset($arg->cid)) { $project_issue_table = project_issue_comment_view($original_node, $arg); } else { // Previewing a comment. $test = drupal_clone($arg); $test->pid = $arg->project_info['pid']; $test->component = $arg->project_info['component']; $test->assigned = $arg->project_info['assigned']; // Add a dummy rid if necessary -- prevents incorrect change data. $test->rid = isset($arg->project_info['rid']) ? $arg->project_info['rid'] : 0; $comment_changes = project_issue_metadata_changes($node, $old_data, $test, project_issue_field_labels('web')); $project_issue_table = theme('project_issue_comment_table', $comment_changes); } if ($project_issue_table) { $arg->comment = '<div class="project-issue"><div class="summary">'. $project_issue_table .'</div></div>' . $arg->comment; } break; } // If there are any affected projects, invalidate the block cache for those. if (!empty($affected_projects)) { foreach ($affected_projects as $pid => $value) { $cid = 'project_issue_cockpit_block:'. $pid; cache_clear_all($cid, 'cache'); } } } /** * Add project issue metadata to the comment form. * * @param $form * Reference to form structure. * @param $form_state * Current form state. */ function project_issue_form_comment_form_alter(&$form, &$form_state) { $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Comment body is not required since we validate that ourselves. unset($form['comment_filter']['comment']['#required']); // The 'your name' item just wastes screen estate. unset($form['_author']); // For existing comments, we want to preserve the comment subject, // Even if the subject field is disabled. if ($cid = $form['cid']['#value']) { $subject = db_result(db_query('SELECT subject FROM {comments} WHERE cid = %d', $cid)); } // For new comments, show the expected next number for previews. // This is only for show, the number will be generated when the comment // is posted. else { $next_id = db_result(db_query('SELECT last_comment_id FROM {project_issues} WHERE nid = %d', $form['nid']['#value'])) + 1; $subject = "#$next_id"; // Clobber the comment signature for new followups if necessary. // TODO: Revamp this for Drupal 6. if (!variable_get('project_issue_show_comment_signatures', 0)) { $form['comment_filter']['comment']['#default_value'] = ''; } } $form['subject'] = array( '#type' => 'value', '#value' => $subject, ); // Any time we're on a reply page, show the full issue below the reply. if (project_issue_is_comment_reply()) { $form['#pre_render'][] = 'project_issue_comment_pre_render'; } // Make sure project is current here -- it may have changed when posted. if (!empty($form_state['values']['project_info']['pid'])) { $node->project_issue['pid'] = $form_state['values']['project_info']['pid']; } $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); project_issue_set_breadcrumb($node, $project); // Only allow metadata changes on new followups. if (isset($form['cid']['#value'])) { return; } // We have to set $form['#action'] to prevent AHAH nastiness. if (!empty($form['pid']['#value'])) { $form['#action'] = url('comment/reply/' . $nid . '/' . $form['pid']['#value']); } else { $form['#action'] = url('comment/reply/' . $nid); } // We need to ask for almost the same metadata as project issue itself // so let's reuse the form. $form += project_issue_form($node, $form_state, TRUE); // comment.module is basically still FAPI v1. It sets the preview button to // #type 'button', so FAPI doesn't really consider that a form submission. // However, we depend on the form being rebuilt on preview to do our magic. // Thanks to a change in 6.14 core, form.inc will only rebuild the form if // $form_state['submitted'] is TRUE. So, we set the preview button to // actually be a 'submit' button so that the form is rebuilt on preview and // our comment preview code can kick in. $form['preview']['#type'] = 'submit'; // We need this otherwise pid collides with comment. $form['project_info']['#tree'] = TRUE; $form['project_info']['#weight'] = -2; // Remove the form item that displays the current project, and // replace the static single project value with a select list // of all projects to make swapping simpler. unset($form['project_info']['project_display']); $uris = NULL; if (variable_get('project_issue_autocomplete', 0) == 1) { $form['project_info']['project_title'] = array( '#type' => 'textfield', '#title' => t('Project'), '#default_value' => $project->title, '#required' => TRUE, '#weight' => -1, '#size' => 35, '#autocomplete_path' => 'project/autocomplete/issue/project', '#attributes' => array( 'onFocus' => 'project_issue_autocomplete_handler()', ), '#ahah' => array( 'progress' => array( 'type' => 'none', ), 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', ), ); } else { $projects = project_projects_select_options($uris); $form['project_info']['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#default_value' => $project->nid, '#options' => $projects, '#required' => TRUE, '#weight' => -1, '#ahah' => array( 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', 'event' => 'change', ), ); } $form['issue_info']['#weight'] = -1; $form['#prefix'] = '<div class="project-issue"><div class="node-form"><div class="standard">'; $form['#suffix'] = '</div></div></div>'; $form['original_issue'] = array( '#type' => 'fieldset', '#title' => t('Edit issue settings'), '#description' => t('Note: changing any of these items will update the issue\'s overall values.'), '#collapsible' => TRUE, '#weight' => -10, ); $form['original_issue']['title'] = array( '#type' => 'textfield', '#title' => t('Issue title'), '#maxlength' => 128, '#default_value' => $node->title, '#weight' => -30, '#required' => TRUE, ); $form['project_info']['assigned'] = $form['issue_info']['assigned']; unset($form['issue_info']['assigned']); $form['project_info']['#prefix'] = '<div id="project-info-wrapper" class="inline-options">'; $form['project_info']['#suffix'] = '</div>'; // Remove the 'Project information' and 'Issue information' fieldsets, // since we'll move everything inside the 'Edit issue settings' fieldset. unset($form['project_info']['#type'], $form['project_info']['#title']); unset($form['issue_info']['#type'], $form['issue_info']['#title']); // Restructure the UI to de-emphasize the original project form inputs. $form['original_issue']['project_info'] = $form['project_info']; $form['original_issue']['issue_info'] = $form['issue_info']; unset($form['project_info'], $form['issue_info']); unset($form['issue_details'], $form['project_help']); drupal_add_js(drupal_get_path('module', 'project_issue') .'/project_issue.js'); } /** * Validate issue metadata on the comment form. * * @param $form * The Drupal form structure. * @param $form_state * The current state of the form. */ function project_issue_form_comment_validate($form, &$form_state) { if (empty($form['cid']['#value']) && variable_get('project_issue_autocomplete', 0) == 1) { if (empty($form_state['values']['project_info']['project_title'])) { form_set_error('project_title', t('You must enter a project to navigate to.')); } else { $pid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_info']['project_title'], 'project_project')); if (empty($pid)) { form_set_error('project_info][project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_info']['project_title']))); } else { $form_state['values']['project_info']['pid'] = $pid; } } } if (!empty($form_state['rebuild'])) { return; } $values = $form_state['values']; $project_info = $form_state['values']['project_info']; $nid = $values['nid']; $node = node_load($nid); // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Adjust new file attachments to go to the issues directory. // We have to do this during validate, otherwise we might miss // adjusting the filename before comment upload saves it (module weighting) // TODO: is this still true? project_issue_change_comment_upload_path($values); // Only validate metadata changes on new followups. if (isset($values['cid'])) { return; } // Make sure project is current here -- it may have changed when posted. if (isset($project_info['pid'])) { $node->project_issue['pid'] = $project_info['pid']; } $project = node_load($node->project_issue['pid']); if (!empty($project) && $project->type == 'project_project') { // Force all comments to be a child of the main issue, to match the // flat display, and also to prevent accidentally deleting a thread. $form_state['values']['pid'] = 0; // Validate version. if (module_exists('project_release') && isset($project_info['rid']) && ($releases = project_release_get_releases($project, 0, 'version', 'all', array($project_info['rid'])))) { $rid = $project_info['rid']; if ($rid && !in_array($rid, array_keys($releases))) { $rid = 0; } // Check to make sure this release is not marked as an invalid // release node for user selection. $invalid_rids = variable_get('project_issue_invalid_releases', array()); if (!empty($invalid_rids) && ((empty($rid) && in_array($node->project_issue['rid'], $invalid_rids)) || in_array($rid, $invalid_rids))) { form_set_error('project_info][rid', t('%version is not a valid version, please select a different value.', array('%version' => $releases[$node->project_issue['rid']]))); } elseif (empty($rid)) { form_set_error('project_info][rid', t('You have to specify a valid version.')); } } // Add a dummy rid if necessary -- prevents incorrect change data. else { $rid = 0; } // Validate component. $component = $project_info['component']; if ($component && !in_array($component, $project->project_issue['components'])) { $component = 0; } empty($component) && form_set_error('project_info][component', t('You have to specify a valid component.')); } else { form_set_error('project_info][pid', t('You have to specify a valid project.')); } empty($values['category']) && form_set_error('category', t('You have to specify a valid category.')); // Now, make sure the comment changes *something* about the issue. // If the user uploaded a file, so long as it's not marked for removal, // we consider that a valid change to the issue, too. $has_file = FALSE; $files = isset($values['files']) ? $values['files'] : array(); foreach ($files as $number => $data) { if (empty($data['remove'])) { $has_file = TRUE; break; } } if (!$has_file && empty($values['comment'])) { $comment = drupal_clone((object) $values); $comment->pid = $project_info['pid']; $comment->component = $component; $comment->rid = $rid; $comment->assigned = $project_info['assigned']; $comment_changes = project_issue_metadata_changes($node, $old_data, $comment, project_issue_field_labels('web')); // If the PID changed, rebuild the form if (isset($comment_changes['pid']['new']) && $comment_changes['pid']['new'] === TRUE) { $form_state['rebuild'] = TRUE; } $has_change = FALSE; foreach ($comment_changes as $field => $changes) { if (isset($changes['new'])) { $has_change = TRUE; break; } } if (!$has_change) { form_set_error('comment', t('You must either add a comment, upload a file, or change something about this issue.')); } } } /** * Theme a project issue metadata table. * * @param $comment_changes * Array containing metadata differences between comments * as returned by project_issue_metadata_changes(). * @return * The themed metadata table. */ function theme_project_issue_comment_table($comment_changes) { $rows = array(); foreach ($comment_changes as $field => $change) { if (!empty($change['label']) && isset($change['old']) && isset($change['new'])) { $rows[] = theme('project_issue_comment_table_row', $field, $change); } } - return theme('table', array(), $rows); + return $rows ? theme('table', array(), $rows) : ''; } /** * Theme a single row of the project issue metadata changes table. * * @param $field * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * An array representing one row of the table. * * NOTE: If you override this theme function, you *must* make sure * that you sanitize all output from this function that is displayed * to the user. No further escaping/filtering of the data in this * table will take place after this function. In most cases * this means that you need to run the $change['label'], $change['old'], * and $change['new'] values through either the check_plain() or * filter_xss() function to prevent XSS and other types * of problems due to any malicious input in these * field values. */ function theme_project_issue_comment_table_row($field, $change) { // Allow anchor, emphasis, and strong tags in metadata tables. $allowed_tags = array('a', 'em', 'strong'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])){ foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { $added[] = '+'. $item; } } elseif (!empty($change['new'])) { $added[] = '+'. $change['new']; } return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(implode(', ', $removed), $allowed_tags), filter_xss(implode(', ', $added), $allowed_tags), ); } elseif (in_array($field, $plain_fields)) { return array( filter_xss($change['label'], $allowed_tags) .':', check_plain(project_issue_change_summary($field, $change['old'])), '&raquo; '. check_plain(project_issue_change_summary($field, $change['new'])), ); } else { return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(project_issue_change_summary($field, $change['old']), $allowed_tags), '&raquo; '. filter_xss(project_issue_change_summary($field, $change['new']), $allowed_tags), ); } } /** * Returns the issue metadata table for a comment. * * @param $node * The corresponding node. * @param $comment * The comment, if it's set then metadata will be returned. If it's not * set then metadata will be precalculated. * @return * A themed table of issue metadata. */ function project_issue_comment_view(&$node, $comment = NULL) { static $project_issue_tables; if (isset($comment)) { return isset($project_issue_tables[$comment->cid]) ? $project_issue_tables[$comment->cid] : ''; } if (!empty($node->comment_count)) { $old = unserialize(db_result(db_query('SELECT original_issue_data FROM {project_issues} WHERE nid = %d', $node->nid))); $labels = project_issue_field_labels('web'); $result = db_query('SELECT p.cid, p.title, p.pid, p.rid, p.component, p.category, p.priority, p.assigned, p.sid FROM {project_issue_comments} p INNER JOIN {comments} c ON p.cid = c.cid WHERE p.nid = %d AND c.status = %d ORDER BY p.timestamp ASC', $node->nid, COMMENT_PUBLISHED); while ($followup = db_fetch_object($result)) { $followup_changes = project_issue_metadata_changes($node, $old, $followup, project_issue_field_labels('web')); $project_issue_tables[$followup->cid] = theme('project_issue_comment_table', $followup_changes); $old = $followup; } } } /** * Updates the project issue based on the comment inserted/updated/deleted. * * @param $comment_data * The comment data that's been submitted. * @param $op * The comment operation performed, 'insert', 'update', 'delete'. * @return * An object representing the comment data used to update the issue. */ function project_issue_update_by_comment($comment_data, $op) { switch ($op) { case 'insert': // Massage the incoming data so the structure is consistent throughout the function. $comment_data['component'] = $comment_data['project_info']['component']; $comment_data['pid'] = $comment_data['project_info']['pid']; $comment_data['rid'] = isset($comment_data['project_info']['rid']) ? $comment_data['project_info']['rid'] : 0; unset ($comment_data['project_info']); $comment_data = (object) $comment_data; // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. if (!isset($comment_data->followup_no_mail)) { // Temporary hack to get around sending of auto-close emails. project_issue_set_mail_notify($comment_data->nid); } break; case 'update': $comment_data = (object) $comment_data; break; } // In order to deal with deleted/unpublished comments, make sure that we're performing // the updates to the issue with the latest available published comment. $comment_data = project_issue_get_newest_comment($comment_data); // Update the issue data to reflect the new final states. db_query("UPDATE {project_issues} SET pid = %d, category = '%s', component = '%s', priority = %d, rid = %d, assigned = %d, sid = %d WHERE nid = %d", $comment_data->pid, $comment_data->category, $comment_data->component, $comment_data->priority, $comment_data->rid, $comment_data->assigned, $comment_data->sid, $comment_data->nid); // Update the issue title. $node = node_load($comment_data->nid, NULL, TRUE); // Don't use cached since we changed data above. $node->title = $comment_data->title; // This also updates the changed date of the issue. node_save($node); // Return the object of comment data we used to update the issue. return $comment_data; } /** * Adjusts the filepath of issue followups so files are saved to * the correct issues directory. * * @param $comment * An array of the submitted comment values. */ function project_issue_change_comment_upload_path(&$comment) { static $run = NULL; // Only for new comments with attachments. if (empty($comment['cid']) && isset($comment['files']) && !isset($run)) { $run = TRUE; // Make sure this only gets run once. project_issue_rewrite_issue_filepath($comment['files']); } } /** * Retrieves the newest published comment for an issue. * * @param $comment_data * An object representing the current comment being edited * @return * An object representing the most recent published comment for the issue. */ function project_issue_get_newest_comment($comment_data) { // Get the cid of the most recent comment. $latest_cid = db_result(db_query_range('SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp DESC', $comment_data->nid, COMMENT_PUBLISHED, 0, 1)); if ($latest_cid) { $comment_data = db_fetch_object(db_query('SELECT * FROM {project_issue_comments} WHERE cid = %d', $latest_cid)); } // No more comments on the issue -- use the original issue metadata. else { // nid isn't stored in the original issue data, so capture it here and pass back // into the object. $nid = $comment_data->nid; $comment_data = unserialize(db_result(db_query("SELECT original_issue_data FROM {project_issues} WHERE nid = %d", $comment_data->nid))); $comment_data->nid = $nid; } return $comment_data; } /** * Test to determine if the active page is the comment reply form. * * @return * TRUE if the active page is the comment reply form, FALSE otherwise. */ function project_issue_is_comment_reply() { return arg(0) == 'comment' && arg(1) == 'reply'; } /** * Test to determine if the active page is the comment edit form. * * @return * TRUE if the active page is the comment edit form, FALSE otherwise. */ function project_issue_is_comment_edit() { return arg(0) == 'comment' && arg(1) == 'edit'; } /** * Appends the comment thread to the comment reply form. */ function project_issue_comment_pre_render($form) { // Force the correct formatting. $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; $suffix = empty($form['#suffix']) ? '' : $form['#suffix']; $node = node_load($form['nid']['#value']); // Unfortunately, the comment module blindly puts the node view // after the comment form on preview, in the case where the comment // parent is 0. If we want our issue previews to be consistent, this // ugly hack is necessary. if (isset($form['#parameters'][1]['values']['op']) && $form['#parameters'][1]['values']['op'] == t('Preview')) { $preview = comment_render($node, 0); } else { $preview = node_show($node, 0); } $form['#suffix'] = $suffix . $preview; return $form; }
Br3nda/drupal-module-project_issue
2ef33d2ba07ad1f0786dffd9998c20636dc4a415
#495476 by jennifer.chang, dww: Fixed PHP notices caused by broken views handlers for the version and component filters.
diff --git a/views/handlers/project_issue_handler_filter_issue_component.inc b/views/handlers/project_issue_handler_filter_issue_component.inc index 919cd14..50ac7c1 100644 --- a/views/handlers/project_issue_handler_filter_issue_component.inc +++ b/views/handlers/project_issue_handler_filter_issue_component.inc @@ -1,61 +1,61 @@ <?php -// $Id: project_issue_handler_filter_issue_component.inc,v 1.1 2009/01/27 23:40:35 dww Exp $ +// $Id: project_issue_handler_filter_issue_component.inc,v 1.2 2010/01/17 00:22:44 dww Exp $ /** * Filter issues based on their component. * * This filter only returns values to select if it's exposed and the view has * a project argument (either nid or uri), and that argument is first. */ class project_issue_handler_filter_issue_component extends views_handler_filter_in_operator { var $is_exposed = FALSE; function value_form(&$form, &$form_state) { if (!empty($form_state['exposed'])) { // Set a flag so get_value_options() knows to return real values. $this->is_exposed = TRUE; // Due to some unknown bug in views, it appears as though this filter // always acts as if it's a "force single" filter, even if it's not. // Therefore, it's (sometimes?) setting its own value to to 'All', when // GET is empty, which gives an invalid choice when you load the form. - unset($this->value); + $this->value = NULL; } parent::value_form($form, $form_state); if (empty($form_state['exposed'])) { $form['warning'] = array( '#type' => 'markup', '#value' => t('You can only select options if you expose this filter and have a project argument'), ); } } function get_value_options() { static $components = array(); // We only want to return real options if we're building an exposed filter // form and we have a project argument (either nid or uri). So, we check // the flag set in value_form() to see if this is an exposed filter. if ($this->is_exposed) { if (empty($components)) { $arg = reset($this->view->args); if (is_numeric($arg)) { $project = db_fetch_object(db_query("SELECT pip.components FROM {project_issue_projects} pip WHERE pip.nid = %d", $arg)); } else { $project = db_fetch_object(db_query("SELECT pip.components FROM {project_issue_projects} pip INNER JOIN {project_projects} pp ON pip.nid = pp.nid WHERE pp.uri = '%s'", $arg)); } if (!empty($project->components)) { foreach (unserialize($project->components) as $component) { $components[$component] = check_plain($component); } } } $this->value_options = $components; } else { $this->value_options = array(); } } } diff --git a/views/handlers/project_issue_handler_filter_issue_version.inc b/views/handlers/project_issue_handler_filter_issue_version.inc index 7166a06..3383953 100644 --- a/views/handlers/project_issue_handler_filter_issue_version.inc +++ b/views/handlers/project_issue_handler_filter_issue_version.inc @@ -1,121 +1,121 @@ <?php -// $Id: project_issue_handler_filter_issue_version.inc,v 1.10 2009/04/22 17:24:18 dww Exp $ +// $Id: project_issue_handler_filter_issue_version.inc,v 1.11 2010/01/17 00:22:44 dww Exp $ /** * Filter issues based on their version. * * This filter only returns values to select if it's exposed and the view has * a project argument (either nid or uri), and that argument is first. * * This is almost a copy of project_issue_handler_filter_issue_component. */ class project_issue_handler_filter_issue_version extends views_handler_filter_in_operator { var $is_exposed = FALSE; var $project_versions = array(); var $project_version_series = array(); function value_form(&$form, &$form_state) { if (!empty($form_state['exposed'])) { // Set a flag so get_value_options() knows to return real values. $this->is_exposed = TRUE; // Due to some unknown bug in views, it appears as though this filter // always acts as if it's a "force single" filter, even if it's not. // Therefore, it's (sometimes?) setting its own value to to 'All', when // GET is empty, which gives an invalid choice when you load the form. - unset($this->value); + $this->value = NULL; } $this->get_value_options(); if (!empty($this->value_options)) { parent::value_form($form, $form_state); } elseif (!empty($form_state['exposed'])) { // This project has no versions at all, hide this filter. $this->view->filter['rid']->options['exposed'] = FALSE; // And exclude the field itself. Instead of assuming the field key is // 'version', search for a field using {project_release_nodes}.version // from the same relationship as this filter. foreach ($this->view->field as $field) { if ($field->table == 'project_release_nodes' && $field->field == 'version') { $field->options['exclude'] = TRUE; } } } if (empty($form_state['exposed'])) { $form['warning'] = array( '#type' => 'markup', '#value' => t('You can only select options if you expose this filter and have a project argument'), ); } } function init_version_info() { if (empty($this->project_versions) && isset($this->view->argument['pid']) && module_exists('project_release')) { $arg = $this->view->argument['pid']->get_value(); if (is_numeric($arg)) { $project_nid = $arg; } else { $project_nid = project_get_nid_from_uri($arg); } // This is needed by project_get_releases() and friends. $project = node_load($project_nid); $this->project_versions = project_release_get_releases($project, FALSE); if (!empty($this->project_versions)) { $active_tids = array_keys(project_release_compatibility_list()); if (!empty($active_tids)) { $tid_placeholders = db_placeholders($active_tids); $nids = array_keys($this->project_versions); $nid_placeholders = db_placeholders($nids); $query_args = array_merge($active_tids, $nids); $query = db_query("SELECT td.name, td.tid, tn.nid FROM {term_data} td INNER JOIN {term_node} tn ON td.tid = tn.tid WHERE tn.tid IN ($tid_placeholders) AND tn.nid IN ($nid_placeholders) ORDER BY td.weight", $query_args); while ($release = db_fetch_object($query)) { $this->project_version_series[$release->name][] = $release->nid; } } } } } function get_value_options() { $this->value_options = array(); // We only want to return real options if we're building an exposed filter // form, so we check the flag set in value_form(). if ($this->is_exposed) { $this->init_version_info(); if (!empty($this->project_version_series)) { foreach ($this->project_version_series as $series => $nids) { $this->value_options[$series] = t('- @series issues -', array('@series' => $series)); } } if (!empty($this->project_versions)) { $this->value_options += $this->project_versions; } } } /** * Generate the query based on this filter. * * This is where the special logic for the "- $series issues -" choices is * converted back into the real release nid values for the underlying query. */ function query() { if (isset($this->value)) { $this->init_version_info(); $values = array(); foreach ($this->value as $key => $value) { if (!empty($this->project_version_series[$value])) { $values += $this->project_version_series[$value]; } else { $values[$key] = $value; } } $this->value = $values; parent::query(); } } }
Br3nda/drupal-module-project_issue
8c9ecf5321cfbe0afdcf381bf6cf9d792dcf16ed
#687018 by dww: Fixed PHP notice when adding an issue comment on a site that doesn't allow anonymous users to access issues.
diff --git a/includes/mail.inc b/includes/mail.inc index 2ec6a19..73b71b1 100644 --- a/includes/mail.inc +++ b/includes/mail.inc @@ -1,660 +1,660 @@ <?php -// $Id: mail.inc,v 1.122 2009/06/18 03:05:25 dww Exp $ +// $Id: mail.inc,v 1.123 2010/01/17 00:16:15 dww Exp $ function project_issue_mailhandler($node, $result, $i, $header, $mailbox) { if ($node->type == 'project') { if (node_access('create', 'project_issue')) { $node->nid = preg_replace('/@.+/', '', $node->nid); if ($node->nid) { /* ** Base the new entry on the node it belongs to, this ensures all ** values are initially correct. */ $entry = node_load(array('nid' => $node->nid, 'type' => 'project_issue')); } // Possible attributes $fields = array( 'pid' => t('Project'), 'category' => t('Category'), 'component' => t('Component'), 'priority' => t('Priority'), 'rid' => t('Version'), 'assigned' => t('Assigned to'), 'sid' => t('Status') ); /* ** Only change the title if it doesn't have the old title in it. ** This should prevent the title from changing due to added ** prefixes. It may on occasion make false positives, but if ** a title change is that minor who cares? */ $entry->title = (strpos($node->title, $entry->title)) ? $entry->title : $node->title; $entry->teaser = $node->teaser; $entry->body = $node->body; $entry->uid = $node->uid; foreach ($fields as $var => $text) { $text = strtolower(str_replace(' ', '_', $text)); if (isset($node->project_issue[$text])) { $node->project_issue[$text] = trim($node->project_issue[$text]); switch ($var) { case 'pid': $project = node_load($node->project_issue[$text]); if ($project->nid) { $entry->project_issue['pid'] = $project->nid; } break; case 'category': if (($category = array_search($node->project_issue[$text], project_issue_category(0, 0)))) { $entry->project_issue['category'] = $category; } break; case 'priority': if (($priority = array_search($node->project_issue[$text], project_issue_priority()))) { $entry->project_issue['priority'] = $priority; } break; case 'rid': if ($entry->project_issue['pid'] && ($nid = db_result(db_query("SELECT nid FROM {project_release_nodes} WHERE pid = %d AND version = '%s'", $entry->project_issue['pid'], $node->project_issue[$text]), 0))) { $entry->project_issue['rid'] = $nid; } break; case 'assigned': if ($user = user_load(array('name' => $node->project_issue[$text]))) { $entry->project_issue['assigned'] = $user->uid; } break; case 'sid': if (($state = array_search($node->project_issue[$text], project_issue_state()))) { $entry->project_issue['sid'] = $state; } break; case 'component': if ($entry->project_issue['pid'] && ($project = node_load(array('nid' => $entry->project_issue['pid'], 'type' => 'project_project')))) { if ($project && in_array($node->project_issue[$text], $project->project_issue['components'])) { $entry->project_issue['component'] = $node->project_issue[$text]; } } break; } } } if (empty($entry->nid)) { $entry->sid = variable_get('project_issue_default_state', 1); $entry->type = 'project_issue'; $entry = node_validate($entry, $error); $error or ($entry->nid = node_save($entry)); } else { $error = project_comment_validate($entry); $error or project_comment_save($entry); } } else { $error['user'] = t('You are not authorized to access this page.'); } if ($error && $mailbox['replies']) { // Send the user his errors $mailto = mailhandler_get_fromaddress($header, $mailbox); $mailfrom = variable_get('site_mail', ini_get('sendmail_from')); $headers = array( 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', ); $body = t('You had some errors in your submission:'); foreach ($error as $field => $text) { $body .= "\n * $field: $text"; } drupal_mail('project_issue_mailhandler_error', $mailto, t('E-mail submission to !sn failed - !subj', array('!sn' => variable_get('site_name', 'Drupal'), '!subj' => $header->subject)), $body, $mailfrom, $headers); } // Return a NULL result so mailhandler doesn't save the node using the default methods. return NULL; } else { return $node; } } function project_mail_urls($url = 0) { static $urls = array(); if ($url) { // If $url is an internal link (eg. '/project/project'), such // as might be returned from the url() function with the // $absolute parameter set to FALSE, we must remove // the leading slash before passing this path through the url() // function again, or otherwise we'll get two slashes in a row // and thus a bad URL. if (substr($url, 0, 1) == '/') { $url = substr($url, 1); } $urls[] = strpos($url, '://') ? $url : url($url, array('absolute' => TRUE)); return count($urls); } return $urls; } function project_mail_output(&$body, $html = 1, $format = FILTER_FORMAT_DEFAULT) { static $i = 0; if ($html) { $body = check_markup($body, $format, FALSE); $pattern = '@<a +([^ >]+ )*?href *= *"([^>"]+?)"[^>]*>([^<]+?)</a>@ei'; $body = preg_replace($pattern, "'\\3 ['. project_mail_urls('\\2') .']'", $body); $urls = project_mail_urls(); if (count($urls)) { $body .= "\n"; for ($max = count($urls); $i < $max; $i++) { $body .= '['. ($i + 1) .'] '. $urls[$i] ."\n"; } } $body = preg_replace('!</?blockquote>!i', '"', $body); $body = preg_replace('!</?(em|i)>!i', '/', $body); $body = preg_replace('!</?(b|strong)>!i', '*', $body); $body = preg_replace("@<br />(?!\n)@i", "\n", $body); $body = preg_replace("@</p>(?!\n\n)@i", "\n\n", $body); $body = preg_replace("@<li>@i", "* ", $body); $body = preg_replace("@</li>\n?@i", "\n", $body); $body = strip_tags($body); $body = decode_entities($body); $body = wordwrap($body, 72); } else { $body = decode_entities($body); } } function project_mail_notify($nid) { global $user; if (defined('PROJECT_NOMAIL')) { return; } $node = node_load($nid, NULL, TRUE); $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); // Store a copy of the issue, so we can load the original issue values // below. $issue = drupal_clone($node); // Load in the original issue data here, since we want a running // reverse history. $original_issue_data = unserialize($node->project_issue['original_issue_data']); $fields = project_issue_field_labels('email'); foreach ($fields as $field => $label) { if ($field != 'name' && $field != 'updator') { $issue->original_issue_metadata->$field = $original_issue_data->$field; } } // Record users that are connected to this issue. $uids = array(); if (!empty($node->uid)) { $uids[$node->uid] = $node->uid; } if (!empty($node->project_issue['assigned'])) { $uids[$node->project_issue['assigned']] = $node->project_issue['assigned']; } // Create complete history of the bug report. $history = array($issue); $result = db_query('SELECT u.name, c.cid, c.nid, c.subject, c.comment, c.uid, c.format, pic.* FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid INNER JOIN {users} u ON u.uid = c.uid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp', $node->nid, COMMENT_PUBLISHED); while ($comment = db_fetch_object($result)) { $comment->comment = db_decode_blob($comment->comment); $comment->files = comment_upload_load_files($comment->cid); $history[] = $comment; // Record users that are connected to this issue. if ($comment->uid) { $uids[$comment->uid] = $comment->uid; } } if (count($uids)) { $placeholders = implode(',', array_fill(0, count($uids), '%d')); array_unshift($uids, $node->project_issue['pid']); $result = db_query("SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND (p.level = 2 OR (p.level = 1 AND u.uid IN ($placeholders)))", $uids); } else { $result = db_query('SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND p.level = 2', $node->project_issue['pid']); } // To save workload, check here if either the anonymous role or the // authenticated role has the 'view uploaded files' permission, since // we only need to process each user's file access permission if this // is NOT the case. $check_file_perms = !db_result(db_query("SELECT COUNT(*) FROM {permission} WHERE perm LIKE '%view uploaded files%' AND rid IN (%d, %d)", DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID)); // We need to determine if node_access() checks are necessary. The // check will be needed if any of the following is true: // 1. The node is not published. // 2. There is at least on node access control module enabled. // 3. Both the anonymous and authenticated user do not have // the 'access project issues' permission. $allowed_roles = user_roles(FALSE, 'access project issues'); if (isset($allowed_roles[DRUPAL_ANONYMOUS_RID]) || isset($allowed_roles[DRUPAL_AUTHENTICATED_RID])) { $anon_auth_access = TRUE; } $grants = module_implements('node_grants'); - $check_node_access = $node->status != 1 || !$anon_auth_access || !empty($grants); + $check_node_access = $node->status != 1 || empty($anon_auth_access) || !empty($grants); $params['node'] = $node; $params['project'] = $project; $params['history'] = $history; $sender->name = t('!name (!site)', array('!name' => $user->name, '!site' => variable_get('site_name', 'Drupal'))); $sender->mail = strtr(variable_get('project_issue_reply_to', variable_get('site_mail', ini_get('sendmail_from'))), array('%project' => $project->project['uri'])); // The sender name is enclosed by double quotes below // to satisfy RFC2822 <http://www.faqs.org/rfcs/rfc2822.html>, // which requires double quotes when special characters (including // some punctuation) are used. See example in Appendix A.1.2. $from = '"' . mime_header_encode($sender->name) . "\" <$sender->mail>"; while ($recipient = db_fetch_object($result)) { // To save work, only go through a user_load if we need it. if ($check_file_perms || $check_node_access) { $account = user_load(array('uid' => $recipient->uid)); $language = user_preferred_language($account); } else { $language = language_default(); } $can_access = $check_node_access ? node_access('view', $node, $account) : TRUE; if ($can_access) { $display_files = $check_file_perms ? user_access('view uploaded files', $account) : TRUE; $params['display_files'] = $display_files; drupal_mail('project_issue', 'project_issue_update_notification', $recipient->mail, $language, $params, $from); } } if (is_array($project->project_issue['mail_copy_filter']) && count(array_filter($project->project_issue['mail_copy_filter'])) && !$project->project_issue['mail_copy_filter'][$node->project_issue['category']]) { return; } if (is_array($project->project_issue['mail_copy_filter_state']) && count(array_filter($project->project_issue['mail_copy_filter_state'])) && !$project->project_issue['mail_copy_filter_state'][$node->project_issue['sid']]) { return; } if (!empty($project->project_issue['mail_copy'])) { $params['display_files'] = TRUE; $message['body'][] = $links; $message['body'][] = project_mail_generate_followup_mail_body($node, $history, TRUE); drupal_mail('project_issue', 'project_issue_update_notification', $project->project_issue['mail_copy'], language_default(), $params, $from); } } /* * Implementation of hook_mail() */ function project_issue_mail($key, &$message, $params) { global $base_url; switch ($key) { case "project_issue_update_notification": // There could be stale data in the cached node, so reset the cache. $node = $params['node']; $project = $params['project']; $history = $params['history']; $fields = project_issue_field_labels('email'); $domain = preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url); $message['headers'] += array( 'Date' => date('r'), 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', 'List-Id' => "$project->title <". $project->project['uri'] ."-issues-$domain>", 'List-Archive' => '<'. url('project/issues/'. $project->project['uri'], array('absolute' => TRUE)) .'>', 'List-Subscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>', 'List-Unsubscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>' ); // Comments exist, set headers accordingly. if (count($history) > 1) { foreach ($history as $comment) { // We need the most recent cid and the next most recent cid for the // message headers. Instead of issuing another query, just keep track // of them here. $previous_cid = isset($cid) ? $cid : ''; $cid = isset($comment->cid) ? $comment->cid : 0; } $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&cid=$cid&host=@$domain>"; $message['headers']['In-Reply-To'] = "<type=project&nid=$node->nid&host=@$domain>"; $message['headers']['References'] = "<type=project&nid=$node->nid&host=@$domain> <type=project&nid=$node->nid&cid=$previous_cid&host=@$domain> <type=project&nid=$node->nid&revcount=1&host=@$domain>"; } else { // Only original issue in this email. $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&host=@$domain>"; } project_mail_output($node->title, 0); $message['subject'] = t('[!short_name] [!category] !title', array('!short_name' => $project->project['uri'], '!category' => $node->project_issue['category'], '!title' => $node->title)); // Create link to related node $links = t('Issue status update for !link', array('!link' => "\n". url("node/$node->nid", array('absolute' => TRUE)))) ."\n"; $links .= t('Post a follow up: !link', array('!link' => "\n". url("comment/reply/$node->nid", array('fragment' => 'comment-form', 'absolute' => TRUE)))) ."\n"; $message['body'][] = $links; $message['body'][] = project_mail_generate_followup_mail_body($node, $history, $params['display_files']); break; case 'project_issue_critical_summary': $project = $params['project']; $message['headers'] += array( 'Date' => date('r'), 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', 'List-Id' => "$project->title <". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'-project-issues-digest>', 'List-Archive' => '<'. url('project/issues', array('query' => array('priorities' => '1'), 'absolute' => TRUE)) .'>', ); $message['subject'] = t('Release critical bugs for !date', array('!date' => date('F d, Y', time()))); $message['body'][] = $params['body']; break; case 'project_issue_reminder': $sender->name = variable_get('site_name', ''); $sender->mail = variable_get('site_mail', ''); $message['headers'] += array( 'Return-Path' => "<$sender->mail;>", 'Date' => date('r'), 'From' => "$sender->name <$sender->mail>", 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', 'List-Id' => "$sender->name <project-reminder-". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'>', 'List-Archive' => '<'. url('project', array('absolute' => TRUE)) .'>', ); $message['subject'] = t('Your submitted bugs for !date', array('!date' => date('F d, Y', time()))); $message['body'][] = $params['body']; break; } } /** * Format the body of an issue followup email. * * @param $node * The issue node. * @param $history * An array containing the history of issue followups. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A string of the email body. */ function project_mail_generate_followup_mail_body($node, $history, $display_files) { global $user; static $output_with_files = NULL, $output_without_files = NULL; // Return cached output if available. if ($display_files) { if (isset($output_with_files)) { return $output_with_files; } } else { if (isset($output_without_files)) { return $output_without_files; } } // Get most recent update. $entry = array_pop($history); $node->project_issue['updator'] = $entry->name ? $entry->name : $user->name; // Check if the latest entry is actually the initial issue. if (empty($history)) { $metadata_previous = new stdClass(); // Have to get the metadata into the entry object. $metadata_entry = $entry->original_issue_metadata; $content = $entry->body; } else { $metadata_previous = end($history); // If the previous was the original issue, then we need to pull // out the metadata from project_issue. if (isset($metadata_previous->original_issue_metadata)) { $metadata_previous = $metadata_previous->original_issue_metadata; } $metadata_entry = $entry; $content = $entry->comment; } $fields = project_issue_field_labels('email'); $comment_changes = project_issue_metadata_changes($node, $metadata_previous, $metadata_entry, $fields); // Since $node->name will always be the original issue author, and since // $node->project_issue['updator'] isn't a property of either $previous or // $entry, these two properties will never show up as being different when // project_issue_metadata_changes() is called, and therefore neither of // these will ever be elements of the $comment_changes array. Since we do // want them to be printed in issue emails, we just need to add their labels // back into the $comment_changes array here, so that // theme_project_issue_mail_summary_field() will know to print the data for // these two fields. $comment_changes['name'] = array( 'label' => $fields['name'], ); $comment_changes['updator'] = array( 'label' => $fields['updator'], ); $summary = theme('project_issue_mail_summary', $entry, $node, $comment_changes, $display_files); // Create main body content project_mail_output($content, 1, $entry->format); $body = "$content\n$entry->name\n"; $hr = str_repeat('-', 72); if (count($history)) { $body .= "\n\n"; $body .= t('Original issue:') ."\n"; $body .= project_mail_format_entry(array_shift($history), $display_files, TRUE); if (count($history)) { $body .= "\n". t('Previous comments (!count):', array('!count' => count($history))) ."\n"; foreach ($history as $entry) { $body .= project_mail_format_entry($entry, $display_files); } } } $output = "$summary\n$body"; // Set cached output. if ($display_files) { $output_with_files = $output; } else { $output_without_files = $output; } return $output; } /** * Themes the display of the issue metadata summary * that is shown at the top of an issue emai. * * @param $entry * The object representing the current entry. This will be a node object * if the current entry is the original issue node; otherwise this will be * a comment object. * @param $node * The original issue node object. * @param $changes * A nested array containing the metadata changes between the original * issue and the first comment, or two consecutive comments. This array * is the output of the project_issue_metadata_changes() function. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A string containing the themed text of the issue metadata table. */ function theme_project_issue_mail_summary($entry, $node, $changes, $display_files) { // Mail summary (status values). $summary = ''; foreach ($changes as $field => $change) { $summary .= theme('project_issue_mail_summary_field', $node, $field, $change); } $summary .= project_mail_format_attachments($entry, $display_files); return $summary; } /** * Theme the email output of one project issue metadata field. * * @param $node * The project issue node object. * @param $field_name * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * A themed line or lines of text ready for inclusion into the email body. */ function theme_project_issue_mail_summary_field($node, $field_name, $change) { // We need to run the label name through strip_tags here so that // the spacing isn't messed up if there are HTML tags in $change['label']. $text = str_pad(strip_tags($change['label']). ':', 14); $summary_row = ''; if (!empty($change['label']) && isset($change['old']) && isset($change['new']) && $field_name != 'updator' && $field_name != 'name') { if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])) { foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { $added[] = '+'. $item; } } elseif (!empty($change['new'])) { $added[] = '+'. $change['new']; } $summary_row = " $text". trim(implode(', ', $removed). ' ' .implode(', ', $added)) ."\n"; } else { $summary_row .= "-$text". project_issue_change_summary($field_name, $change['old']) ."\n"; $summary_row .= "+$text". project_issue_change_summary($field_name, $change['new']) ."\n"; } } elseif (!empty($change['label'])) { if (!empty($change['new'])) { // This condition is necessary when building the first email message of an // issue, since in this case $change['old'] should not exist. if (is_array($change['new'])) { $summary_row .= " $text". implode(', ', $change['new']) ."\n"; } else { $summary_row .= " $text". project_issue_change_summary($field_name, $change['new']) ."\n"; } } else { // This condition is where fields that are stored in the $node object and // which haven't changed but should be printed anyway get processed. // For example, the project, category, etc. are printed in each email // whether or not they have changed. // @TODO: Should we really assume the field in is $node->project_issue[]? if (isset($node->project_issue[$field_name])) { $summary_row .= " $text". project_issue_change_summary($field_name, $node->project_issue[$field_name]) ."\n"; } } } // HTML tags in the email will make it hard to read, so pass // this output through strip_tags(). return strip_tags($summary_row); } /** * Formats attachments for issue notification e-mails. * * @param $entry * An issue or followup object containing the file data. * @param $display_files * Boolean indicating if file attachments should be displayed. * @return * A formatted string of file attachments. */ function project_mail_format_attachments($entry, $display_files) { $output = ''; if ($display_files && is_array($entry->files)) { foreach ($entry->files as $file) { // Comment upload has it's files in an array, so cast to an object // for consistency. $file = (object) $file; $output .= ' '. str_pad(t('Attachment') .':', 14) . file_create_url($file->filepath) .' ('. format_size($file->filesize) .")\n"; } } return $output; } /** * Format an issue entry for display in an email. * * @param entry * The entry to the formatted. * @param $display_files * Boolean indicating if file attachments should be displayed. * @param is_original * Whether this entry is the original issue or a followup. Followup issues * will be automatically numbered. * @return * Formatted text for the entry. */ function project_mail_format_entry($entry, $display_files, $is_original = FALSE) { static $history_count = 1; $hr = str_repeat('-', 72); $output = "$hr\n"; // Nodes and comments have different stamp fields. $timestamp = isset($entry->created) ? $entry->created : $entry->timestamp; if (!$is_original) { $output .= "$entry->subject -- "; } $output .= format_date($timestamp, 'large') ." : $entry->name\n"; if (!$is_original) { $output .= url("node/$entry->nid", array('fragment' => "comment-$entry->cid", 'absolute' => TRUE)) ."\n"; } $output .= project_mail_format_attachments($entry, $display_files); // Must distinguish between nodes and comments -- here we do it // by looking for a revision ID. if (empty($entry->vid)) { $content = $entry->comment; } else { $content = $entry->body; } project_mail_output($content, 1, $entry->format); if ($content) { $output .= "\n$content"; } return $output; }
Br3nda/drupal-module-project_issue
8d146cbeed533f88662a6a14d19769af5f3f5819
#673108 by boombatower: Added a way to set the username for programatically created issue comments (helps with #672850).
diff --git a/project_issue.module b/project_issue.module index 0371904..360a94e 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,1096 +1,1096 @@ <?php -// $Id: project_issue.module,v 1.174 2009/08/06 23:35:34 dww Exp $ +// $Id: project_issue.module,v 1.175 2010/01/17 00:10:23 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); foreach (array('comment', 'mail') as $file) { module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { - $changes['uid'] = $auto_user->uid; + $changes['uid'] = !empty($changes['uid']) ? $changes['uid'] : $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': module_load_include('inc', 'project_issue', 'includes/project_node'); project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implement hook_delete() for project issue nodes. */ function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } /** * Implement hook_form() for project issue nodes. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_form($node, $form_state, $include_metadata_fields); } /** * Implement hook_validate() for project issue nodes. */ function project_issue_validate($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_validate($node); } /** * Implement hook_insert() for project issue nodes. */ function project_issue_insert($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_insert($node); } /** * Implement hook_view() for project issue nodes. */ function project_issue_view($node, $teaser = FALSE, $page = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_view'); return _project_issue_view($node, $teaser, $page); } /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { foreach ($nids as $nid) { project_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned']));
Br3nda/drupal-module-project_issue
818bac6f29a6107285591ca9c358252e8810c3f7
#575206 by dww, Kars-T: Fixed a bug causing a redirect loop when submiting a new issue on a site that has only one term in the "Project types" taxonomy vocabulary (introduced by #526438).
diff --git a/includes/issue_node_form.inc b/includes/issue_node_form.inc index 18b4561..affeb56 100644 --- a/includes/issue_node_form.inc +++ b/includes/issue_node_form.inc @@ -1,477 +1,484 @@ <?php -// $Id: issue_node_form.inc,v 1.4 2009/08/11 17:13:57 dww Exp $ +// $Id: issue_node_form.inc,v 1.5 2009/10/08 23:36:16 dww Exp $ /** * @file * Code required for the issue node form. */ /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); - // Fetch a list of all projects. - $uris = NULL; - $projects = project_projects_select_options($uris); - if (!$projects) { + // Fetch a list of all projects (nid => title, grouped by project type + // categories if any), and also get an array of project shortnames. + $short_names = array(); + $projects = project_projects_select_options($short_names); + if (empty($projects)) { drupal_set_message(t('You do not have access to any projects.'), 'error'); + // No reason to return a project selector form with no elements, so just + // return an empty array for the form. + return array(); } - elseif (count($projects) == 1) { - $project = node_load(key($projects)); - drupal_goto('node/add/project-issue/' . $project->project['uri']); + + // See if there's only one project the user has access to, and if so, + // redirect directly to the issue form for that project. + if (count($short_names) == 1) { + drupal_goto('node/add/project-issue/' . key($short_names)); } + // Otherwise, return a form to select which project to submit an issue for. $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => array(t('<none>')) + $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Private helper to implement hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function _project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => check_markup($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => check_markup($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if ($releases) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'value', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } else { // If we're not allowing issue metadata changes, add all of these values // into the form so they show up in the $node->project_issue array during // validation and submit, so we're consistent with where they live. $form['project_issue'] = array('#tree' => TRUE); $form['project_issue']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if (isset($node->project_issue['rid'])) { $form['project_issue']['rid'] = array( '#type' => 'value', '#value' => $node->project_issue['rid'], ); } $form['project_issue']['component'] = array( '#type' => 'value', '#value' => $node->project_issue['component'], ); $form['project_issue']['category'] = array( '#type' => 'value', '#value' => $node->project_issue['category'], ); $form['project_issue']['priority'] = array( '#type' => 'value', '#value' => $node->project_issue['priority'], ); $form['project_issue']['assigned'] = array( '#type' => 'value', '#value' => $node->project_issue['assigned'], ); $form['project_issue']['sid'] = array( '#type' => 'value', '#value' => $node->project_issue['sid'], ); } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Private helper to implement hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function _project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } /** * Private helper to implement hook_insert(). * * @param $node * Object containing form values from the project_issue node form. This is * NOT a fully loaded $node object, so the issue-related values are directly * in $node, not in the $node->project_issue array. */ function _project_issue_insert($node) { // Permanently store the original issue states in a serialized array. This // is a bit yucky, but we need them for proper handling of states workflow. // The current states need to be stored in {project_issues} as well for // query efficiency in issue queue searches, and it seems too messy to add a // bunch of new columns to the {project_issues} table for the original // states. $original_issue_data = new stdClass(); $fields = array( 'pid' => 0, 'rid' => 0, 'component' => '', 'category' => '', 'priority' => 0, 'assigned' => 0, 'sid' => 0, 'title' => '', ); foreach ($fields as $field => $default) { // Some of the incoming data may not have the correct default. if (empty($node->$field)) { $node->$field = $default; } $original_issue_data->$field = $node->$field; } db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); // Invalidate the "Issue cockpit" block cache for this project, since the // new issue will have altered the summary totals. cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); }
Br3nda/drupal-module-project_issue
e4ca12a8fb02e02973fb18ca3eea18030169e301
#579900 by dww, DamZ: Worked-around a 6.14 FAPI regression (#302240) that broke forms which use #type 'button' to trigger a form rebuild. This change will continue to work even in 6.15 and beyond when/if that FAPI regression is fixed, so this should be a long-term solution.
diff --git a/includes/comment.inc b/includes/comment.inc index 9328fe0..2a3f689 100644 --- a/includes/comment.inc +++ b/includes/comment.inc @@ -1,664 +1,673 @@ <?php -// $Id: comment.inc,v 1.154 2009/06/18 03:05:20 dww Exp $ +// $Id: comment.inc,v 1.155 2009/09/23 00:27:05 dww Exp $ function project_issue_comment(&$arg, $op) { // $arg can be a comment object, or a form or form_values. if (is_object($arg)) { $nid = $arg->nid; } elseif (is_array($arg)) { $nid = is_array($arg['nid']) ? $arg['nid']['#value'] : $arg['nid']; } $node = node_load($nid); if ($node->type != 'project_issue') { return; } // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Maintain an array of project ids that are affected by this comment // operation. We'll use this to invalidate the "Issue cockpit" block cache // for any of these projects. $affected_projects = array(); switch ($op) { case 'insert': // Get a lock on the issue in order to generate the next comment ID. $tries = 20; $sleep_increment = 0; while ($tries) { $lock = db_query("UPDATE {project_issues} SET db_lock = 1 WHERE nid = %d AND db_lock = 0", $arg['nid']); if (db_affected_rows()) { $id = db_result(db_query("SELECT last_comment_id FROM {project_issues} WHERE nid = %d", $arg['nid'])) + 1; db_query("UPDATE {project_issues} SET last_comment_id = %d, db_lock = 0 WHERE nid = %d", $id, $arg['nid']); break; } // Wait a random and increasing amount of time before the next attempt. $sleep = rand(10000, 1000000) + $sleep_increment; usleep($sleep); $sleep_increment += 50000; $tries--; } if (isset($id)) { $rid = isset($arg['project_info']['rid']) ? $arg['project_info']['rid'] : 0; db_query("INSERT INTO {project_issue_comments} (nid, cid, pid, rid, component, category, priority, assigned, sid, title, timestamp, comment_number) VALUES (%d, %d, %d, %d, '%s', '%s', %d, %d, %d, '%s', %d, %d)", $arg['nid'], $arg['cid'], $arg['project_info']['pid'], $rid, $arg['project_info']['component'], $arg['category'], $arg['priority'], $arg['project_info']['assigned'], $arg['sid'], $arg['title'], $arg['timestamp'], $id); db_query("UPDATE {comments} SET subject = '%s' WHERE cid = %d", "#$id", $arg['cid']); project_issue_update_by_comment($arg, 'insert'); $affected_projects[$old_data->pid] = 1; $affected_projects[$arg['project_info']['pid']] = 1; } else { drupal_set_message(t('There was an error submitting your comment -- please try again. If the problem persists, contact the system administrator.'), 'error'); watchdog('project_issue', 'Error obtaining lock for project issue %nid', array('%nid' => $arg['nid']), WATCHDOG_ERROR, 'node/'. $arg['nid']); // This is a bit extreme, but we have to clean up the failed comment, // or it will appear on the issue. _comment_delete_thread((object) $arg); _comment_update_node_statistics($arg['nid']); cache_clear_all(); // The hard redirect prevents any bogus data from being inserted for the failed comment. drupal_goto('node/'. $arg['nid']); } break; case 'update': project_issue_update_by_comment($arg, 'update'); // Updating a comment can't change anything relevant about the issue for // the purposes of the issue blocks, so we don't need to touch // $affected_projects here. break; case 'delete': // Save the project that's specified in this comment so we can // invalidate its issue block cache. $deleted_comment_project_id = db_result(db_query("SELECT pid FROM {project_issue_comments} WHERE cid = %d", $arg->cid)); $affected_projects[$deleted_comment_project_id] = 1; // Actually delete the comment db_query("DELETE FROM {project_issue_comments} WHERE cid = %d", $arg->cid); $current_data = project_issue_update_by_comment($arg, 'delete'); // We should also invalidate the block cache for whatever project is now // used for this issue, since we might be deleting a comment that moved // an issue from one project to another. $affected_projects[$current_data->pid] = 1; break; case 'view': if (isset($arg->cid)) { $project_issue_table = project_issue_comment_view($original_node, $arg); } else { // Previewing a comment. $test = drupal_clone($arg); $test->pid = $arg->project_info['pid']; $test->component = $arg->project_info['component']; $test->assigned = $arg->project_info['assigned']; // Add a dummy rid if necessary -- prevents incorrect change data. $test->rid = isset($arg->project_info['rid']) ? $arg->project_info['rid'] : 0; $comment_changes = project_issue_metadata_changes($node, $old_data, $test, project_issue_field_labels('web')); $project_issue_table = theme('project_issue_comment_table', $comment_changes); } if ($project_issue_table) { $arg->comment = '<div class="project-issue"><div class="summary">'. $project_issue_table .'</div></div>' . $arg->comment; } break; } // If there are any affected projects, invalidate the block cache for those. if (!empty($affected_projects)) { foreach ($affected_projects as $pid => $value) { $cid = 'project_issue_cockpit_block:'. $pid; cache_clear_all($cid, 'cache'); } } } /** * Add project issue metadata to the comment form. * * @param $form * Reference to form structure. * @param $form_state * Current form state. */ function project_issue_form_comment_form_alter(&$form, &$form_state) { $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Comment body is not required since we validate that ourselves. unset($form['comment_filter']['comment']['#required']); // The 'your name' item just wastes screen estate. unset($form['_author']); // For existing comments, we want to preserve the comment subject, // Even if the subject field is disabled. if ($cid = $form['cid']['#value']) { $subject = db_result(db_query('SELECT subject FROM {comments} WHERE cid = %d', $cid)); } // For new comments, show the expected next number for previews. // This is only for show, the number will be generated when the comment // is posted. else { $next_id = db_result(db_query('SELECT last_comment_id FROM {project_issues} WHERE nid = %d', $form['nid']['#value'])) + 1; $subject = "#$next_id"; // Clobber the comment signature for new followups if necessary. // TODO: Revamp this for Drupal 6. if (!variable_get('project_issue_show_comment_signatures', 0)) { $form['comment_filter']['comment']['#default_value'] = ''; } } $form['subject'] = array( '#type' => 'value', '#value' => $subject, ); // Any time we're on a reply page, show the full issue below the reply. if (project_issue_is_comment_reply()) { $form['#pre_render'][] = 'project_issue_comment_pre_render'; } // Make sure project is current here -- it may have changed when posted. if (!empty($form_state['values']['project_info']['pid'])) { $node->project_issue['pid'] = $form_state['values']['project_info']['pid']; } $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); project_issue_set_breadcrumb($node, $project); // Only allow metadata changes on new followups. if (isset($form['cid']['#value'])) { return; } // We have to set $form['#action'] to prevent AHAH nastiness. if (!empty($form['pid']['#value'])) { $form['#action'] = url('comment/reply/' . $nid . '/' . $form['pid']['#value']); } else { $form['#action'] = url('comment/reply/' . $nid); } // We need to ask for almost the same metadata as project issue itself // so let's reuse the form. - $form += drupal_retrieve_form('project_issue_form', $node, $form_state, TRUE); + $form += project_issue_form($node, $form_state, TRUE); + + // comment.module is basically still FAPI v1. It sets the preview button to + // #type 'button', so FAPI doesn't really consider that a form submission. + // However, we depend on the form being rebuilt on preview to do our magic. + // Thanks to a change in 6.14 core, form.inc will only rebuild the form if + // $form_state['submitted'] is TRUE. So, we set the preview button to + // actually be a 'submit' button so that the form is rebuilt on preview and + // our comment preview code can kick in. + $form['preview']['#type'] = 'submit'; // We need this otherwise pid collides with comment. $form['project_info']['#tree'] = TRUE; $form['project_info']['#weight'] = -2; // Remove the form item that displays the current project, and // replace the static single project value with a select list // of all projects to make swapping simpler. unset($form['project_info']['project_display']); $uris = NULL; if (variable_get('project_issue_autocomplete', 0) == 1) { $form['project_info']['project_title'] = array( '#type' => 'textfield', '#title' => t('Project'), '#default_value' => $project->title, '#required' => TRUE, '#weight' => -1, '#size' => 35, '#autocomplete_path' => 'project/autocomplete/issue/project', '#attributes' => array( 'onFocus' => 'project_issue_autocomplete_handler()', ), '#ahah' => array( 'progress' => array( 'type' => 'none', ), 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', ), ); } else { $projects = project_projects_select_options($uris); $form['project_info']['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#default_value' => $project->nid, '#options' => $projects, '#required' => TRUE, '#weight' => -1, '#ahah' => array( 'path' => 'project/issues/update_project', 'wrapper' => 'project-info-wrapper', 'event' => 'change', ), ); } $form['issue_info']['#weight'] = -1; $form['#prefix'] = '<div class="project-issue"><div class="node-form"><div class="standard">'; $form['#suffix'] = '</div></div></div>'; $form['original_issue'] = array( '#type' => 'fieldset', '#title' => t('Edit issue settings'), '#description' => t('Note: changing any of these items will update the issue\'s overall values.'), '#collapsible' => TRUE, '#weight' => -10, ); $form['original_issue']['title'] = array( '#type' => 'textfield', '#title' => t('Issue title'), '#maxlength' => 128, '#default_value' => $node->title, '#weight' => -30, '#required' => TRUE, ); $form['project_info']['assigned'] = $form['issue_info']['assigned']; unset($form['issue_info']['assigned']); $form['project_info']['#prefix'] = '<div id="project-info-wrapper" class="inline-options">'; $form['project_info']['#suffix'] = '</div>'; // Remove the 'Project information' and 'Issue information' fieldsets, // since we'll move everything inside the 'Edit issue settings' fieldset. unset($form['project_info']['#type'], $form['project_info']['#title']); unset($form['issue_info']['#type'], $form['issue_info']['#title']); // Restructure the UI to de-emphasize the original project form inputs. $form['original_issue']['project_info'] = $form['project_info']; $form['original_issue']['issue_info'] = $form['issue_info']; unset($form['project_info'], $form['issue_info']); unset($form['issue_details'], $form['project_help']); drupal_add_js(drupal_get_path('module', 'project_issue') .'/project_issue.js'); } /** * Validate issue metadata on the comment form. * * @param $form * The Drupal form structure. * @param $form_state * The current state of the form. */ function project_issue_form_comment_validate($form, &$form_state) { if (empty($form['cid']['#value']) && variable_get('project_issue_autocomplete', 0) == 1) { if (empty($form_state['values']['project_info']['project_title'])) { form_set_error('project_title', t('You must enter a project to navigate to.')); } else { $pid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_info']['project_title'], 'project_project')); if (empty($pid)) { form_set_error('project_info][project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_info']['project_title']))); } else { $form_state['values']['project_info']['pid'] = $pid; } } } if (!empty($form_state['rebuild'])) { return; } $values = $form_state['values']; $project_info = $form_state['values']['project_info']; $nid = $values['nid']; $node = node_load($nid); // Make a copy here so we have all the original metadata, since some // of it can change below. $original_node = drupal_clone($node); $old_data = (object) $original_node->project_issue; $old_data->title = $original_node->title; // Adjust new file attachments to go to the issues directory. // We have to do this during validate, otherwise we might miss // adjusting the filename before comment upload saves it (module weighting) // TODO: is this still true? project_issue_change_comment_upload_path($values); // Only validate metadata changes on new followups. if (isset($values['cid'])) { return; } // Make sure project is current here -- it may have changed when posted. if (isset($project_info['pid'])) { $node->project_issue['pid'] = $project_info['pid']; } $project = node_load($node->project_issue['pid']); if (!empty($project) && $project->type == 'project_project') { // Force all comments to be a child of the main issue, to match the // flat display, and also to prevent accidentally deleting a thread. $form_state['values']['pid'] = 0; // Validate version. if (module_exists('project_release') && isset($project_info['rid']) && ($releases = project_release_get_releases($project, 0, 'version', 'all', array($project_info['rid'])))) { $rid = $project_info['rid']; if ($rid && !in_array($rid, array_keys($releases))) { $rid = 0; } // Check to make sure this release is not marked as an invalid // release node for user selection. $invalid_rids = variable_get('project_issue_invalid_releases', array()); if (!empty($invalid_rids) && ((empty($rid) && in_array($node->project_issue['rid'], $invalid_rids)) || in_array($rid, $invalid_rids))) { form_set_error('project_info][rid', t('%version is not a valid version, please select a different value.', array('%version' => $releases[$node->project_issue['rid']]))); } elseif (empty($rid)) { form_set_error('project_info][rid', t('You have to specify a valid version.')); } } // Add a dummy rid if necessary -- prevents incorrect change data. else { $rid = 0; } // Validate component. $component = $project_info['component']; if ($component && !in_array($component, $project->project_issue['components'])) { $component = 0; } empty($component) && form_set_error('project_info][component', t('You have to specify a valid component.')); } else { form_set_error('project_info][pid', t('You have to specify a valid project.')); } empty($values['category']) && form_set_error('category', t('You have to specify a valid category.')); // Now, make sure the comment changes *something* about the issue. // If the user uploaded a file, so long as it's not marked for removal, // we consider that a valid change to the issue, too. $has_file = FALSE; $files = isset($values['files']) ? $values['files'] : array(); foreach ($files as $number => $data) { if (empty($data['remove'])) { $has_file = TRUE; break; } } if (!$has_file && empty($values['comment'])) { $comment = drupal_clone((object) $values); $comment->pid = $project_info['pid']; $comment->component = $component; $comment->rid = $rid; $comment->assigned = $project_info['assigned']; $comment_changes = project_issue_metadata_changes($node, $old_data, $comment, project_issue_field_labels('web')); // If the PID changed, rebuild the form if (isset($comment_changes['pid']['new']) && $comment_changes['pid']['new'] === TRUE) { $form_state['rebuild'] = TRUE; } $has_change = FALSE; foreach ($comment_changes as $field => $changes) { if (isset($changes['new'])) { $has_change = TRUE; break; } } if (!$has_change) { form_set_error('comment', t('You must either add a comment, upload a file, or change something about this issue.')); } } } /** * Theme a project issue metadata table. * * @param $comment_changes * Array containing metadata differences between comments * as returned by project_issue_metadata_changes(). * @return * The themed metadata table. */ function theme_project_issue_comment_table($comment_changes) { $rows = array(); foreach ($comment_changes as $field => $change) { if (!empty($change['label']) && isset($change['old']) && isset($change['new'])) { $rows[] = theme('project_issue_comment_table_row', $field, $change); } } return theme('table', array(), $rows); } /** * Theme a single row of the project issue metadata changes table. * * @param $field * The name of the field to theme. * @param $change * A nested array containing changes to project issue metadata * for the given issue or comment. * @return * An array representing one row of the table. * * NOTE: If you override this theme function, you *must* make sure * that you sanitize all output from this function that is displayed * to the user. No further escaping/filtering of the data in this * table will take place after this function. In most cases * this means that you need to run the $change['label'], $change['old'], * and $change['new'] values through either the check_plain() or * filter_xss() function to prevent XSS and other types * of problems due to any malicious input in these * field values. */ function theme_project_issue_comment_table_row($field, $change) { // Allow anchor, emphasis, and strong tags in metadata tables. $allowed_tags = array('a', 'em', 'strong'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); if (is_array($change['old']) || is_array($change['new'])) { $removed = array(); if (is_array($change['old'])){ foreach ($change['old'] as $item) { $removed[] = '-'. $item; } } elseif (!empty($change['old'])) { $removed[] = '-'. $change['old']; } $added = array(); if (is_array($change['new'])) { foreach ($change['new'] as $item) { $added[] = '+'. $item; } } elseif (!empty($change['new'])) { $added[] = '+'. $change['new']; } return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(implode(', ', $removed), $allowed_tags), filter_xss(implode(', ', $added), $allowed_tags), ); } elseif (in_array($field, $plain_fields)) { return array( filter_xss($change['label'], $allowed_tags) .':', check_plain(project_issue_change_summary($field, $change['old'])), '&raquo; '. check_plain(project_issue_change_summary($field, $change['new'])), ); } else { return array( filter_xss($change['label'], $allowed_tags) .':', filter_xss(project_issue_change_summary($field, $change['old']), $allowed_tags), '&raquo; '. filter_xss(project_issue_change_summary($field, $change['new']), $allowed_tags), ); } } /** * Returns the issue metadata table for a comment. * * @param $node * The corresponding node. * @param $comment * The comment, if it's set then metadata will be returned. If it's not * set then metadata will be precalculated. * @return * A themed table of issue metadata. */ function project_issue_comment_view(&$node, $comment = NULL) { static $project_issue_tables; if (isset($comment)) { return isset($project_issue_tables[$comment->cid]) ? $project_issue_tables[$comment->cid] : ''; } if (!empty($node->comment_count)) { $old = unserialize(db_result(db_query('SELECT original_issue_data FROM {project_issues} WHERE nid = %d', $node->nid))); $labels = project_issue_field_labels('web'); $result = db_query('SELECT p.cid, p.title, p.pid, p.rid, p.component, p.category, p.priority, p.assigned, p.sid FROM {project_issue_comments} p INNER JOIN {comments} c ON p.cid = c.cid WHERE p.nid = %d AND c.status = %d ORDER BY p.timestamp ASC', $node->nid, COMMENT_PUBLISHED); while ($followup = db_fetch_object($result)) { $followup_changes = project_issue_metadata_changes($node, $old, $followup, project_issue_field_labels('web')); $project_issue_tables[$followup->cid] = theme('project_issue_comment_table', $followup_changes); $old = $followup; } } } /** * Updates the project issue based on the comment inserted/updated/deleted. * * @param $comment_data * The comment data that's been submitted. * @param $op * The comment operation performed, 'insert', 'update', 'delete'. * @return * An object representing the comment data used to update the issue. */ function project_issue_update_by_comment($comment_data, $op) { switch ($op) { case 'insert': // Massage the incoming data so the structure is consistent throughout the function. $comment_data['component'] = $comment_data['project_info']['component']; $comment_data['pid'] = $comment_data['project_info']['pid']; $comment_data['rid'] = isset($comment_data['project_info']['rid']) ? $comment_data['project_info']['rid'] : 0; unset ($comment_data['project_info']); $comment_data = (object) $comment_data; // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. if (!isset($comment_data->followup_no_mail)) { // Temporary hack to get around sending of auto-close emails. project_issue_set_mail_notify($comment_data->nid); } break; case 'update': $comment_data = (object) $comment_data; break; } // In order to deal with deleted/unpublished comments, make sure that we're performing // the updates to the issue with the latest available published comment. $comment_data = project_issue_get_newest_comment($comment_data); // Update the issue data to reflect the new final states. db_query("UPDATE {project_issues} SET pid = %d, category = '%s', component = '%s', priority = %d, rid = %d, assigned = %d, sid = %d WHERE nid = %d", $comment_data->pid, $comment_data->category, $comment_data->component, $comment_data->priority, $comment_data->rid, $comment_data->assigned, $comment_data->sid, $comment_data->nid); // Update the issue title. $node = node_load($comment_data->nid, NULL, TRUE); // Don't use cached since we changed data above. $node->title = $comment_data->title; // This also updates the changed date of the issue. node_save($node); // Return the object of comment data we used to update the issue. return $comment_data; } /** * Adjusts the filepath of issue followups so files are saved to * the correct issues directory. * * @param $comment * An array of the submitted comment values. */ function project_issue_change_comment_upload_path(&$comment) { static $run = NULL; // Only for new comments with attachments. if (empty($comment['cid']) && isset($comment['files']) && !isset($run)) { $run = TRUE; // Make sure this only gets run once. project_issue_rewrite_issue_filepath($comment['files']); } } /** * Retrieves the newest published comment for an issue. * * @param $comment_data * An object representing the current comment being edited * @return * An object representing the most recent published comment for the issue. */ function project_issue_get_newest_comment($comment_data) { // Get the cid of the most recent comment. $latest_cid = db_result(db_query_range('SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp DESC', $comment_data->nid, COMMENT_PUBLISHED, 0, 1)); if ($latest_cid) { $comment_data = db_fetch_object(db_query('SELECT * FROM {project_issue_comments} WHERE cid = %d', $latest_cid)); } // No more comments on the issue -- use the original issue metadata. else { // nid isn't stored in the original issue data, so capture it here and pass back // into the object. $nid = $comment_data->nid; $comment_data = unserialize(db_result(db_query("SELECT original_issue_data FROM {project_issues} WHERE nid = %d", $comment_data->nid))); $comment_data->nid = $nid; } return $comment_data; } /** * Test to determine if the active page is the comment reply form. * * @return * TRUE if the active page is the comment reply form, FALSE otherwise. */ function project_issue_is_comment_reply() { return arg(0) == 'comment' && arg(1) == 'reply'; } /** * Test to determine if the active page is the comment edit form. * * @return * TRUE if the active page is the comment edit form, FALSE otherwise. */ function project_issue_is_comment_edit() { return arg(0) == 'comment' && arg(1) == 'edit'; } /** * Appends the comment thread to the comment reply form. */ function project_issue_comment_pre_render($form) { // Force the correct formatting. $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; $suffix = empty($form['#suffix']) ? '' : $form['#suffix']; $node = node_load($form['nid']['#value']); // Unfortunately, the comment module blindly puts the node view // after the comment form on preview, in the case where the comment // parent is 0. If we want our issue previews to be consistent, this // ugly hack is necessary. if (isset($form['#parameters'][1]['values']['op']) && $form['#parameters'][1]['values']['op'] == t('Preview')) { $preview = comment_render($node, 0); } else { $preview = node_show($node, 0); } $form['#suffix'] = $suffix . $preview; return $form; }
Br3nda/drupal-module-project_issue
4d98d6be82610006aefd65919f0f785f1d1909b7
#582402 by dww: The default issue views that include exposed filters for taxonomy vocabularies which apply to issue nodes should unlock the operator so that you can, e.g. filter by issues without a given tag.
diff --git a/views/project_issue.views_default.inc b/views/project_issue.views_default.inc index d7896cd..333bc9d 100644 --- a/views/project_issue.views_default.inc +++ b/views/project_issue.views_default.inc @@ -1,70 +1,70 @@ <?php -// $Id: project_issue.views_default.inc,v 1.47 2009/06/18 03:38:42 dww Exp $ +// $Id: project_issue.views_default.inc,v 1.48 2009/09/23 00:21:36 dww Exp $ /** * @file * Provides default views on behalf of the project_issue module. */ /** * Implementation of hook_views_default_views(). */ function project_issue_views_default_views() { // Search the "default_views" directory for files ending in .view.php. $files = file_scan_directory(drupal_get_path('module', 'project_issue'). '/views/default_views', 'view.php'); foreach ($files as $absolute => $file) { require_once $absolute; if (isset($view)) { // $file->name has the ".php" stripped off, but still has the ".view". $view_name = substr($file->name, 0, strrpos($file->name, '.')); $views[$view_name] = $view; } } return $views; } /** * Add exposed filters for every taxonomy vocabulary for project_issue nodes. * * This is a helper function used by a few of the default view definitions. */ function _project_issue_views_add_taxonomy_filters(&$filters) { if (!module_exists('taxonomy')) { return; } $issue_vocabularies = taxonomy_get_vocabularies('project_issue'); $i = 0; foreach ($issue_vocabularies as $vid => $vocab) { $view_key = 'tid'; if ($i) { $view_key .= "_$i"; } $i++; $identifier = project_issue_views_filter_identifier($vocab->name); $filters[$view_key] = array( 'operator' => 'or', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( - 'use_operator' => 0, - 'operator' => 'tid_op', + 'use_operator' => 1, + 'operator' => $identifier . '_op', 'identifier' => $identifier, 'label' => check_plain($vocab->name), 'optional' => 1, 'single' => 1, 'remember' => 0, ), 'type' => 'textfield', 'vid' => $vid, 'id' => 'tid', 'table' => 'term_node', 'field' => 'tid', 'hierarchy' => 0, 'relationship' => 'none', 'reduce_duplicates' => 1, ); } }
Br3nda/drupal-module-project_issue
ba8713c7b1d6b61dc4c20b7a9a82079a71dafe47
#546488 by dww: Fixed D6 schema regression where {project_issue_comments} no longer used 'cid' as the primary key.
diff --git a/project_issue.install b/project_issue.install index 5d91edb..4c5d7bb 100644 --- a/project_issue.install +++ b/project_issue.install @@ -1,435 +1,448 @@ <?php -// $Id: project_issue.install,v 1.63 2009/08/03 19:16:36 dww Exp $ +// $Id: project_issue.install,v 1.64 2009/08/21 22:51:31 dww Exp $ /** * Implementation of hook_schema(). */ function project_issue_schema() { $schema['project_issue_projects'] = array( 'description' => 'Table containing per-project issue-related settings.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {project_projects}.nid of the project.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'issues' => array( 'description' => 'Boolean value indicating whether or not issue-tracking is enabled for this project.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'components' => array( 'description' => 'A serialized array defining the components for this project.', 'type' => 'text', 'not null' => FALSE, ), 'default_component' => array( 'description' => 'The default component for new issues of this project, or an empty string if the user needs to select a component.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'help' => array( 'description' => 'Submission guidelines for issues added to this project.', 'type' => 'text', 'not null' => FALSE, ), 'mail_digest' => array( 'description' => 'E-mail address for the weekly critical issues report.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy' => array( 'description' => 'E-mail address to send a copy of all issues to.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter' => array( 'description' => 'A serialized array containing the types of issues to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter_state' => array( 'description' => 'A serialized array containing the statuses to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_reminder' => array( 'description' => 'Boolean indicating whether or not users with open issues should receive a monthly reminder.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('nid'), ); $schema['project_issues'] = array( 'description' => 'The base table for issues.', 'fields' => array( 'nid' => array( 'description' => 'Primary Key: The {node}.nid of this project_issue node.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'category' => array( 'description' => 'Category of the issue.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'component' => array( 'description' => 'Component of the issue as defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => 'The priority for this issue.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) for this issue (only used in conjunction with the project_release module).', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue is currently assigned.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'Current {project_issue_state}.sid of this issue.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'original_issue_data' => array( 'description' => 'A serialized object containing the original metadata values that were used when this issue was created.', 'type' => 'text', 'not null' => TRUE, ), 'last_comment_id' => array( 'description' => '{comments}.cid of the most recent comment added to the issue. 0 if no comment has been added yet.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'db_lock' => array( 'description' => 'Row-lock indicator to prevent race conditions when determining sequential comment number (http://drupal.org/node/180866).', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_issues_pid' => array('pid'), 'project_issues_sid' => array('sid'), 'project_issues_nid_assigned' => array('nid', 'assigned'), ), 'primary key' => array('nid'), ); $schema['project_issue_comments'] = array( 'description' => 'The base table for comments added to issues.', 'fields' => array( 'nid' => array( 'description' => 'References {project_issues}.nid, the issue to which this comment was added.', 'type' => 'int', 'not null' => FALSE, ), 'cid' => array( - 'description' => 'The {comments}.cid for this comment.', + 'description' => 'Primary Key: The {comments}.cid for this comment.', 'type' => 'int', 'not null' => FALSE, ), 'rid' => array( 'description' => 'The {project_release_nodes}.rid (version identifier) after this comment was made (only used in conjunction with the project_release module).', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'component' => array( 'description' => 'Component of the issue after this comment was made. Components are defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'category' => array( 'description' => 'Category of this issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => 'The priority for this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => 'The {users}.uid of the user to which this issue was assigned after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => 'The {project_issue_state}.sid of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => 'The {project_projects}.nid of the project to which this issue belongs after this comment was made.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'title' => array( 'description' => 'The title of the issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, ), 'timestamp' => array( 'description' => 'Timestamp for this comment.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, ), 'comment_number' => array( 'description' => 'The sequential number for this comment in the issue.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), ), + 'primary key' => array('cid'), 'indexes' => array( 'nid_timestamp' => array('nid', 'timestamp'), 'comment_number' => array('comment_number'), ), ); $schema['project_subscriptions'] = array( 'description' => 'Table keeping track of per-user project_issue subscriptions.', 'fields' => array( 'nid' => array( 'description' => '{project_projects}.nid of the project to which the user is subscribed.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'uid' => array( 'description' => 'The {users}.uid for this subscriber.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'level' => array( 'description' => 'The type of subscription for the project. Possible values are: 0 = not subscribed, 1 = subscribed to own issues or 2 = subscribed to all issues.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_subscriptions_nid_uid_level' => array('nid', 'uid', 'level'), ), ); $schema['project_issue_state'] = array( 'description' => 'Table that holds all possible values for issue statuses.', 'fields' => array( 'sid' => array( 'description' => 'Primary Key: Unique id for this status.', 'type' => 'serial', 'unsigned' => 1, 'not null' => TRUE, ), 'name' => array( 'description' => 'Display-friendly name for this status.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => 'Weight for this status, used when ordering statuses', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'author_has' => array( 'description' => 'Boolean indicating whether or not the author of an issue may use this issue status in that issue, regardless of the permissions controlling site-wide use of this status.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'default_query' => array( 'description' => 'Boolean indicating whether or not issues with this status are included in default queries.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('sid'), ); return $schema; } function project_issue_install() { // We need to check this before we try to create the table, so that // if it already exists, we don't attempt to insert our own values. $project_issue_state_existed = db_table_exists('project_issue_state'); // Create tables. drupal_install_schema('project_issue'); if (!$project_issue_state_existed) { // sid, name, weight, author-can-set, in-default-queries project_issue_init_state(1, 'active', -13, 0, 1); project_issue_init_state(2, 'fixed', 1, 0, 1); project_issue_init_state(3, 'duplicate', 4, 0, 0); project_issue_init_state(4, 'postponed', 6, 0, 1); project_issue_init_state(5, "won't fix", 9, 0, 0); project_issue_init_state(6, 'by design', 11, 0, 0); project_issue_init_state(7, 'closed', 13, 1, 0); project_issue_init_state(8, 'needs review', -8, 0, 0); project_issue_init_state(13, 'needs work', -6, 0, 0); project_issue_init_state(14, 'ready to commit', -2, 0, 0); // Since we're hacking in auto-increment values here, // update the sequence value for Postgres -- ugly but necessary for now. if ($GLOBALS['db_type'] == 'pgsql') { db_query("SELECT setval('project_issue_state_sid_seq', 14)"); } } project_issue_add_missing_projects(); db_query("UPDATE {system} SET weight = 2 WHERE name = 'project_issue'"); // Set up future followups to be read/write. if (module_exists('comment')) { variable_set('comment_project_issue', COMMENT_NODE_READ_WRITE); } // Enable file attachments for followups. variable_set('comment_upload_project_issue', 1); // Enable file attachments for issues. variable_set('upload_project_issue', 1); } /** * Implementation of hook_uninstall(). */ function project_issue_uninstall() { // Remove tables. drupal_uninstall_schema('project_issue'); $variables = array( 'project_issue_default_state', 'project_directory_issues', 'project_reply_to', 'project_issue_digest_last', 'project_issue_cockpit_categories', 'project_issue_digest_interval', 'project_issue_reminder_last', 'project_issue_reminder_interval', 'project_issue_show_comment_signatures', 'project_issue_site_help', 'project_issue_invalid_releases', 'project_issue_followup_user', 'project_issue_hook_cron', ); foreach ($variables as $variable) { variable_del($variable); } } function project_issue_enable() { project_issue_add_missing_projects(); } /** * Initialize a given issue state in the database. */ function project_issue_init_state($sid, $name, $weight, $author, $query) { db_query("INSERT INTO {project_issue_state} (sid, name, weight, author_has, default_query) VALUES (%d, '%s', %d, %d, %d)", $sid, $name, $weight, $author, $query); } /** * Check for existing project nodes that do not have an entry in the * {project_issue_projects} table, and add them. * */ function project_issue_add_missing_projects() { $projects = db_query("SELECT n.nid, pip.nid AS pip_nid FROM {node} n LEFT JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.type = 'project_project' AND pip.nid IS NULL"); while ($project = db_fetch_object($projects)) { db_query('INSERT INTO {project_issue_projects} (nid) VALUES (%d)', $project->nid); } } /** * Remove stale setting that's now provided by views. */ function project_issue_update_6000() { variable_del('project_issues_per_page'); return array(); } /** * Add the 'default_component' field to {project_issue_projects}. */ function project_issue_update_6001() { $ret = array(); db_add_field($ret, 'project_issue_projects', 'default_component', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '')); return $ret; } +/** + * Make {project_issue_comments}.cid the primary key for that table. + */ +function project_issue_update_6002() { + $ret = array(); + db_add_primary_key($ret, 'project_issue_comments', array('cid')); + if (empty($ret[0]['success'])) { + return array(array('success' => TRUE, 'query' => '<strong>' . t("It is safe to ignore warnings about 'Multiple primary key defined'.") . '</strong>')); + } + return $ret; +} +
Br3nda/drupal-module-project_issue
3ff963707b6c27e7a2e052a88b1bc1743cdfc1b0
#554978 by dww: Fixed bug where the tabledrag breaks the component editing UI for projects with tons of components since the weight field didn't have a sufficiently large delta to keep things ordered properly.
diff --git a/includes/project_edit_issues.inc b/includes/project_edit_issues.inc index a964aef..8672ce3 100644 --- a/includes/project_edit_issues.inc +++ b/includes/project_edit_issues.inc @@ -1,290 +1,292 @@ <?php -// $Id: project_edit_issues.inc,v 1.2 2009/05/05 19:15:58 dww Exp $ +// $Id: project_edit_issues.inc,v 1.3 2009/08/21 21:58:23 dww Exp $ /** * @file * Code for the "issues" subtab to the edit tab on project nodes. */ /** * Page callback for the "issues" subtab to the edit tab on project nodes. */ function project_issue_project_edit_issues($node) { project_project_set_breadcrumb($node); drupal_set_title(check_plain($node->title)); return drupal_get_form('project_issue_project_edit_form', $node); } /** * Theme function to render the issue subtab form. */ function theme_project_issue_project_edit_form($form) { drupal_add_tabledrag('project-issue-edit-project-components-table', 'order', 'self', 'project-issue-component-weight'); $header = array( array('data' => t('Name')), array('data' => t('Weight')), array('data' => t('Operations')) ); // List the existing components. foreach (element_children($form['component']) as $key) { $rows[] = array( 'class' => 'draggable', 'data' => array( drupal_render($form['component'][$key]['name']), drupal_render($form['component'][$key]['weight']), drupal_render($form['component'][$key]['delete']), ), ); } // Add a row to add a new component. $rows[] = array( 'class' => 'draggable', 'data' => array( drupal_render($form['component_add']['name']), drupal_render($form['component_add']['weight']), NULL, ), ); $output = drupal_render($form['issue']); $output .= drupal_render($form['email']); $output .= '<h3>' . t('Issue components') . '</h3>'; $output .= '<div>' . theme('table', $header, $rows, array('id' => 'project-issue-edit-project-components-table')) . '</div>'; $output .= drupal_render($form); return $output; } /** * Form builder for the issues subtab on the edit tab for project nodes. */ function project_issue_project_edit_form(&$form_state, $node) { /* Issue properties */ $form['issue'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#collapsible' => TRUE, ); $form['issue']['issue'] = array( '#type' => 'item', '#title' => t('Issue tracker'), ); $form['issue']['issues'] = array( '#type' => 'checkbox', '#title' => t('Enable issue tracker'), '#return_value' => 1, '#default_value' => isset($node->project_issue['issues']) ? $node->project_issue['issues'] : 1, '#description' => t('Let users submit bug requests, patches, feature requests, support requests, etc.'), ); $form['issue']['help'] = array( '#type' => 'textarea', '#title' => t('Submission guidelines'), '#default_value' => isset($node->project_issue['help']) ? $node->project_issue['help'] : NULL, '#cols' => 20, '#rows' => 5, ); $weight = 0; $default_component_options[0] = t('<none> (user must select)'); $form['component']['#tree'] = TRUE; + $number_components = count($node->project_issue['components']); + $delta = max(20, $number_components + 10); foreach ($node->project_issue['components'] as $component) { $default_component_options[$component] = $component; $form['component'][$component]['name'] = array( '#type' => 'textfield', '#default_value' => $component, '#size' => 20, ); $form['component'][$component]['weight'] = array( '#type' => 'weight', '#default_value' => $weight, - '#delta' => 15, + '#delta' => $delta, '#attributes' => array('class' => 'project-issue-component-weight'), ); // For the delete links, we just need the offset of the component as // currently stored in the DB or node. So, we can just use the $weight. // Using an integer offset avoids problems with urlencoding for component // names that have '/' in them. $del_link = ($component != $node->project_issue['default_component']) ? l(t('Delete'), 'node/'. $node->nid .'/edit/component/delete/'. $weight) : ''; $form['component'][$component]['delete'] = array( '#type' => 'markup', '#value' => $del_link, ); $weight++; } $form['component_add']['#tree'] = TRUE; $form['component_add']['name'] = array( '#type' => 'textfield', '#size' => 20, ); $form['component_add']['weight'] = array( '#type' => 'weight', '#default_value' => $weight, - '#delta' => 15, + '#delta' => $delta, '#attributes' => array('class' => 'project-issue-component-weight'), ); $form['default_component'] = array( '#type' => 'select', '#title' => t('Default component for new issues'), '#options' => $default_component_options, '#default_value' => !empty($node->project_issue['default_component']) ? $node->project_issue['default_component'] : 0, ); /* E-mail options */ $form['email'] = array( '#type' => 'fieldset', '#title' => t('Issue e-mail options'), '#collapsible' => TRUE, '#collapsed' => TRUE, ); $form['email']['mail_digest'] = array( '#type' => 'textfield', '#title' => t('Weekly critical issues report'), '#default_value' => isset($node->project_issue['mail_digest']) ? $node->project_issue['mail_digest'] : NULL, '#size' => 20, '#maxlength' => 255, '#description' => t('To get a weekly digest of critical issues specify an e-mail address.'), ); $form['email']['mail_copy'] = array( '#type' => 'textfield', '#title' => t('Issues e-mail address'), '#default_value' => isset($node->project_issue['mail_copy']) ? $node->project_issue['mail_copy'] : NULL, '#size' => 20, '#maxlength' => 255, '#description' => t('If you wish to receive a copy of all the issues to a central location specify an address here. <em>Note: the copy will contain links to file attachments.</em>'), ); $options = project_issue_category(); $form['email']['categories'] = array( '#type' => 'item', '#title' => t('Categories'), '#description' => t('Which issue categories to e-mail. If none is checked all categories will be posted.'), ); $form['email']['mail_copy_filter']['#tree'] = TRUE; foreach ($options as $key => $choice) { $form['email']['mail_copy_filter'][$key] = array( '#type' => 'checkbox', '#title' => $choice, '#return_value' => $key, '#default_value' => isset($node->project_issue['mail_copy_filter'][$key]) ? $node->project_issue['mail_copy_filter'][$key] : NULL, ); } $options = project_issue_state(); $form['email']['states'] = array( '#type' => 'item', '#title' => t('States'), '#description' => t('Which issue states to e-mail. If none is checked all states will be posted.'), ); $form['email']['mail_copy_filter_state']['#tree'] = TRUE; foreach ($options as $key => $choice) { $form['email']['mail_copy_filter_state'][$key] = array( '#type' => 'checkbox', '#title' => check_plain($choice), '#return_value' => $key, '#default_value' => isset($node->project_issue['mail_copy_filter_state'][$key]) ? $node->project_issue['mail_copy_filter_state'][$key] : NULL, ); } if (user_access('administer projects')) { $form['email']['reminder'] = array( '#type' => 'item', '#title' => t('Monthly reminder'), ); $form['email']['mail_reminder'] = array( '#type' => 'checkbox', '#title' => t('Send monthly reminders to users'), '#return_value' => 1, '#default_value' => isset($node->project_issue['mail_reminder']) ? $node->project_issue['mail_reminder'] : NULL, '#description' => t('Enabling this will send a monthly reminder to users that have open issues registered.'), ); } $form['nid'] = array('#type' => 'value', '#value' => $node->nid); $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), '#weight' => 45, ); return $form; } /** * Validation handler when project admins use the issues subtab. * @see project_issue_project_edit_issues */ function project_issue_project_edit_form_validate($form, &$form_state) { if (!empty($form_state['values']['mail_digest']) && ($data = user_validate_mail($form_state['values']['mail_digest']))) { form_set_error('mail_digest', $data); } if (!empty($form_state['values']['mail_copy']) && ($data = user_validate_mail($form_state['values']['mail_copy']))) { form_set_error('mail_copy', $data); } } /** * Submit handler when project admins use the issues subtab. * @see project_issue_project_edit_issues */ function project_issue_project_edit_form_submit($form, &$form_state) { $components = array(); if (!empty($form_state['values']['component_add']['name'])) { $components[trim($form_state['values']['component_add']['name'])] = $form_state['values']['component_add']['weight']; } if (!empty($form_state['values']['component'])) { foreach ($form_state['values']['component'] as $component) { $components[trim($component['name'])] = $component['weight']; } } asort($components); $components = serialize(array_keys($components)); $default_component = !empty($form_state['values']['default_component']) ? $form_state['values']['default_component'] : ''; $mail_copy_filter = serialize($form_state['values']['mail_copy_filter']); $mail_copy_filter_state = serialize($form_state['values']['mail_copy_filter_state']); db_query("UPDATE {project_issue_projects} SET issues = %d, components = '%s',default_component = '%s', mail_digest = '%s', mail_reminder = %d, mail_copy = '%s', mail_copy_filter = '%s', mail_copy_filter_state = '%s', help = '%s' WHERE nid = %d", $form_state['values']['issues'], $components, $default_component, $form_state['values']['mail_digest'], $form_state['values']['mail_reminder'], $form_state['values']['mail_copy'], $mail_copy_filter, $mail_copy_filter_state, $form_state['values']['help'], $form_state['values']['nid']); db_query("UPDATE {node} SET changed = %d WHERE nid = %d", time(), $form_state['values']['nid']); drupal_set_message(t('Issue settings have been saved.')); } function project_issue_component_delete_form($form_state, $project, $component_offset) { $component = $project->project_issue['components'][$component_offset]; $form['component'] = array( '#type' => 'value', '#value' => $component, ); $form['project'] = array( '#type' => 'value', '#value' => $project, ); return confirm_form( $form, t('Are you sure you want to delete the component %component?', array('%component' => $component)), 'node/' . $project->nid . '/edit/issues', t('This action cannot be undone.'), t('Delete'), t('Cancel') ); } function project_issue_component_delete_form_submit($form, &$form_state) { $project = $form_state['values']['project']; $component = $form_state['values']['component']; project_issue_delete_component($project, $component); drupal_set_message(t('Issue component %component deleted.', array('%component' => $component))); $form_state['redirect'] = 'node/' . $project->nid . '/edit/issues'; } /** * Remove a component from a given project. * * @param $project * The project to remove the component from. * @param $component * The component to remove. */ function project_issue_delete_component($project, $component) { $components = array_diff($project->project_issue['components'], array($component)); db_query("UPDATE {project_issue_projects} SET components = '%s' WHERE nid = %d", serialize($components), $project->nid); db_query("UPDATE {node} SET changed = %d WHERE nid = %d", time(), $project->nid); }
Br3nda/drupal-module-project_issue
c097ea866f616ef1c782b870759843a93bf365b3
#374863 by greggles, dww: Changed the code that renders the "submission guidelines" text (both per-project and site-wide) to use the default input format instead of filter_xss() so that "block" HTML elements are preserved.
diff --git a/includes/issue_node_form.inc b/includes/issue_node_form.inc index b7c2a0a..18b4561 100644 --- a/includes/issue_node_form.inc +++ b/includes/issue_node_form.inc @@ -1,477 +1,477 @@ <?php -// $Id: issue_node_form.inc,v 1.3 2009/08/06 23:31:23 dww Exp $ +// $Id: issue_node_form.inc,v 1.4 2009/08/11 17:13:57 dww Exp $ /** * @file * Code required for the issue node form. */ /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects. $uris = NULL; $projects = project_projects_select_options($uris); if (!$projects) { drupal_set_message(t('You do not have access to any projects.'), 'error'); } elseif (count($projects) == 1) { $project = node_load(key($projects)); drupal_goto('node/add/project-issue/' . $project->project['uri']); } $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => array(t('<none>')) + $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Private helper to implement hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function _project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', - '#value' => filter_xss($site_help), + '#value' => check_markup($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', - '#value' => filter_xss($project_help), + '#value' => check_markup($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if ($releases) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'value', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } else { // If we're not allowing issue metadata changes, add all of these values // into the form so they show up in the $node->project_issue array during // validation and submit, so we're consistent with where they live. $form['project_issue'] = array('#tree' => TRUE); $form['project_issue']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if (isset($node->project_issue['rid'])) { $form['project_issue']['rid'] = array( '#type' => 'value', '#value' => $node->project_issue['rid'], ); } $form['project_issue']['component'] = array( '#type' => 'value', '#value' => $node->project_issue['component'], ); $form['project_issue']['category'] = array( '#type' => 'value', '#value' => $node->project_issue['category'], ); $form['project_issue']['priority'] = array( '#type' => 'value', '#value' => $node->project_issue['priority'], ); $form['project_issue']['assigned'] = array( '#type' => 'value', '#value' => $node->project_issue['assigned'], ); $form['project_issue']['sid'] = array( '#type' => 'value', '#value' => $node->project_issue['sid'], ); } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Private helper to implement hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function _project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } /** * Private helper to implement hook_insert(). * * @param $node * Object containing form values from the project_issue node form. This is * NOT a fully loaded $node object, so the issue-related values are directly * in $node, not in the $node->project_issue array. */ function _project_issue_insert($node) { // Permanently store the original issue states in a serialized array. This // is a bit yucky, but we need them for proper handling of states workflow. // The current states need to be stored in {project_issues} as well for // query efficiency in issue queue searches, and it seems too messy to add a // bunch of new columns to the {project_issues} table for the original // states. $original_issue_data = new stdClass(); $fields = array( 'pid' => 0, 'rid' => 0, 'component' => '', 'category' => '', 'priority' => 0, 'assigned' => 0, 'sid' => 0, 'title' => '', ); foreach ($fields as $field => $default) { // Some of the incoming data may not have the correct default. if (empty($node->$field)) { $node->$field = $default; } $original_issue_data->$field = $node->$field; } db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); // Invalidate the "Issue cockpit" block cache for this project, since the // new issue will have altered the summary totals. cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); }
Br3nda/drupal-module-project_issue
58856a4a2276c96c8e6edbb551e344d18c41ca67
#229063 by dww, mikehostetler, jeffschuler, greggles: Added token support.
diff --git a/project_issue.module b/project_issue.module index e323622..0371904 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,514 +1,514 @@ <?php -// $Id: project_issue.module,v 1.173 2009/06/18 03:30:22 dww Exp $ +// $Id: project_issue.module,v 1.174 2009/08/06 23:35:34 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); foreach (array('comment', 'mail') as $file) { module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); @@ -741,954 +741,1023 @@ function project_issue_nodeapi(&$node, $op, $arg) { */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implement hook_delete() for project issue nodes. */ function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } /** * Implement hook_form() for project issue nodes. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_form($node, $form_state, $include_metadata_fields); } /** * Implement hook_validate() for project issue nodes. */ function project_issue_validate($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_validate($node); } /** * Implement hook_insert() for project issue nodes. */ function project_issue_insert($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_insert($node); } /** * Implement hook_view() for project issue nodes. */ function project_issue_view($node, $teaser = FALSE, $page = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_view'); return _project_issue_view($node, $teaser, $page); } /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { foreach ($nids as $nid) { project_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes)); } $output = '<span class="project-issue-status-'. $node->project_issue['sid'] .' project-issue-status-info">'. $link; if ($include_assigned && !empty($username)) { $output .= ' <span class="project-issue-assigned-user">'. t('Assigned to: @username', array('@username' => $username)) .'</span>'; } $output .= '</span>'; return $output; } /** * Implementation of hook_form_filter_tips(). * @ingroup project_issue_filter */ function project_issue_filter_tips($delta, $format, $long = FALSE) { if ($long) { return t("References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically, with the title of the issue appended. The status of the issue is shown on hover. If '@' is appended (e.g. [#1234@]), the user the issue is assigned to will also be printed."); } else { return t('Project issue numbers (ex. [#12345]) turn into links automatically.'); } } /** * Implementation of hook_filter(). * @ingroup project_issue_filter */ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { switch ($op) { case 'list': return array(0 => t('Project Issue to link filter')); case 'description': return t('Converts references to project issues (in the form of [#12345]) into links. Caching should be disabled if node access control modules are used.'); case 'no cache': return FALSE; case 'prepare': return $text; case 'process': $regex = '(?:(?<!\w)\[#\d+(?:-\d+)?(@)?\](?!\w))|<pre>.*?<\/pre>|<code>.*?<\/code>|<a(?:[^>"\']|"[^"]*"|\'[^\']*\')*>.*?<\/a>'; $text = preg_replace_callback("/$regex/", 'project_issue_link_filter_callback', $text); return $text; } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); if (!empty($grants)) { $conflict_grants = TRUE; } $allowed_roles = user_roles(FALSE, 'access project issues'); if (!isset($allowed_roles[DRUPAL_ANONYMOUS_RID])) { $conflict_anonymous = TRUE; } foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if ($conflict_grants && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } +/** + * Implement hook_token_list() (from token.module). + */ +function project_issue_token_list($type) { + if ($type == 'node') { + $tokens['node'] = array( + 'project_issue_pid' => t("The issue's project nid"), + 'project_issue_project_title' => t("The issue's project title"), + 'project_issue_project_title-raw' => t("The issue's project title raw"), + 'project_issue_project_shortname' => t("The issue's project short name"), + 'project_issue_category' => t("The issue's category (bug, feature)"), + 'project_issue_component' => t("The issue's component"), + 'project_issue_priority' => t("The issue's priority"), + 'project_issue_version' => t("The issue's version (if any)"), + 'project_issue_assigned' => t("The name of the user an issue is assigned to"), + 'project_issue_status' => t("The issue's status"), + ); + return $tokens; + } +} + +/** + * Implement hook_token_values() (from token.module). + */ +function project_issue_token_values($type = 'all', $object = NULL) { + if ($type == 'node') { + // Defaults in case it's not an issue or we can't load its parent project. + $values = array( + 'project_issue_pid' => '', + 'project_issue_project_title' => '', + 'project_issue_project_title-raw' => '', + 'project_issue_project_shortname' => '', + 'project_issue_category' => '', + 'project_issue_component' => '', + 'project_issue_priority' => '', + 'project_issue_version' => '', + 'project_issue_assigned' => '', + 'project_issue_status' => '', + ); + if ($object->type == 'project_issue') { + if (!empty($object->project_issue)) { + // If $node->project_issue exists, use it. + $issue = (object)$object->project_issue; + } + else { + $issue = $object; + } + if ($project = node_load($issue->pid)) { + $values['project_issue_pid'] = intval($issue->pid); + $values['project_issue_project_title'] = check_plain($project->title); + $values['project_issue_project_title-raw'] = $project->title; + $values['project_issue_project_shortname'] = check_plain($project->project['uri']); + } + if (module_exists('project_release') && !empty($issue->rid) && $release = node_load($issue->rid)) { + $values['project_issue_version'] = check_plain($release->project_release['version']); + } + if (!empty($issue->assigned)) { + $account = user_load($issue->assigned); + $values['project_issue_assigned'] = check_plain($account->name); + } + $values['project_issue_category'] = project_issue_category($issue->category, FALSE); + $values['project_issue_component'] = check_plain($issue->component); + $values['project_issue_priority'] = project_issue_priority($issue->priority); + $values['project_issue_status'] = check_plain(project_issue_state($issue->sid)); + } + return $values; + } +} + /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } } $variables['class'] .= " project-issue"; } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( 'info' => t('Issue cockpit'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, ); return $form; } elseif ($op == 'save' && $delta == 'issue_cockpit') { variable_set('project_issue_cockpit_categories', $edit['project_issue_cockpit_categories']); // Invalidate the cache for this block since the categories might change. cache_clear_all('project_issue_cockpit_block:', 'cache', TRUE); } elseif ($op == 'view' && ($node = project_get_project_from_menu()) && !empty($node->project_issue['issues']) && node_access('view', $node)) { $cid = 'project_issue_cockpit_block:'. $node->nid; if (($cache = cache_get($cid))) { $block = $cache->data; } else { module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); $block = array( 'subject' => t('Issues for @project', array('@project' => $node->title)), 'content' => theme('project_issue_issue_cockpit', $node), ); cache_set($cid, $block); } return $block; } } /** * Implemenation of hook_project_page_link_alter(). * * Add project_issue-specific links to the array of project links. */ function project_issue_project_page_link_alter(&$links, $node) { // TODO: Assumes "patch" issue status values (http://drupal.org/node/27865). // Prepend a link to the development section to view pending patches. if (!empty($node->project['uri'])) { $patches['pending_patches'] = l(t('View pending patches'), 'project/issues/search/'. $node->project['uri'], array('query' => 'status[]=8&status[]=13&status[]=14')); $links['development']['links'] = $patches + $links['development']['links']; } }
Br3nda/drupal-module-project_issue
cf5d43567e24c05f88edc1e8bbb702d4e7bcbf93
#542150 by dww: Initial patch to make the $node->project_issue namespace consistent. This just ensures all the issue metadata fields are available in $node->project_issue when you edit an existing issue. (Follow-up from #98278, required for #229063).
diff --git a/includes/issue_node_form.inc b/includes/issue_node_form.inc index 8629f56..b7c2a0a 100644 --- a/includes/issue_node_form.inc +++ b/includes/issue_node_form.inc @@ -1,441 +1,477 @@ <?php -// $Id: issue_node_form.inc,v 1.2 2009/07/30 08:07:07 dww Exp $ +// $Id: issue_node_form.inc,v 1.3 2009/08/06 23:31:23 dww Exp $ /** * @file * Code required for the issue node form. */ /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects. $uris = NULL; $projects = project_projects_select_options($uris); if (!$projects) { drupal_set_message(t('You do not have access to any projects.'), 'error'); } elseif (count($projects) == 1) { $project = node_load(key($projects)); drupal_goto('node/add/project-issue/' . $project->project['uri']); } $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => array(t('<none>')) + $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Private helper to implement hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function _project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => filter_xss($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => filter_xss($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if ($releases) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( - '#type' => 'hidden', + '#type' => 'value', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } + else { + // If we're not allowing issue metadata changes, add all of these values + // into the form so they show up in the $node->project_issue array during + // validation and submit, so we're consistent with where they live. + $form['project_issue'] = array('#tree' => TRUE); + $form['project_issue']['pid'] = array( + '#type' => 'value', + '#value' => $node->project_issue['pid'], + ); + if (isset($node->project_issue['rid'])) { + $form['project_issue']['rid'] = array( + '#type' => 'value', + '#value' => $node->project_issue['rid'], + ); + } + $form['project_issue']['component'] = array( + '#type' => 'value', + '#value' => $node->project_issue['component'], + ); + $form['project_issue']['category'] = array( + '#type' => 'value', + '#value' => $node->project_issue['category'], + ); + $form['project_issue']['priority'] = array( + '#type' => 'value', + '#value' => $node->project_issue['priority'], + ); + $form['project_issue']['assigned'] = array( + '#type' => 'value', + '#value' => $node->project_issue['assigned'], + ); + $form['project_issue']['sid'] = array( + '#type' => 'value', + '#value' => $node->project_issue['sid'], + ); + } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Private helper to implement hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function _project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } /** * Private helper to implement hook_insert(). * * @param $node * Object containing form values from the project_issue node form. This is * NOT a fully loaded $node object, so the issue-related values are directly * in $node, not in the $node->project_issue array. */ function _project_issue_insert($node) { // Permanently store the original issue states in a serialized array. This // is a bit yucky, but we need them for proper handling of states workflow. // The current states need to be stored in {project_issues} as well for // query efficiency in issue queue searches, and it seems too messy to add a // bunch of new columns to the {project_issues} table for the original // states. $original_issue_data = new stdClass(); $fields = array( 'pid' => 0, 'rid' => 0, 'component' => '', 'category' => '', 'priority' => 0, 'assigned' => 0, 'sid' => 0, 'title' => '', ); foreach ($fields as $field => $default) { // Some of the incoming data may not have the correct default. if (empty($node->$field)) { $node->$field = $default; } $original_issue_data->$field = $node->$field; } db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); // Invalidate the "Issue cockpit" block cache for this project, since the // new issue will have altered the summary totals. cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); }
Br3nda/drupal-module-project_issue
dc0b22baa6b1b6139b803ecfa17c1dc023aac200
#538986 by hass: Removed t() from schema description strings.
diff --git a/project_issue.install b/project_issue.install index a6f2720..5d91edb 100644 --- a/project_issue.install +++ b/project_issue.install @@ -1,435 +1,435 @@ <?php -// $Id: project_issue.install,v 1.62 2009/05/08 18:54:09 dww Exp $ +// $Id: project_issue.install,v 1.63 2009/08/03 19:16:36 dww Exp $ /** * Implementation of hook_schema(). */ function project_issue_schema() { $schema['project_issue_projects'] = array( - 'description' => t('Table containing per-project issue-related settings.'), + 'description' => 'Table containing per-project issue-related settings.', 'fields' => array( 'nid' => array( - 'description' => t('Primary Key: The {project_projects}.nid of the project.'), + 'description' => 'Primary Key: The {project_projects}.nid of the project.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'issues' => array( - 'description' => t('Boolean value indicating whether or not issue-tracking is enabled for this project.'), + 'description' => 'Boolean value indicating whether or not issue-tracking is enabled for this project.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'components' => array( - 'description' => t('A serialized array defining the components for this project.'), + 'description' => 'A serialized array defining the components for this project.', 'type' => 'text', 'not null' => FALSE, ), 'default_component' => array( - 'description' => t('The default component for new issues of this project, or an empty string if the user needs to select a component.'), + 'description' => 'The default component for new issues of this project, or an empty string if the user needs to select a component.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'help' => array( - 'description' => t('Submission guidelines for issues added to this project.'), + 'description' => 'Submission guidelines for issues added to this project.', 'type' => 'text', 'not null' => FALSE, ), 'mail_digest' => array( - 'description' => t('E-mail address for the weekly critical issues report.'), + 'description' => 'E-mail address for the weekly critical issues report.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy' => array( - 'description' => t('E-mail address to send a copy of all issues to.'), + 'description' => 'E-mail address to send a copy of all issues to.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter' => array( - 'description' => t('A serialized array containing the types of issues to include in the e-mail sent to {project_projects}.mail_copy.'), + 'description' => 'A serialized array containing the types of issues to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter_state' => array( - 'description' => t('A serialized array containing the statuses to include in the e-mail sent to {project_projects}.mail_copy.'), + 'description' => 'A serialized array containing the statuses to include in the e-mail sent to {project_projects}.mail_copy.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_reminder' => array( - 'description' => t('Boolean indicating whether or not users with open issues should receive a monthly reminder.'), + 'description' => 'Boolean indicating whether or not users with open issues should receive a monthly reminder.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('nid'), ); $schema['project_issues'] = array( - 'description' => t('The base table for issues.'), + 'description' => 'The base table for issues.', 'fields' => array( 'nid' => array( - 'description' => t('Primary Key: The {node}.nid of this project_issue node.'), + 'description' => 'Primary Key: The {node}.nid of this project_issue node.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'pid' => array( - 'description' => t('The {project_projects}.nid of the project to which this issue belongs.'), + 'description' => 'The {project_projects}.nid of the project to which this issue belongs.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'category' => array( - 'description' => t('Category of the issue.'), + 'description' => 'Category of the issue.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'component' => array( - 'description' => t('Component of the issue as defined per-project in {project_issue_projects}.components.'), + 'description' => 'Component of the issue as defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( - 'description' => t('The priority for this issue.'), + 'description' => 'The priority for this issue.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'rid' => array( - 'description' => t('The {project_release_nodes}.rid (version identifier) for this issue (only used in conjunction with the project_release module).'), + 'description' => 'The {project_release_nodes}.rid (version identifier) for this issue (only used in conjunction with the project_release module).', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( - 'description' => t('The {users}.uid of the user to which this issue is currently assigned.'), + 'description' => 'The {users}.uid of the user to which this issue is currently assigned.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'sid' => array( - 'description' => t('Current {project_issue_state}.sid of this issue.'), + 'description' => 'Current {project_issue_state}.sid of this issue.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'original_issue_data' => array( - 'description' => t('A serialized object containing the original metadata values that were used when this issue was created.'), + 'description' => 'A serialized object containing the original metadata values that were used when this issue was created.', 'type' => 'text', 'not null' => TRUE, ), 'last_comment_id' => array( - 'description' => t('{comments}.cid of the most recent comment added to the issue. 0 if no comment has been added yet.'), + 'description' => '{comments}.cid of the most recent comment added to the issue. 0 if no comment has been added yet.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'db_lock' => array( - 'description' => t('Row-lock indicator to prevent race conditions when determining sequential comment number (http://drupal.org/node/180866).'), + 'description' => 'Row-lock indicator to prevent race conditions when determining sequential comment number (http://drupal.org/node/180866).', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_issues_pid' => array('pid'), 'project_issues_sid' => array('sid'), 'project_issues_nid_assigned' => array('nid', 'assigned'), ), 'primary key' => array('nid'), ); $schema['project_issue_comments'] = array( - 'description' => t('The base table for comments added to issues.'), + 'description' => 'The base table for comments added to issues.', 'fields' => array( 'nid' => array( - 'description' => t('References {project_issues}.nid, the issue to which this comment was added.'), + 'description' => 'References {project_issues}.nid, the issue to which this comment was added.', 'type' => 'int', 'not null' => FALSE, ), 'cid' => array( - 'description' => t('The {comments}.cid for this comment.'), + 'description' => 'The {comments}.cid for this comment.', 'type' => 'int', 'not null' => FALSE, ), 'rid' => array( - 'description' => t('The {project_release_nodes}.rid (version identifier) after this comment was made (only used in conjunction with the project_release module).'), + 'description' => 'The {project_release_nodes}.rid (version identifier) after this comment was made (only used in conjunction with the project_release module).', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'component' => array( - 'description' => t('Component of the issue after this comment was made. Components are defined per-project in {project_issue_projects}.components.'), + 'description' => 'Component of the issue after this comment was made. Components are defined per-project in {project_issue_projects}.components.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'category' => array( - 'description' => t('Category of this issue after this comment was made.'), + 'description' => 'Category of this issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( - 'description' => t('The priority for this issue after this comment was made.'), + 'description' => 'The priority for this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( - 'description' => t('The {users}.uid of the user to which this issue was assigned after this comment was made.'), + 'description' => 'The {users}.uid of the user to which this issue was assigned after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'sid' => array( - 'description' => t('The {project_issue_state}.sid of this issue after this comment was made.'), + 'description' => 'The {project_issue_state}.sid of this issue after this comment was made.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'pid' => array( - 'description' => t('The {project_projects}.nid of the project to which this issue belongs after this comment was made.'), + 'description' => 'The {project_projects}.nid of the project to which this issue belongs after this comment was made.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'title' => array( - 'description' => t('The title of the issue after this comment was made.'), + 'description' => 'The title of the issue after this comment was made.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, ), 'timestamp' => array( - 'description' => t('Timestamp for this comment.'), + 'description' => 'Timestamp for this comment.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, ), 'comment_number' => array( - 'description' => t('The sequential number for this comment in the issue.'), + 'description' => 'The sequential number for this comment in the issue.', 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'nid_timestamp' => array('nid', 'timestamp'), 'comment_number' => array('comment_number'), ), ); $schema['project_subscriptions'] = array( - 'description' => t('Table keeping track of per-user project_issue subscriptions.'), + 'description' => 'Table keeping track of per-user project_issue subscriptions.', 'fields' => array( 'nid' => array( - 'description' => t('{project_projects}.nid of the project to which the user is subscribed.'), + 'description' => '{project_projects}.nid of the project to which the user is subscribed.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'uid' => array( - 'description' => t('The {users}.uid for this subscriber.'), + 'description' => 'The {users}.uid for this subscriber.', 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'level' => array( - 'description' => t('The type of subscription for the project. Possible values are: 0 = not subscribed, 1 = subscribed to own issues or 2 = subscribed to all issues.'), + 'description' => 'The type of subscription for the project. Possible values are: 0 = not subscribed, 1 = subscribed to own issues or 2 = subscribed to all issues.', 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_subscriptions_nid_uid_level' => array('nid', 'uid', 'level'), ), ); $schema['project_issue_state'] = array( - 'description' => t('Table that holds all possible values for issue statuses.'), + 'description' => 'Table that holds all possible values for issue statuses.', 'fields' => array( 'sid' => array( - 'description' => t('Primary Key: Unique id for this status.'), + 'description' => 'Primary Key: Unique id for this status.', 'type' => 'serial', 'unsigned' => 1, 'not null' => TRUE, ), 'name' => array( - 'description' => t('Display-friendly name for this status.'), + 'description' => 'Display-friendly name for this status.', 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( - 'description' => t('Weight for this status, used when ordering statuses'), + 'description' => 'Weight for this status, used when ordering statuses', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'author_has' => array( - 'description' => t('Boolean indicating whether or not the author of an issue may use this issue status in that issue, regardless of the permissions controlling site-wide use of this status.'), + 'description' => 'Boolean indicating whether or not the author of an issue may use this issue status in that issue, regardless of the permissions controlling site-wide use of this status.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'default_query' => array( - 'description' => t('Boolean indicating whether or not issues with this status are included in default queries.'), + 'description' => 'Boolean indicating whether or not issues with this status are included in default queries.', 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('sid'), ); return $schema; } function project_issue_install() { // We need to check this before we try to create the table, so that // if it already exists, we don't attempt to insert our own values. $project_issue_state_existed = db_table_exists('project_issue_state'); // Create tables. drupal_install_schema('project_issue'); if (!$project_issue_state_existed) { // sid, name, weight, author-can-set, in-default-queries project_issue_init_state(1, 'active', -13, 0, 1); project_issue_init_state(2, 'fixed', 1, 0, 1); project_issue_init_state(3, 'duplicate', 4, 0, 0); project_issue_init_state(4, 'postponed', 6, 0, 1); project_issue_init_state(5, "won't fix", 9, 0, 0); project_issue_init_state(6, 'by design', 11, 0, 0); project_issue_init_state(7, 'closed', 13, 1, 0); project_issue_init_state(8, 'needs review', -8, 0, 0); project_issue_init_state(13, 'needs work', -6, 0, 0); project_issue_init_state(14, 'ready to commit', -2, 0, 0); // Since we're hacking in auto-increment values here, // update the sequence value for Postgres -- ugly but necessary for now. if ($GLOBALS['db_type'] == 'pgsql') { db_query("SELECT setval('project_issue_state_sid_seq', 14)"); } } project_issue_add_missing_projects(); db_query("UPDATE {system} SET weight = 2 WHERE name = 'project_issue'"); // Set up future followups to be read/write. if (module_exists('comment')) { variable_set('comment_project_issue', COMMENT_NODE_READ_WRITE); } // Enable file attachments for followups. variable_set('comment_upload_project_issue', 1); // Enable file attachments for issues. variable_set('upload_project_issue', 1); } /** * Implementation of hook_uninstall(). */ function project_issue_uninstall() { // Remove tables. drupal_uninstall_schema('project_issue'); $variables = array( 'project_issue_default_state', 'project_directory_issues', 'project_reply_to', 'project_issue_digest_last', 'project_issue_cockpit_categories', 'project_issue_digest_interval', 'project_issue_reminder_last', 'project_issue_reminder_interval', 'project_issue_show_comment_signatures', 'project_issue_site_help', 'project_issue_invalid_releases', 'project_issue_followup_user', 'project_issue_hook_cron', ); foreach ($variables as $variable) { variable_del($variable); } } function project_issue_enable() { project_issue_add_missing_projects(); } /** * Initialize a given issue state in the database. */ function project_issue_init_state($sid, $name, $weight, $author, $query) { db_query("INSERT INTO {project_issue_state} (sid, name, weight, author_has, default_query) VALUES (%d, '%s', %d, %d, %d)", $sid, $name, $weight, $author, $query); } /** * Check for existing project nodes that do not have an entry in the * {project_issue_projects} table, and add them. * */ function project_issue_add_missing_projects() { $projects = db_query("SELECT n.nid, pip.nid AS pip_nid FROM {node} n LEFT JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.type = 'project_project' AND pip.nid IS NULL"); while ($project = db_fetch_object($projects)) { db_query('INSERT INTO {project_issue_projects} (nid) VALUES (%d)', $project->nid); } } /** * Remove stale setting that's now provided by views. */ function project_issue_update_6000() { variable_del('project_issues_per_page'); return array(); } /** * Add the 'default_component' field to {project_issue_projects}. */ function project_issue_update_6001() { $ret = array(); db_add_field($ret, 'project_issue_projects', 'default_component', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '')); return $ret; }
Br3nda/drupal-module-project_issue
c207df6f58728fbeb0e4a6b5a8dc4a982bceca92
#537168 by dww: Fixed bug in the "Project issue: Project issue queue" views field that caused the "Label" option (and others) to not appear.
diff --git a/views/handlers/project_issue_handler_field_issue_queue_link.inc b/views/handlers/project_issue_handler_field_issue_queue_link.inc index 646ffa4..e5b7a7a 100644 --- a/views/handlers/project_issue_handler_field_issue_queue_link.inc +++ b/views/handlers/project_issue_handler_field_issue_queue_link.inc @@ -1,49 +1,49 @@ <?php -// $Id: project_issue_handler_field_issue_queue_link.inc,v 1.2 2009/01/31 02:46:17 dww Exp $ +// $Id: project_issue_handler_field_issue_queue_link.inc,v 1.3 2009/08/01 03:43:47 dww Exp $ /** * Field handler to link to the issue queue of a given project. */ class project_issue_handler_field_issue_queue_link extends views_handler_field { /** * Constructor to provide additional field to add. */ function construct() { parent::construct(); $this->additional_fields['nid'] = 'nid'; $this->additional_fields['uri'] = array('table' => 'project_projects', 'field' => 'uri'); } function option_definition() { $options = parent::option_definition(); $options['link_type'] = array('default' => 'issue', 'translatable' => FALSE); return $options; } function options_form(&$form, &$form_state) { - parent::option_definition(); + parent::options_form($form, $form_state); $form['link_type'] = array( '#type' => 'radios', '#title' => t('Type of link to display'), '#options' => $this->get_link_type_options(), '#default_value' => $this->options['link_type'], ); } function get_link_type_options() { return array( 'issues' => t('Link to issue queue'), 'search' => t('Link to advanced search'), ); } function render($values) { $basepath = 'project/issues/'; if ($this->options['link_type'] == 'search') { $basepath .= 'search/'; } return l($values->{$this->field_alias}, $basepath . $values->{$this->aliases['uri']}); } }
Br3nda/drupal-module-project_issue
4a96e58b4cc402f58d9a921d98df693237cb74be
#526438 by Dave Reid: Added logic to skip project selection when creating a new issue if the user only has access to one project.
diff --git a/includes/issue_node_form.inc b/includes/issue_node_form.inc index 079526f..8629f56 100644 --- a/includes/issue_node_form.inc +++ b/includes/issue_node_form.inc @@ -1,437 +1,441 @@ <?php -// $Id: issue_node_form.inc,v 1.1 2009/06/18 03:27:57 dww Exp $ +// $Id: issue_node_form.inc,v 1.2 2009/07/30 08:07:07 dww Exp $ /** * @file * Code required for the issue node form. */ /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects. $uris = NULL; - $projects = array(t('<none>')) + project_projects_select_options($uris); - if (count($projects) == 1) { + $projects = project_projects_select_options($uris); + if (!$projects) { drupal_set_message(t('You do not have access to any projects.'), 'error'); } + elseif (count($projects) == 1) { + $project = node_load(key($projects)); + drupal_goto('node/add/project-issue/' . $project->project['uri']); + } $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), - '#options' => $projects, + '#options' => array(t('<none>')) + $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Private helper to implement hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function _project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => filter_xss($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => filter_xss($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if ($releases) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'hidden', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Private helper to implement hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function _project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } /** * Private helper to implement hook_insert(). * * @param $node * Object containing form values from the project_issue node form. This is * NOT a fully loaded $node object, so the issue-related values are directly * in $node, not in the $node->project_issue array. */ function _project_issue_insert($node) { // Permanently store the original issue states in a serialized array. This // is a bit yucky, but we need them for proper handling of states workflow. // The current states need to be stored in {project_issues} as well for // query efficiency in issue queue searches, and it seems too messy to add a // bunch of new columns to the {project_issues} table for the original // states. $original_issue_data = new stdClass(); $fields = array( 'pid' => 0, 'rid' => 0, 'component' => '', 'category' => '', 'priority' => 0, 'assigned' => 0, 'sid' => 0, 'title' => '', ); foreach ($fields as $field => $default) { // Some of the incoming data may not have the correct default. if (empty($node->$field)) { $node->$field = $default; } $original_issue_data->$field = $node->$field; } db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); // Invalidate the "Issue cockpit" block cache for this project, since the // new issue will have altered the summary totals. cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); }
Br3nda/drupal-module-project_issue
d7d342e774fd6c5bfc9036ac68d7c6f04d60eef1
#494424 by Pasqualle: Hide li background images on the issue summary links.
diff --git a/project_issue.css b/project_issue.css index fe8f7f4..149fe20 100644 --- a/project_issue.css +++ b/project_issue.css @@ -1,215 +1,216 @@ -/* $Id: project_issue.css,v 1.25 2009/02/05 06:46:47 dww Exp $ */ +/* $Id: project_issue.css,v 1.26 2009/06/18 04:54:18 dww Exp $ */ /* Summary content */ #project-issue-summary-table { float: left; } #project-issue-summary-links { float: right; } #project-issue-summary-links li { + background: none; list-style-type: none; margin-left: 0; padding-left: 0; } /* Viewing issue nodes */ .project-issue .header { font-weight: bold; padding-top: 0.5em; } .project-issue .summary table { border-collapse: collapse; width: auto; border: 1px; border-style: solid; border-color: #eee; } .project-issue .summary table td { color: #333; background-color: transparent; font-size: 90%; padding: 0em 1em; border: 0; } .project-issue tbody { border: 0; } .project-issue .summary table tr { border: 0; } /* Issue node and comment followup form UI */ .project-issue .node-form div.inline-options .form-item { float: left; padding-right: 0.8em; margin: 0.05em 0.1em; } .project-issue .node-form div.inline-options { overflow: hidden; /* Gets rid of ugly scrollbars on comments */ } .project-issue .node-form div.inline-options:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .project-issue .node-form fieldset { display: inline-block; /* Fixes fieldset display problems in Safari 2 */ width: 97%; } .project-issue .node-form #edit-pid, .project-issue .node-form #edit-project-info-pid { width: 225px; } /* "My Projects" table UI */ table.projects { width: 100%; margin-bottom: 3em; } table.projects .project-name { width: 24%; } table.projects .project-issue-updated { width: 15%; } table.projects .project-issues { width: 11%; text-align: center; } table.projects .project-issue-links { width: 28%; padding-left: 0.4em; padding-right: 0.4em; text-align: center; } table.projects .project-project-links { width: 22%; text-align: center; } table.projects .project-project-links a { white-space:nowrap; } /* Issue query bar UI */ .project-issue .quick-search #edit-projects, .project-issue .quick-search #edit-states { width: 150px; } /* Views based issue query bar UI */ .view-project-issues-project .form-item #edit-filter1, .view-project-issues-project-search .form-item #edit-filter1, #edit-filter2{ width:150px; } /* Views based issue advanced search filters */ .view-project-issues-project-search #views-filters { width: 100%; overflow: auto; } .project-issue .quick-search tr td .form-item, .project-issue .quick-search tr td input { margin: 0; padding: 0; } .project-issue .quick-search tr td { vertical-align: bottom; } /* Issue links from the [#12345] filter. */ .project-issue-status-info a, .project-issue-status-info .project-issue-assigned-user { background-color: #cdcdcd; -moz-border-radius: 4px; /* Mozilla based browsers */ -webkit-border-radius: 4px; /* Webkit based browsers */ border-radius: 4px; /* CSS 3 standard */ padding: 2px 4px; } .project-issue-status-info .project-issue-assigned-user { white-space: nowrap; } /* Coloring based on issue status (issue query results and [#12345] links). */ .project-issue tr.state-1, .project-issue-status-1 a { background-color: #fff; } .project-issue tr.state-1 td.active { background-color: #e1e7eb; } .project-issue tr.state-2, .project-issue-status-2 a { background-color: #c0ffc0; } .project-issue tr.state-2 td.active { background-color: #cec; } .project-issue tr.state-3, .project-issue-status-3 a, .project-issue tr.state-4, .project-issue-status-4 a, .project-issue tr.state-5, .project-issue-status-5 a, .project-issue tr.state-6, .project-issue-status-6 a { background-color: #ddf; } .project-issue tr.state-3 td.active, .project-issue tr.state-4 td.active, .project-issue tr.state-5 td.active, .project-issue tr.state-6 td.active { background-color: #cce; } .project-issue tr.state-7, .project-issue-status-7 a { background-color: #ffc9c9; } .project-issue tr.state-7 td.active { background-color: #eeb9b9; } .project-issue tr.state-8, .project-issue-status-8 a { background-color: #ffd; } .project-issue tr.state-8 td.active { background-color: #eed; } .project-issue tr.state-13, .project-issue-status-13 a { background-color: #ffe7dd; } .project-issue tr.state-13 td.active { background-color: #eed7cc; } .project-issue tr.state-14, .project-issue-status-14 a { background-color: #e7ffdd; } .project-issue tr.state-14 td.active { background-color: #d7eecc; } /* Issue statistics page */ .project-issue-numeric { text-align: center; } .project-issue-numeric-light { text-align: center; color: #999; } .project-issue-statistics-overview-table { overflow: auto; } /* Automatic issue links */ .project-issue-status-2, .project-issue-status-3, .project-issue-status-5, .project-issue-status-6, .project-issue-status-7 { text-decoration: line-through; } .wrapper-throbber { /* Apparently there's no safe way to do this in CSS, so this could be broken for sites that install in subdirectories. */ background: url(/misc/throbber.gif) no-repeat right -18px; width: 20px; height: 18px; margin-top: 20px; float: left; }
Br3nda/drupal-module-project_issue
c01d18667adf65ff661cc8132c6ea5af4b8f9d5a
#494646 by Pasqualle: Fixed incorrect views theme template path.
diff --git a/views/project_issue.views.inc b/views/project_issue.views.inc index 0e593a6..4765a95 100644 --- a/views/project_issue.views.inc +++ b/views/project_issue.views.inc @@ -1,258 +1,258 @@ <?php -// $Id: project_issue.views.inc,v 1.8 2009/03/23 17:24:53 dww Exp $ +// $Id: project_issue.views.inc,v 1.9 2009/06/18 03:48:53 dww Exp $ /** * @file * Provides support for Views integration. */ /** * Implementation of hook_views_data(). */ function project_issue_views_data() { $data = array(); $data['project_issues']['table']['group'] = t('Project issue'); $data['project_issues']['table']['join'] = array( 'node' => array( 'type' => 'INNER', 'left_field' => 'nid', 'field' => 'nid', ), 'project_projects' => array( 'type' => 'INNER', 'left_table' => 'project_projects', 'left_field' => 'nid', 'field' => 'pid', ), 'project_release_nodes' => array( 'type' => 'INNER', 'left_table' => 'project_release_nodes', 'left_field' => 'nid', 'field' => 'rid', ), ); $data['project_issues']['pid'] = array( 'title' => t('Project'), 'help' => t('The project an issue is tied to.'), 'field' => array( 'handler' => 'views_handler_field_node', 'click sortable' => TRUE, ), // Information for accepting a pid as an argument 'argument' => array( 'handler' => 'views_handler_argument_node_nid', 'name field' => 'title', 'numeric' => TRUE, 'validate type' => 'nid', ), // Information for accepting a pid as a filter 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_project', ), 'relationship' => array( 'base' => 'node', 'handler' => 'views_handler_relationship', 'label' => t('Project node'), ), ); $data['node']['project_issue_queue'] = array( 'title' => t('Project issue queue'), 'help' => t("Displays a link to the issue queue for the project this issue is assigned to."), 'field' => array( 'field' => 'title', 'group' => t('Project issue'), 'handler' => 'project_issue_handler_field_issue_queue_link', 'click sortable' => TRUE, ), ); $data['project_issues']['category'] = array( 'title' => t('Category'), 'help' => t("The issue's category (bug, task, feature, etc)."), 'field' => array( 'handler' => 'project_issue_handler_field_issue_category', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_category', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); $data['project_issues']['component'] = array( 'title' => t('Component'), 'help' => t("The issue's component (the options are controlled per-project)."), 'field' => array( 'handler' => 'views_handler_field_node', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_component', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); $data['project_issues']['priority'] = array( 'title' => t('Priority'), 'help' => t("The issue's priority (critical, normal, minor)."), 'field' => array( 'handler' => 'project_issue_handler_field_issue_priority', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', 'help' => t("Sort by the issue's priority."), ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_priority', 'help' => t("Filter on each issue's status."), ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); $data['project_issues']['rid'] = array( 'title' => t('Version'), 'help' => t('The version associated with the issue (depends on project_release.module).'), 'field' => array( 'handler' => 'views_handler_field_node', 'click sortable' => TRUE, ), 'argument' => array( 'handler' => 'views_handler_argument_node_nid', 'name field' => 'title', 'numeric' => TRUE, 'validate type' => 'nid', ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_version', ), 'relationship' => array( 'base' => 'node', 'handler' => 'views_handler_relationship', 'label' => t('Project release node'), ), ); $data['project_issues']['assigned'] = array( 'title' => t('Assigned'), 'help' => t('The user the issue is assigned to.'), 'relationship' => array( 'base' => 'users', 'handler' => 'views_handler_relationship', 'label' => t('Assigned user'), ), ); $data['project_issues']['sid'] = array( 'title' => t('Status'), 'help' => t('The status of each issue'), 'field' => array( 'handler' => 'project_issue_handler_field_issue_status', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', 'help' => t("Sort by the issue's status."), ), 'filter' => array( 'handler' => 'project_issue_handler_filter_issue_status', 'help' => t("Filter on each issue's status."), ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); return $data; } /** * Implementation of hook_views_handlers(). */ function project_issue_views_handlers() { return array( 'info' => array( 'path' => drupal_get_path('module', 'project_issue') .'/views/handlers', ), 'handlers' => array( 'project_issue_handler_field_issue_category' => array( 'parent' => 'views_handler_field', ), 'project_issue_handler_field_issue_priority' => array( 'parent' => 'views_handler_field', ), 'project_issue_handler_field_issue_queue_link' => array( 'parent' => 'views_handler_field', ), 'project_issue_handler_field_issue_status' => array( 'parent' => 'views_handler_field', ), 'project_issue_handler_filter_issue_category' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_component' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_priority' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_project' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_status' => array( 'parent' => 'views_handler_filter_in_operator', ), 'project_issue_handler_filter_issue_version' => array( 'parent' => 'views_handler_filter_in_operator', ), ), ); } function project_issue_views_plugins() { $path = drupal_get_path('module', 'project_issue') . '/views/plugins'; $views_path = drupal_get_path('module', 'views'); return array( 'style' => array( 'project_issue_table' => array( 'title' => t('Project issue table'), 'help' => t('Table with colored rows depending on issue status.'), 'handler' => 'project_issue_table_plugin_style', 'parent' => 'table', 'path' => $path, 'theme' => 'views_view_table', 'theme file' => 'theme.inc', - 'theme path' => "$views_path/views/theme", + 'theme path' => "$views_path/theme", 'uses row plugin' => FALSE, 'uses fields' => TRUE, 'uses options' => TRUE, 'type' => 'normal', ), ), 'access' => array( 'project_issue_access_per_user_queue' => array( 'title' => t('View per-user issue queues'), 'help' => t('Access will be granted if the user is requested in the URL or for users viewing their own per-user issue queues.'), 'handler' => 'project_issue_plugin_access_per_user_queue', 'uses options' => TRUE, 'path' => $path, ), ), ); }
Br3nda/drupal-module-project_issue
fcd9871fbf43eaa27f79e6bf2977514cd3a3bf95
#460248 by dww: Split default views into separate files. project_issue_views_default_views() now auto-discovers any files in the views/default_views subdirectory that end in ".view.php" and exposes those as default views.
diff --git a/views/default_views/project_issue_all_projects.view.php b/views/default_views/project_issue_all_projects.view.php new file mode 100644 index 0000000..382f43b --- /dev/null +++ b/views/default_views/project_issue_all_projects.view.php @@ -0,0 +1,432 @@ +<?php +// $Id: project_issue_all_projects.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ + +/** + * @file + * Issue queue across all projects. + */ + +$view = new view; +$view->name = 'project_issue_all_projects'; +$view->description = 'Project issues for all projects'; +$view->tag = 'Project issue'; +$view->view_php = ''; +$view->base_table = 'node'; +$view->is_cacheable = FALSE; +$view->api_version = 2; +$view->disabled = FALSE; +$handler = $view->new_display('default', 'Defaults', 'default'); +$handler->override_option('relationships', array( + 'assigned' => array( + 'label' => 'Assigned user', + 'required' => 1, + 'id' => 'assigned', + 'table' => 'project_issues', + 'field' => 'assigned', + 'relationship' => 'none', + ), + 'rid' => array( + 'label' => 'Version', + 'required' => 0, + 'id' => 'rid', + 'table' => 'project_issues', + 'field' => 'rid', + 'relationship' => 'none', + ), + 'pid' => array( + 'label' => 'Project node', + 'required' => 1, + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + ), +)); +$fields = array( + 'project_issue_queue' => array( + 'label' => 'Project', + 'link_type' => 'issues', + 'exclude' => 0, + 'id' => 'project_issue_queue', + 'table' => 'node', + 'field' => 'project_issue_queue', + 'relationship' => 'pid', + ), + 'title' => array( + 'label' => 'Summary', + 'link_to_node' => 1, + 'exclude' => 0, + 'id' => 'title', + 'table' => 'node', + 'field' => 'title', + 'relationship' => 'none', + ), + 'timestamp' => array( + 'label' => '', + 'alter' => array(), + 'link_to_node' => 0, + 'comments' => 0, + 'exclude' => 0, + 'id' => 'timestamp', + 'table' => 'history_user', + 'field' => 'timestamp', + 'relationship' => 'none', + ), + 'sid' => array( + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + ), + 'priority' => array( + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + ), + 'category' => array( + 'label' => 'Category', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), + 'comment_count' => array( + 'label' => 'Replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'exclude' => 0, + 'id' => 'comment_count', + 'table' => 'node_comment_statistics', + 'field' => 'comment_count', + 'relationship' => 'none', + ), + 'new_comments' => array( + 'label' => 'New replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => ' new', + 'link_to_comment' => 1, + 'no_empty' => 1, + 'exclude' => 0, + 'id' => 'new_comments', + 'table' => 'node', + 'field' => 'new_comments', + 'relationship' => 'none', + ), + 'last_comment_timestamp' => array( + 'label' => 'Last updated', + 'date_format' => 'raw time ago', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', + ), + 'name' => array( + 'label' => 'Assigned to', + 'link_to_user' => 1, + 'overwrite_anonymous' => 1, + 'anonymous_text' => '', + 'exclude' => 0, + 'id' => 'name', + 'table' => 'users', + 'field' => 'name', + 'relationship' => 'assigned', + ), +); +if (module_exists('search')) { + $fields['score'] = array( + 'label' => 'Score', + 'alter' => array(), + 'set_precision' => 1, + 'precision' => '3', + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'alternate_sort' => 'last_comment_timestamp', + 'alternate_order' => 'desc', + 'exclude' => 0, + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('fields', $fields); +$sorts['last_comment_timestamp'] = array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', +); +if (module_exists('search')) { + $sorts['score'] = array( + 'order' => 'DESC', + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('sorts', $sorts); +$filters = array( + 'status_extra' => array( + 'operator' => '=', + 'value' => '', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'status_extra', + 'table' => 'node', + 'field' => 'status_extra', + 'relationship' => 'none', + ), + 'pid' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'operator' => 'pid_op', + 'label' => 'Project', + 'use_operator' => 0, + 'identifier' => 'projects', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'widget' => 'textfield', + 'project_source' => 'all', + 'project_uid_argument' => '', + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + 'relationship' => 'none', + ), + 'sid' => array( + 'operator' => 'in', + 'value' => array( + 'Open' => 'Open', + ), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'sid_op', + 'identifier' => 'status', + 'label' => 'Status', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + 'relationship' => 'none', + ), + 'priority' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'priority_op', + 'identifier' => 'priorities', + 'label' => 'Priority', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + 'relationship' => 'none', + ), + 'category' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'category_op', + 'identifier' => 'categories', + 'label' => 'Category', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), +); +if (module_exists('search')) { + $search_filter['keys'] = array( + 'operator' => 'optional', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'keys_op', + 'identifier' => 'text', + 'label' => 'Search for', + 'optional' => 1, + 'remember' => 0, + ), + 'id' => 'keys', + 'table' => 'search_index', + 'field' => 'keys', + 'relationship' => 'none', + ); + $filters = $search_filter + $filters; +} +$handler->override_option('filters', $filters); +$handler->override_option('access', array( + 'type' => 'none', +)); +$handler->override_option('title', 'Issues for all projects'); +$handler->override_option('empty', 'No issues match your criteria.'); +$handler->override_option('empty_format', '1'); +$handler->override_option('items_per_page', 50); +$handler->override_option('use_pager', '1'); +$handler->override_option('style_plugin', 'project_issue_table'); +$handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 1, + 'order' => 'desc', + 'columns' => array( + 'project_issue_queue' => 'project_issue_queue', + 'title' => 'title', + 'timestamp' => 'title', + 'sid' => 'sid', + 'priority' => 'priority', + 'category' => 'category', + 'comment_count' => 'comment_count', + 'new_comments' => 'comment_count', + 'last_comment_timestamp' => 'last_comment_timestamp', + 'name' => 'name', + 'score' => 'score', + ), + 'info' => array( + 'project_issue_queue' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'title' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'timestamp' => array( + 'separator' => '', + ), + 'sid' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'priority' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'category' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'comment_count' => array( + 'sortable' => 1, + 'separator' => '<br />', + ), + 'new_comments' => array( + 'separator' => '', + ), + 'last_comment_timestamp' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'score' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', +)); +$handler = $view->new_display('page', 'Page', 'page_1'); +$handler->override_option('path', 'project/issues'); +$handler->override_option('menu', array( + 'type' => 'normal', + 'title' => 'Issues', + 'description' => '', + 'weight' => '0', + 'name' => 'navigation', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler = $view->new_display('feed', 'Feed', 'feed_1'); +$handler->override_option('sorts', array( + 'last_comment_timestamp' => array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'override' => array( + 'button' => 'Use default', + ), + 'relationship' => 'none', + ), +)); +$handler->override_option('style_plugin', 'rss'); +$handler->override_option('style_options', array( + 'mission_description' => FALSE, + 'description' => '', +)); +$handler->override_option('row_plugin', 'node_rss'); +$handler->override_option('path', 'project/issues/rss'); +$handler->override_option('menu', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => '', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler->override_option('displays', array( + 'page_1' => 'page_1', + 'default' => 0, +)); +$handler->override_option('sitename_title', FALSE); diff --git a/views/default_views/project_issue_project.view.php b/views/default_views/project_issue_project.view.php new file mode 100644 index 0000000..908f0fb --- /dev/null +++ b/views/default_views/project_issue_project.view.php @@ -0,0 +1,581 @@ +<?php +// $Id: project_issue_project.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ + +/** + * @file + * Issue queue for a specific project. + */ + +$view = new view; +$view->name = 'project_issue_project'; +$view->description = 'Project issues by project'; +$view->tag = 'Project issue'; +$view->view_php = ''; +$view->base_table = 'node'; +$view->is_cacheable = FALSE; +$view->api_version = 2; +$view->disabled = FALSE; +$handler = $view->new_display('default', 'Defaults', 'default'); +$handler->override_option('relationships', array( + 'assigned' => array( + 'label' => 'Assigned user', + 'required' => 1, + 'id' => 'assigned', + 'table' => 'project_issues', + 'field' => 'assigned', + 'relationship' => 'none', + ), + 'rid' => array( + 'label' => 'Version', + 'required' => 0, + 'id' => 'rid', + 'table' => 'project_issues', + 'field' => 'rid', + 'relationship' => 'none', + ), +)); +$fields = array( + 'title' => array( + 'label' => 'Summary', + 'link_to_node' => 1, + 'exclude' => 0, + 'id' => 'title', + 'table' => 'node', + 'field' => 'title', + 'relationship' => 'none', + ), + 'timestamp' => array( + 'label' => '', + 'alter' => array(), + 'link_to_node' => 0, + 'comments' => 0, + 'exclude' => 0, + 'id' => 'timestamp', + 'table' => 'history_user', + 'field' => 'timestamp', + 'relationship' => 'none', + ), + 'sid' => array( + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + ), + 'priority' => array( + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + ), + 'category' => array( + 'label' => 'Category', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), + 'version' => array( + 'label' => 'Version', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'version', + 'table' => 'project_release_nodes', + 'field' => 'version', + 'relationship' => 'rid', + ), + 'component' => array( + 'label' => 'Component', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'component', + 'table' => 'project_issues', + 'field' => 'component', + 'relationship' => 'none', + ), + 'comment_count' => array( + 'label' => 'Replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'exclude' => 0, + 'id' => 'comment_count', + 'table' => 'node_comment_statistics', + 'field' => 'comment_count', + 'relationship' => 'none', + ), + 'new_comments' => array( + 'label' => 'New replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => ' new', + 'link_to_comment' => 1, + 'no_empty' => 1, + 'exclude' => 0, + 'id' => 'new_comments', + 'table' => 'node', + 'field' => 'new_comments', + 'relationship' => 'none', + ), + 'last_comment_timestamp' => array( + 'label' => 'Last updated', + 'date_format' => 'raw time ago', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', + ), + 'name' => array( + 'label' => 'Assigned to', + 'link_to_user' => 1, + 'overwrite_anonymous' => 1, + 'anonymous_text' => '', + 'exclude' => 0, + 'id' => 'name', + 'table' => 'users', + 'field' => 'name', + 'relationship' => 'assigned', + ), +); +if (module_exists('search')) { + $fields['score'] = array( + 'label' => 'Score', + 'alter' => array(), + 'set_precision' => 1, + 'precision' => '3', + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'alternate_sort' => 'last_comment_timestamp', + 'alternate_order' => 'desc', + 'exclude' => 0, + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('fields', $fields); +$handler->override_option('arguments', array( + 'pid' => array( + 'default_action' => 'not found', + 'style_plugin' => 'default_summary', + 'style_options' => array(), + 'wildcard' => '', + 'wildcard_substitution' => '', + 'title' => 'Issues for %1', + 'default_argument_type' => 'fixed', + 'default_argument' => '', + 'validate_type' => 'project_nid', + 'validate_fail' => 'not found', + 'break_phrase' => 0, + 'not' => 0, + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + 'relationship' => 'none', + 'default_options_div_prefix' => '', + 'default_argument_user' => 0, + 'default_argument_fixed' => '', + 'default_argument_php' => '', + ), +)); +$sorts['last_comment_timestamp'] = array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', +); +if (module_exists('search')) { + $sorts['score'] = array( + 'order' => 'DESC', + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('sorts', $sorts); +$filters = array( + 'status_extra' => array( + 'operator' => '=', + 'value' => '', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'status_extra', + 'table' => 'node', + 'field' => 'status_extra', + 'relationship' => 'none', + ), + 'sid' => array( + 'operator' => 'in', + 'value' => array( + 'Open' => 'Open', + ), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'sid_op', + 'identifier' => 'status', + 'label' => 'Status', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + 'relationship' => 'none', + ), + 'priority' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'priority_op', + 'identifier' => 'priorities', + 'label' => 'Priority', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + 'relationship' => 'none', + ), + 'category' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'category_op', + 'identifier' => 'categories', + 'label' => 'Category', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), + 'rid' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'rid_op', + 'identifier' => 'version', + 'label' => 'Version', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'rid', + 'table' => 'project_issues', + 'field' => 'rid', + 'relationship' => 'none', + ), + 'component' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'component_op', + 'identifier' => 'component', + 'label' => 'Component', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'component', + 'table' => 'project_issues', + 'field' => 'component', + 'relationship' => 'none', + ), +); +if (module_exists('search')) { + $search_filter['keys'] = array( + 'operator' => 'optional', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'keys_op', + 'identifier' => 'text', + 'label' => 'Search for', + 'optional' => 1, + 'remember' => 0, + ), + 'id' => 'keys', + 'table' => 'search_index', + 'field' => 'keys', + 'relationship' => 'none', + ); + $filters = $search_filter + $filters; +} +$handler->override_option('filters', $filters); +$handler->override_option('access', array( + 'type' => 'none', +)); +$handler->override_option('title', 'Issues by project'); +$handler->override_option('empty', 'No issues match your criteria.'); +$handler->override_option('empty_format', '1'); +$handler->override_option('items_per_page', 50); +$handler->override_option('use_pager', '1'); +$handler->override_option('style_plugin', 'project_issue_table'); +$handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 1, + 'order' => 'desc', + 'columns' => array( + 'title' => 'title', + 'timestamp' => 'title', + 'sid' => 'sid', + 'priority' => 'priority', + 'category' => 'category', + 'version' => 'version', + 'component' => 'component', + 'comment_count' => 'comment_count', + 'new_comments' => 'comment_count', + 'last_comment_timestamp' => 'last_comment_timestamp', + 'name' => 'name', + 'score' => 'score', + ), + 'info' => array( + 'title' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'timestamp' => array( + 'separator' => '', + ), + 'sid' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'priority' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'category' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'version' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'component' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'comment_count' => array( + 'sortable' => 1, + 'separator' => '<br />', + ), + 'new_comments' => array( + 'separator' => '', + ), + 'last_comment_timestamp' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'score' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', +)); +$handler = $view->new_display('page', 'Page', 'page_1'); +$handler->override_option('path', 'project/issues/%'); +$handler->override_option('menu', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => '0', + 'name' => '', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler = $view->new_display('feed', 'Feed', 'feed_1'); +$handler->override_option('sorts', array( + 'last_comment_timestamp' => array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'override' => array( + 'button' => 'Use default', + ), + 'relationship' => 'none', + ), +)); +$handler->override_option('style_plugin', 'rss'); +$handler->override_option('style_options', array( + 'mission_description' => FALSE, + 'description' => '', +)); +$handler->override_option('row_plugin', 'node_rss'); +$handler->override_option('path', 'project/issues/rss/%'); +$handler->override_option('menu', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => '', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler->override_option('displays', array( + 'page_1' => 'page_1', + 'default' => 0, +)); +$handler->override_option('sitename_title', FALSE); +$handler = $view->new_display('block', 'Block', 'block_1'); +$handler->override_option('title', 'Recent issues'); +$handler->override_option('relationships', array()); +$handler->override_option('fields', array( + 'title' => array( + 'label' => '', + 'alter' => array(), + 'link_to_node' => 1, + 'exclude' => 0, + 'id' => 'title', + 'table' => 'node', + 'field' => 'title', + 'relationship' => 'none', + 'override' => array( + 'button' => 'Use default', + ), + ), + 'timestamp' => array( + 'label' => '', + 'alter' => array(), + 'link_to_node' => 0, + 'comments' => 0, + 'exclude' => 0, + 'id' => 'timestamp', + 'table' => 'history_user', + 'field' => 'timestamp', + 'relationship' => 'none', + ), +)); +$handler->override_option('sorts', array( + 'last_comment_timestamp' => array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', + ), +)); +$handler->override_option('arguments', array( + 'pid' => array( + 'default_action' => 'default', + 'style_plugin' => 'default_summary', + 'style_options' => array(), + 'wildcard' => '', + 'wildcard_substitution' => '', + 'default_argument_type' => 'node', + 'default_argument' => '', + 'validate_type' => 'project_nid', + 'validate_fail' => 'not found', + 'break_phrase' => 0, + 'not' => 0, + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + 'relationship' => 'none', + ), +)); +$handler->override_option('filters', array( + 'status_extra' => array( + 'operator' => '=', + 'value' => '', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array(), + 'id' => 'status_extra', + 'table' => 'node', + 'field' => 'status_extra', + 'relationship' => 'none', + ), + 'sid' => array( + 'operator' => 'in', + 'value' => array( + 'Open' => 'Open', + ), + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array(), + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + 'relationship' => 'none', + ), +)); +$handler->override_option('items_per_page', 5); +$handler->override_option('use_pager', '0'); +$handler->override_option('style_plugin', 'list'); +$handler->override_option('style_options', array( + 'grouping' => '', + 'type' => 'ul', +)); +$handler->override_option('row_options', array( + 'inline' => array( + 'title' => 'title', + 'timestamp' => 'timestamp', + ), + 'separator' => ' ', +)); +$handler->override_option('block_description', 'Project: recent issues'); +$handler->override_option('block_caching', -1); + diff --git a/views/default_views/project_issue_search_all.view.php b/views/default_views/project_issue_search_all.view.php new file mode 100644 index 0000000..26053c7 --- /dev/null +++ b/views/default_views/project_issue_search_all.view.php @@ -0,0 +1,503 @@ +<?php +// $Id: project_issue_search_all.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ + +/** + * @file + * Advanced issue search for all projects. + */ + +$view = new view; +$view->name = 'project_issue_search_all'; +$view->description = 'Project issue advanced search for all projects'; +$view->tag = 'Project issue'; +$view->view_php = ''; +$view->base_table = 'node'; +$view->is_cacheable = FALSE; +$view->api_version = 2; +$view->disabled = FALSE; +$handler = $view->new_display('default', 'Defaults', 'default'); +$handler->override_option('relationships', array( + 'assigned' => array( + 'label' => 'Assigned user', + 'required' => 1, + 'id' => 'assigned', + 'table' => 'project_issues', + 'field' => 'assigned', + 'relationship' => 'none', + ), + 'rid' => array( + 'label' => 'Version', + 'required' => 0, + 'id' => 'rid', + 'table' => 'project_issues', + 'field' => 'rid', + 'relationship' => 'none', + ), + 'pid' => array( + 'label' => 'Project node', + 'required' => 1, + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + ), +)); +$fields = array( + 'project_issue_queue' => array( + 'label' => 'Project', + 'link_type' => 'search', + 'exclude' => 0, + 'id' => 'project_issue_queue', + 'table' => 'node', + 'field' => 'project_issue_queue', + 'relationship' => 'pid', + ), + 'title' => array( + 'label' => 'Summary', + 'link_to_node' => 1, + 'exclude' => 0, + 'id' => 'title', + 'table' => 'node', + 'field' => 'title', + 'relationship' => 'none', + ), + 'timestamp' => array( + 'label' => '', + 'alter' => array(), + 'link_to_node' => 0, + 'comments' => 0, + 'exclude' => 0, + 'id' => 'timestamp', + 'table' => 'history_user', + 'field' => 'timestamp', + 'relationship' => 'none', + ), + 'sid' => array( + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + ), + 'priority' => array( + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + ), + 'category' => array( + 'label' => 'Category', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), + 'version' => array( + 'label' => 'Version', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'version', + 'table' => 'project_release_nodes', + 'field' => 'version', + 'relationship' => 'rid', + ), + 'comment_count' => array( + 'label' => 'Replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'exclude' => 0, + 'id' => 'comment_count', + 'table' => 'node_comment_statistics', + 'field' => 'comment_count', + 'relationship' => 'none', + ), + 'new_comments' => array( + 'label' => 'New replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => ' new', + 'link_to_comment' => 1, + 'no_empty' => 1, + 'exclude' => 0, + 'id' => 'new_comments', + 'table' => 'node', + 'field' => 'new_comments', + 'relationship' => 'none', + ), + 'last_comment_timestamp' => array( + 'label' => 'Last updated', + 'date_format' => 'raw time ago', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', + ), + 'name' => array( + 'label' => 'Assigned to', + 'link_to_user' => 1, + 'overwrite_anonymous' => 1, + 'anonymous_text' => '', + 'exclude' => 0, + 'id' => 'name', + 'table' => 'users', + 'field' => 'name', + 'relationship' => 'assigned', + ), +); +if (module_exists('search')) { + $fields['score'] = array( + 'label' => 'Score', + 'alter' => array(), + 'set_precision' => 1, + 'precision' => '3', + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'alternate_sort' => 'last_comment_timestamp', + 'alternate_order' => 'desc', + 'exclude' => 0, + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('fields', $fields); +$sorts['last_comment_timestamp'] = array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', +); +if (module_exists('search')) { + $sorts['score'] = array( + 'order' => 'DESC', + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('sorts', $sorts); +$filters = array( + 'status_extra' => array( + 'operator' => '=', + 'value' => '', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'status_extra', + 'table' => 'node', + 'field' => 'status_extra', + 'relationship' => 'none', + ), + 'pid' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'operator' => 'pid_op', + 'label' => 'Project', + 'use_operator' => 0, + 'identifier' => 'projects', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'widget' => 'textfield', + 'project_source' => 'all', + 'project_uid_argument' => '', + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + 'relationship' => 'none', + ), + 'uid' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'uid_op', + 'identifier' => 'assigned', + 'label' => 'Assigned', + 'optional' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'uid', + 'table' => 'users', + 'field' => 'uid', + 'relationship' => 'assigned', + ), + 'uid_1' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'uid_1_op', + 'identifier' => 'submitted', + 'label' => 'Submitted by', + 'optional' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'uid_1', + 'table' => 'users', + 'field' => 'uid', + 'relationship' => 'none', + ), + 'uid_touch' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'uid_touch_op', + 'identifier' => 'participant', + 'label' => 'Participant', + 'optional' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'uid_touch', + 'table' => 'node', + 'field' => 'uid_touch', + 'relationship' => 'none', + ), + 'sid' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'sid_op', + 'identifier' => 'status', + 'label' => 'Status', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + 'relationship' => 'none', + ), + 'priority' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'priority_op', + 'identifier' => 'priorities', + 'label' => 'Priority', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + 'relationship' => 'none', + ), + 'category' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'category_op', + 'identifier' => 'categories', + 'label' => 'Category', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), +); +if (module_exists('search')) { + $search_filter['keys'] = array( + 'operator' => 'optional', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'keys_op', + 'identifier' => 'text', + 'label' => 'Search for', + 'optional' => 1, + 'remember' => 0, + ), + 'id' => 'keys', + 'table' => 'search_index', + 'field' => 'keys', + 'relationship' => 'none', + ); + $filters = $search_filter + $filters; +} +_project_issue_views_add_taxonomy_filters($filters); +$handler->override_option('filters', $filters); +$handler->override_option('access', array( + 'type' => 'none', +)); +$handler->override_option('title', 'Search issues for all projects'); +$handler->override_option('empty', 'No issues match your criteria.'); +$handler->override_option('empty_format', '1'); +$handler->override_option('items_per_page', 50); +$handler->override_option('use_pager', '1'); +$handler->override_option('style_plugin', 'project_issue_table'); +$handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 1, + 'order' => 'desc', + 'columns' => array( + 'project_issue_queue' => 'project_issue_queue', + 'title' => 'title', + 'timestamp' => 'title', + 'sid' => 'sid', + 'priority' => 'priority', + 'category' => 'category', + 'version' => 'version', + 'comment_count' => 'comment_count', + 'new_comments' => 'comment_count', + 'last_comment_timestamp' => 'last_comment_timestamp', + 'name' => 'name', + 'score' => 'score', + ), + 'info' => array( + 'project_issue_queue' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'title' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'timestamp' => array( + 'separator' => '', + ), + 'sid' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'priority' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'category' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'version' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'comment_count' => array( + 'sortable' => 1, + 'separator' => '<br />', + ), + 'new_comments' => array( + 'separator' => '', + ), + 'last_comment_timestamp' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'score' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', +)); +$handler = $view->new_display('page', 'Page', 'page_1'); +$handler->override_option('path', 'project/issues/search'); +$handler->override_option('menu', array( + 'type' => 'normal', + 'title' => 'Advanced search', + 'description' => '', + 'weight' => '0', + 'name' => 'navigation', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler = $view->new_display('feed', 'Feed', 'feed_1'); +$handler->override_option('sorts', array( + 'last_comment_timestamp' => array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'override' => array( + 'button' => 'Use default', + ), + 'relationship' => 'none', + ), +)); +$handler->override_option('style_plugin', 'rss'); +$handler->override_option('style_options', array( + 'mission_description' => FALSE, + 'description' => '', +)); +$handler->override_option('row_plugin', 'node_rss'); +$handler->override_option('path', 'project/issues/search/rss'); +$handler->override_option('menu', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => '', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler->override_option('displays', array( + 'page_1' => 'page_1', + 'default' => 0, +)); +$handler->override_option('sitename_title', FALSE); + diff --git a/views/default_views/project_issue_search_project.view.php b/views/default_views/project_issue_search_project.view.php new file mode 100644 index 0000000..3af1c5f --- /dev/null +++ b/views/default_views/project_issue_search_project.view.php @@ -0,0 +1,557 @@ +<?php +// $Id: project_issue_search_project.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ + +/** + * @file + * Advanced issue search for a specific project. + */ + +$view = new view; +$view->name = 'project_issue_search_project'; +$view->description = 'Project issue advanced search for specific projects'; +$view->tag = 'Project issue'; +$view->view_php = ''; +$view->base_table = 'node'; +$view->is_cacheable = FALSE; +$view->api_version = 2; +$view->disabled = FALSE; +$handler = $view->new_display('default', 'Defaults', 'default'); +$handler->override_option('relationships', array( + 'assigned' => array( + 'label' => 'Assigned user', + 'required' => 1, + 'id' => 'assigned', + 'table' => 'project_issues', + 'field' => 'assigned', + 'relationship' => 'none', + ), + 'rid' => array( + 'label' => 'Version', + 'required' => 0, + 'id' => 'rid', + 'table' => 'project_issues', + 'field' => 'rid', + 'relationship' => 'none', + ), + 'pid' => array( + 'label' => 'Project node', + 'required' => 1, + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + ), +)); +$fields = array( + 'title' => array( + 'label' => 'Summary', + 'link_to_node' => 1, + 'exclude' => 0, + 'id' => 'title', + 'table' => 'node', + 'field' => 'title', + 'relationship' => 'none', + ), + 'timestamp' => array( + 'label' => '', + 'alter' => array(), + 'link_to_node' => 0, + 'comments' => 0, + 'exclude' => 0, + 'id' => 'timestamp', + 'table' => 'history_user', + 'field' => 'timestamp', + 'relationship' => 'none', + ), + 'sid' => array( + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + ), + 'priority' => array( + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + ), + 'category' => array( + 'label' => 'Category', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), + 'version' => array( + 'label' => 'Version', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'version', + 'table' => 'project_release_nodes', + 'field' => 'version', + 'relationship' => 'rid', + ), + 'component' => array( + 'label' => 'Component', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'component', + 'table' => 'project_issues', + 'field' => 'component', + 'relationship' => 'none', + ), + 'comment_count' => array( + 'label' => 'Replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'exclude' => 0, + 'id' => 'comment_count', + 'table' => 'node_comment_statistics', + 'field' => 'comment_count', + 'relationship' => 'none', + ), + 'new_comments' => array( + 'label' => 'New replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => ' new', + 'link_to_comment' => 1, + 'no_empty' => 1, + 'exclude' => 0, + 'id' => 'new_comments', + 'table' => 'node', + 'field' => 'new_comments', + 'relationship' => 'none', + ), + 'last_comment_timestamp' => array( + 'label' => 'Last updated', + 'date_format' => 'raw time ago', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', + ), + 'name' => array( + 'label' => 'Assigned to', + 'link_to_user' => 1, + 'overwrite_anonymous' => 1, + 'anonymous_text' => '', + 'exclude' => 0, + 'id' => 'name', + 'table' => 'users', + 'field' => 'name', + 'relationship' => 'assigned', + ), +); +if (module_exists('search')) { + $fields['score'] = array( + 'label' => 'Score', + 'alter' => array(), + 'set_precision' => 1, + 'precision' => '3', + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'alternate_sort' => 'last_comment_timestamp', + 'alternate_order' => 'desc', + 'exclude' => 0, + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('fields', $fields); +$handler->override_option('arguments', array( + 'pid' => array( + 'default_action' => 'not found', + 'style_plugin' => 'default_summary', + 'style_options' => array(), + 'wildcard' => '', + 'wildcard_substitution' => '', + 'title' => 'Search issues for %1', + 'default_argument_type' => 'fixed', + 'default_argument' => '', + 'validate_type' => 'project_nid', + 'validate_fail' => 'not found', + 'break_phrase' => 0, + 'not' => 0, + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + 'relationship' => 'none', + 'default_options_div_prefix' => '', + 'default_argument_user' => 0, + 'default_argument_fixed' => '', + 'default_argument_php' => '', + 'validate_argument_node_type' => array(), + 'validate_argument_node_access' => 0, + 'validate_argument_nid_type' => 'nid', + 'validate_argument_vocabulary' => array(), + 'validate_argument_type' => 'tid', + 'validate_argument_project_term_vocabulary' => array( + '1' => 0, + ), + 'validate_argument_project_term_argument_type' => 'tid', + 'validate_argument_project_term_argument_action_top_without' => 'pass', + 'validate_argument_project_term_argument_action_top_with' => 'pass', + 'validate_argument_project_term_argument_action_child' => 'pass', + 'validate_argument_php' => '', + ), +)); +$sorts['last_comment_timestamp'] = array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', +); +if (module_exists('search')) { + $sorts['score'] = array( + 'order' => 'DESC', + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('sorts', $sorts); +$filters = array( + 'status_extra' => array( + 'operator' => '=', + 'value' => '', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'status_extra', + 'table' => 'node', + 'field' => 'status_extra', + 'relationship' => 'none', + ), + 'uid' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'uid_op', + 'identifier' => 'assigned', + 'label' => 'Assigned', + 'optional' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'uid', + 'table' => 'users', + 'field' => 'uid', + 'relationship' => 'assigned', + ), + 'uid_1' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'uid_1_op', + 'identifier' => 'submitted', + 'label' => 'Submitted by', + 'optional' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'uid_1', + 'table' => 'users', + 'field' => 'uid', + 'relationship' => 'none', + ), + 'uid_touch' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'uid_touch_op', + 'identifier' => 'participant', + 'label' => 'Participant', + 'optional' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'uid_touch', + 'table' => 'node', + 'field' => 'uid_touch', + 'relationship' => 'none', + ), + 'sid' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'sid_op', + 'identifier' => 'status', + 'label' => 'Status', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + 'relationship' => 'none', + ), + 'priority' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'priority_op', + 'identifier' => 'priorities', + 'label' => 'Priority', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + 'relationship' => 'none', + ), + 'category' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'category_op', + 'identifier' => 'categories', + 'label' => 'Category', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), + 'rid' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'rid_op', + 'identifier' => 'version', + 'label' => 'Version', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'rid', + 'table' => 'project_issues', + 'field' => 'rid', + 'relationship' => 'none', + ), + 'component' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'component_op', + 'identifier' => 'component', + 'label' => 'Component', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'component', + 'table' => 'project_issues', + 'field' => 'component', + 'relationship' => 'none', + ), +); +if (module_exists('search')) { + $search_filter['keys'] = array( + 'operator' => 'optional', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'keys_op', + 'identifier' => 'text', + 'label' => 'Search for', + 'optional' => 1, + 'remember' => 0, + ), + 'id' => 'keys', + 'table' => 'search_index', + 'field' => 'keys', + 'relationship' => 'none', + ); + $filters = $search_filter + $filters; +} +_project_issue_views_add_taxonomy_filters($filters); +$handler->override_option('filters', $filters); +$handler->override_option('access', array( + 'type' => 'none', +)); +$handler->override_option('title', 'Search issues for a project'); +$handler->override_option('empty', 'No issues match your criteria.'); +$handler->override_option('empty_format', '1'); +$handler->override_option('items_per_page', 50); +$handler->override_option('use_pager', '1'); +$handler->override_option('style_plugin', 'project_issue_table'); +$handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 1, + 'order' => 'desc', + 'columns' => array( + 'title' => 'title', + 'timestamp' => 'title', + 'sid' => 'sid', + 'priority' => 'priority', + 'category' => 'category', + 'version' => 'version', + 'component' => 'component', + 'comment_count' => 'comment_count', + 'new_comments' => 'comment_count', + 'last_comment_timestamp' => 'last_comment_timestamp', + 'name' => 'name', + 'score' => 'score', + ), + 'info' => array( + 'title' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'timestamp' => array( + 'separator' => '', + ), + 'sid' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'priority' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'category' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'version' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'component' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'comment_count' => array( + 'sortable' => 1, + 'separator' => '<br />', + ), + 'new_comments' => array( + 'separator' => '', + ), + 'last_comment_timestamp' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'score' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', +)); +$handler = $view->new_display('page', 'Page', 'page_1'); +$handler->override_option('path', 'project/issues/search/%'); +$handler->override_option('menu', array( + 'type' => 'none', + 'title' => 'Advanced search', + 'description' => '', + 'weight' => '0', + 'name' => 'navigation', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler = $view->new_display('feed', 'Feed', 'feed_1'); +$handler->override_option('sorts', array( + 'last_comment_timestamp' => array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'override' => array( + 'button' => 'Use default', + ), + 'relationship' => 'none', + ), +)); +$handler->override_option('style_plugin', 'rss'); +$handler->override_option('style_options', array( + 'mission_description' => FALSE, + 'description' => '', +)); +$handler->override_option('row_plugin', 'node_rss'); +$handler->override_option('path', 'project/issues/search/%/rss'); +$handler->override_option('menu', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => '', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler->override_option('displays', array( + 'page_1' => 'page_1', + 'default' => 0, +)); +$handler->override_option('sitename_title', FALSE); + diff --git a/views/default_views/project_issue_user_issues.view.php b/views/default_views/project_issue_user_issues.view.php new file mode 100644 index 0000000..ba244b8 --- /dev/null +++ b/views/default_views/project_issue_user_issues.view.php @@ -0,0 +1,460 @@ +<?php +// $Id: project_issue_user_issues.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ + +/** + * @file + * All issues a user has created or commented on. + */ + +$view = new view; +$view->name = 'project_issue_user_issues'; +$view->description = 'Project issues for a specific user'; +$view->tag = 'Project issue'; +$view->view_php = ''; +$view->base_table = 'node'; +$view->is_cacheable = FALSE; +$view->api_version = 2; +$view->disabled = FALSE; +$handler = $view->new_display('default', 'Defaults', 'default'); +$handler->override_option('relationships', array( + 'assigned' => array( + 'label' => 'Assigned user', + 'required' => 1, + 'id' => 'assigned', + 'table' => 'project_issues', + 'field' => 'assigned', + 'relationship' => 'none', + ), + 'rid' => array( + 'label' => 'Version', + 'required' => 0, + 'id' => 'rid', + 'table' => 'project_issues', + 'field' => 'rid', + 'relationship' => 'none', + ), + 'pid' => array( + 'label' => 'Project node', + 'required' => 1, + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + ), +)); +$fields = array( + 'project_issue_queue' => array( + 'label' => 'Project', + 'link_type' => 'issues', + 'exclude' => 0, + 'id' => 'project_issue_queue', + 'table' => 'node', + 'field' => 'project_issue_queue', + 'relationship' => 'pid', + ), + 'title' => array( + 'label' => 'Summary', + 'link_to_node' => 1, + 'exclude' => 0, + 'id' => 'title', + 'table' => 'node', + 'field' => 'title', + 'relationship' => 'none', + ), + 'timestamp' => array( + 'label' => '', + 'alter' => array(), + 'link_to_node' => 0, + 'comments' => 0, + 'exclude' => 0, + 'id' => 'timestamp', + 'table' => 'history_user', + 'field' => 'timestamp', + 'relationship' => 'none', + ), + 'sid' => array( + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + ), + 'priority' => array( + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + ), + 'category' => array( + 'label' => 'Category', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), + 'version' => array( + 'label' => 'Version', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'version', + 'table' => 'project_release_nodes', + 'field' => 'version', + 'relationship' => 'rid', + ), + 'comment_count' => array( + 'label' => 'Replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'exclude' => 0, + 'id' => 'comment_count', + 'table' => 'node_comment_statistics', + 'field' => 'comment_count', + 'relationship' => 'none', + ), + 'new_comments' => array( + 'label' => '', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => ' new', + 'link_to_comment' => 1, + 'no_empty' => 1, + 'exclude' => 0, + 'id' => 'new_comments', + 'table' => 'node', + 'field' => 'new_comments', + 'relationship' => 'none', + ), + 'last_comment_timestamp' => array( + 'label' => 'Last updated', + 'date_format' => 'raw time ago', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', + ), + 'name' => array( + 'label' => 'Assigned to', + 'link_to_user' => 1, + 'overwrite_anonymous' => 1, + 'anonymous_text' => '', + 'exclude' => 0, + 'id' => 'name', + 'table' => 'users', + 'field' => 'name', + 'relationship' => 'assigned', + ), +); +if (module_exists('search')) { + $fields['score'] = array( + 'label' => 'Score', + 'alter' => array(), + 'set_precision' => 1, + 'precision' => '3', + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'alternate_sort' => 'last_comment_timestamp', + 'alternate_order' => 'desc', + 'exclude' => 0, + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('fields', $fields); +$handler->override_option('arguments', array( + 'uid_touch' => array( + 'default_action' => 'default', + 'style_plugin' => 'default_summary', + 'style_options' => array(), + 'wildcard' => 'all', + 'wildcard_substitution' => 'All', + 'title' => 'Issues for %1', + 'default_argument_type' => 'current_user', + 'default_argument' => '', + 'validate_type' => 'user', + 'validate_fail' => 'not found', + 'id' => 'uid_touch', + 'table' => 'node', + 'field' => 'uid_touch', + 'relationship' => 'none', + 'default_options_div_prefix' => '', + 'default_argument_user' => 0, + 'default_argument_fixed' => '', + 'default_argument_php' => '', + 'validate_user_argument_type' => 'either', + 'validate_user_restrict_roles' => 1, + 'validate_user_roles' => array('2' => 2), + ), +)); +$sorts['last_comment_timestamp'] = array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', +); +if (module_exists('search')) { + $sorts['score'] = array( + 'order' => 'DESC', + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('sorts', $sorts); +$filters = array( + 'status_extra' => array( + 'operator' => '=', + 'value' => '', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'status_extra', + 'table' => 'node', + 'field' => 'status_extra', + 'relationship' => 'none', + ), + 'pid' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'operator' => 'pid_op', + 'label' => 'Project', + 'use_operator' => 0, + 'identifier' => 'projects', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'widget' => 'textfield', + 'project_source' => 'participant', + 'project_uid_argument' => 'uid_touch', + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + 'relationship' => 'none', + ), + 'sid' => array( + 'operator' => 'in', + 'value' => array( + 'Open' => 'Open', + ), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'sid_op', + 'identifier' => 'status', + 'label' => 'Status', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + 'relationship' => 'none', + ), + 'priority' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'priority_op', + 'identifier' => 'priorities', + 'label' => 'Priority', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + 'relationship' => 'none', + ), + 'category' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'category_op', + 'identifier' => 'categories', + 'label' => 'Category', + 'optional' => 1, + 'single' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), +); +if (module_exists('search')) { + $search_filter['keys'] = array( + 'operator' => 'optional', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'keys_op', + 'identifier' => 'text', + 'label' => 'Search for', + 'optional' => 1, + 'remember' => 0, + ), + 'id' => 'keys', + 'table' => 'search_index', + 'field' => 'keys', + 'relationship' => 'none', + ); + $filters = $search_filter + $filters; +} +$handler->override_option('filters', $filters); +$handler->override_option('access', array( + 'type' => 'project_issue_access_per_user_queue', + 'project_issue_user_argument' => 'uid_touch', +)); +$handler->override_option('title', 'My issues'); +$handler->override_option('empty', 'No issues match your criteria.'); +$handler->override_option('empty_format', '1'); +$handler->override_option('items_per_page', 50); +$handler->override_option('use_pager', '1'); +$handler->override_option('style_plugin', 'project_issue_table'); +$handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 1, + 'order' => 'desc', + 'columns' => array( + 'project_issue_queue' => 'project_issue_queue', + 'title' => 'title', + 'timestamp' => 'title', + 'sid' => 'sid', + 'priority' => 'priority', + 'category' => 'category', + 'version' => 'version', + 'comment_count' => 'comment_count', + 'new_comments' => 'comment_count', + 'last_comment_timestamp' => 'last_comment_timestamp', + 'name' => 'name', + 'score' => 'score', + ), + 'info' => array( + 'project_issue_queue' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'title' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'timestamp' => array( + 'separator' => '', + ), + 'sid' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'priority' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'category' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'version' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'comment_count' => array( + 'sortable' => 1, + 'separator' => '<br />', + ), + 'new_comments' => array( + 'separator' => '', + ), + 'last_comment_timestamp' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'score' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', +)); +$handler = $view->new_display('page', 'Page', 'page_1'); +$handler->override_option('path', 'project/issues/user'); +$handler->override_option('menu', array( + 'type' => 'normal', + 'title' => 'My issues', + 'description' => '', + 'weight' => '0', + 'name' => 'navigation', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler = $view->new_display('feed', 'Feed', 'feed_1'); +$handler->override_option('style_plugin', 'rss'); +$handler->override_option('style_options', array( + 'mission_description' => FALSE, + 'description' => '', +)); +$handler->override_option('row_plugin', 'node_rss'); +$handler->override_option('path', 'project/issues/user/%/feed'); +$handler->override_option('menu', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => 'navigation', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler->override_option('displays', array( + 'page_1' => 'page_1', + 'default' => 0, +)); +$handler->override_option('sitename_title', FALSE); + diff --git a/views/default_views/project_issue_user_projects.view.php b/views/default_views/project_issue_user_projects.view.php new file mode 100644 index 0000000..a96c504 --- /dev/null +++ b/views/default_views/project_issue_user_projects.view.php @@ -0,0 +1,464 @@ +<?php +// $Id: project_issue_user_projects.view.php,v 1.1 2009/06/18 03:38:43 dww Exp $ + +/** + * @file + * Issues across all projects owned by a user. + */ + +$view = new view; +$view->name = 'project_issue_user_projects'; +$view->description = "Project issues for a specific user's projects"; +$view->tag = 'Project issue'; +$view->view_php = ''; +$view->base_table = 'node'; +$view->is_cacheable = FALSE; +$view->api_version = 2; +$view->disabled = FALSE; +$handler = $view->new_display('default', 'Defaults', 'default'); +$handler->override_option('relationships', array( + 'assigned' => array( + 'label' => 'Assigned user', + 'required' => 1, + 'id' => 'assigned', + 'table' => 'project_issues', + 'field' => 'assigned', + 'relationship' => 'none', + ), + 'rid' => array( + 'label' => 'Version', + 'required' => 0, + 'id' => 'rid', + 'table' => 'project_issues', + 'field' => 'rid', + 'relationship' => 'none', + ), + 'pid' => array( + 'label' => 'Project node', + 'required' => 1, + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + ), +)); +$fields = array( + 'project_issue_queue' => array( + 'label' => 'Project', + 'link_type' => 'issues', + 'exclude' => 0, + 'id' => 'project_issue_queue', + 'table' => 'node', + 'field' => 'project_issue_queue', + 'relationship' => 'pid', + ), + 'title' => array( + 'label' => 'Summary', + 'link_to_node' => 1, + 'exclude' => 0, + 'id' => 'title', + 'table' => 'node', + 'field' => 'title', + 'relationship' => 'none', + ), + 'timestamp' => array( + 'label' => '', + 'alter' => array(), + 'link_to_node' => 0, + 'comments' => 0, + 'exclude' => 0, + 'id' => 'timestamp', + 'table' => 'history_user', + 'field' => 'timestamp', + 'relationship' => 'none', + ), + 'sid' => array( + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + ), + 'priority' => array( + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + ), + 'category' => array( + 'label' => 'Category', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), + 'version' => array( + 'label' => 'Version', + 'link_to_node' => 0, + 'exclude' => 0, + 'id' => 'version', + 'table' => 'project_release_nodes', + 'field' => 'version', + 'relationship' => 'rid', + ), + 'comment_count' => array( + 'label' => 'Replies', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'exclude' => 0, + 'id' => 'comment_count', + 'table' => 'node_comment_statistics', + 'field' => 'comment_count', + 'relationship' => 'none', + ), + 'new_comments' => array( + 'label' => '', + 'set_precision' => FALSE, + 'precision' => 0, + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => ' new', + 'link_to_comment' => 1, + 'no_empty' => 1, + 'exclude' => 0, + 'id' => 'new_comments', + 'table' => 'node', + 'field' => 'new_comments', + 'relationship' => 'none', + ), + 'last_comment_timestamp' => array( + 'label' => 'Last updated', + 'date_format' => 'raw time ago', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', + ), + 'name' => array( + 'label' => 'Assigned to', + 'link_to_user' => 1, + 'overwrite_anonymous' => 1, + 'anonymous_text' => '', + 'exclude' => 0, + 'id' => 'name', + 'table' => 'users', + 'field' => 'name', + 'relationship' => 'assigned', + ), +); +if (module_exists('search')) { + $fields['score'] = array( + 'label' => 'Score', + 'alter' => array(), + 'set_precision' => 1, + 'precision' => '3', + 'decimal' => '.', + 'separator' => ',', + 'prefix' => '', + 'suffix' => '', + 'alternate_sort' => 'last_comment_timestamp', + 'alternate_order' => 'desc', + 'exclude' => 0, + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('fields', $fields); +$sorts['last_comment_timestamp'] = array( + 'order' => 'DESC', + 'granularity' => 'second', + 'id' => 'last_comment_timestamp', + 'table' => 'node_comment_statistics', + 'field' => 'last_comment_timestamp', + 'relationship' => 'none', +); +if (module_exists('search')) { + $sorts['score'] = array( + 'order' => 'DESC', + 'id' => 'score', + 'table' => 'search_index', + 'field' => 'score', + 'relationship' => 'none', + ); +} +$handler->override_option('sorts', $sorts); +$handler->override_option('arguments', array( + 'uid' => array( + 'default_action' => 'default', + 'style_plugin' => 'default_summary', + 'style_options' => array(), + 'wildcard' => 'all', + 'wildcard_substitution' => 'All', + 'title' => 'Projects by %1', + 'default_argument_type' => 'current_user', + 'default_argument' => '', + 'validate_type' => 'user', + 'validate_fail' => 'not found', + 'break_phrase' => 0, + 'not' => 0, + 'id' => 'uid', + 'table' => 'users', + 'field' => 'uid', + 'relationship' => 'pid', + 'default_options_div_prefix' => '', + 'default_argument_user' => 0, + 'default_argument_fixed' => '', + 'default_argument_php' => '', + 'validate_user_argument_type' => 'either', + 'validate_user_restrict_roles' => 1, + 'validate_user_roles' => array('2' => 2), + ), +)); +$filters = array( + 'status_extra' => array( + 'operator' => '=', + 'value' => '', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'status_extra', + 'table' => 'node', + 'field' => 'status_extra', + 'relationship' => 'none', + ), + 'pid' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'operator' => 'pid_op', + 'label' => 'Project', + 'use_operator' => 0, + 'identifier' => 'projects', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'widget' => 'select', + 'project_source' => 'owner', + 'project_uid_argument' => 'uid', + 'id' => 'pid', + 'table' => 'project_issues', + 'field' => 'pid', + 'relationship' => 'none', + ), + 'sid' => array( + 'operator' => 'in', + 'value' => array( + 'Open' => 'Open', + ), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'sid_op', + 'identifier' => 'status', + 'label' => 'Status', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'sid', + 'table' => 'project_issues', + 'field' => 'sid', + 'relationship' => 'none', + ), + 'priority' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'priority_op', + 'identifier' => 'priorities', + 'label' => 'Priority', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'priority', + 'table' => 'project_issues', + 'field' => 'priority', + 'relationship' => 'none', + ), + 'category' => array( + 'operator' => 'in', + 'value' => array(), + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'category_op', + 'identifier' => 'categories', + 'label' => 'Category', + 'optional' => 1, + 'single' => 0, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'category', + 'table' => 'project_issues', + 'field' => 'category', + 'relationship' => 'none', + ), +); +if (module_exists('search')) { + $search_filter['keys'] = array( + 'operator' => 'optional', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'keys_op', + 'identifier' => 'text', + 'label' => 'Search for', + 'optional' => 1, + 'remember' => 0, + ), + 'id' => 'keys', + 'table' => 'search_index', + 'field' => 'keys', + 'relationship' => 'none', + ); + $filters = $search_filter + $filters; +} +$handler->override_option('filters', $filters); +$handler->override_option('access', array( + 'type' => 'project_issue_access_per_user_queue', + 'project_issue_user_argument' => 'uid', +)); +$handler->override_option('empty', 'No issues match your criteria.'); +$handler->override_option('empty_format', '1'); +$handler->override_option('items_per_page', 50); +$handler->override_option('use_pager', '1'); +$handler->override_option('style_plugin', 'project_issue_table'); +$handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 1, + 'order' => 'desc', + 'columns' => array( + 'project_issue_queue' => 'project_issue_queue', + 'title' => 'title', + 'timestamp' => 'title', + 'sid' => 'sid', + 'priority' => 'priority', + 'category' => 'category', + 'version' => 'version', + 'comment_count' => 'comment_count', + 'new_comments' => 'comment_count', + 'last_comment_timestamp' => 'last_comment_timestamp', + 'name' => 'name', + 'score' => 'score', + ), + 'info' => array( + 'project_issue_queue' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'title' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'timestamp' => array( + 'separator' => '', + ), + 'sid' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'priority' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'category' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'version' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'comment_count' => array( + 'sortable' => 1, + 'separator' => '<br />', + ), + 'new_comments' => array( + 'separator' => '', + ), + 'last_comment_timestamp' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'score' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', +)); +$handler = $view->new_display('page', 'Page', 'page_1'); +$handler->override_option('path', 'project/user'); +$handler->override_option('menu', array( + 'type' => 'normal', + 'title' => 'My projects', + 'description' => '', + 'weight' => '0', + 'name' => 'navigation', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler = $view->new_display('feed', 'Feed', 'feed_1'); +$handler->override_option('style_plugin', 'rss'); +$handler->override_option('style_options', array( + 'mission_description' => FALSE, + 'description' => '', +)); +$handler->override_option('row_plugin', 'node_rss'); +$handler->override_option('row_options', array( + 'item_length' => 'default', +)); +$handler->override_option('path', 'project/user/%/feed'); +$handler->override_option('menu', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => 'navigation', +)); +$handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, +)); +$handler->override_option('displays', array( + 'page_1' => 'page_1', + 'default' => 0, +)); +$handler->override_option('sitename_title', FALSE); + diff --git a/views/project_issue.views_default.inc b/views/project_issue.views_default.inc index 46f5644..d7896cd 100644 --- a/views/project_issue.views_default.inc +++ b/views/project_issue.views_default.inc @@ -1,3043 +1,70 @@ <?php -// $Id: project_issue.views_default.inc,v 1.46 2009/05/06 06:38:39 dww Exp $ +// $Id: project_issue.views_default.inc,v 1.47 2009/06/18 03:38:42 dww Exp $ /** * @file * Provides default views on behalf of the project_issue module. */ /** * Implementation of hook_views_default_views(). */ function project_issue_views_default_views() { - // ---------------------------------------- - // Issue queue across all projects - // ---------------------------------------- - $view = new view; - $view->name = 'project_issue_all_projects'; - $view->description = 'Project issues for all projects'; - $view->tag = 'Project issue'; - $view->view_php = ''; - $view->base_table = 'node'; - $view->is_cacheable = FALSE; - $view->api_version = 2; - $view->disabled = FALSE; - $handler = $view->new_display('default', 'Defaults', 'default'); - $handler->override_option('relationships', array( - 'assigned' => array( - 'label' => 'Assigned user', - 'required' => 1, - 'id' => 'assigned', - 'table' => 'project_issues', - 'field' => 'assigned', - 'relationship' => 'none', - ), - 'rid' => array( - 'label' => 'Version', - 'required' => 0, - 'id' => 'rid', - 'table' => 'project_issues', - 'field' => 'rid', - 'relationship' => 'none', - ), - 'pid' => array( - 'label' => 'Project node', - 'required' => 1, - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - ), - )); - $fields = array( - 'project_issue_queue' => array( - 'label' => 'Project', - 'link_type' => 'issues', - 'exclude' => 0, - 'id' => 'project_issue_queue', - 'table' => 'node', - 'field' => 'project_issue_queue', - 'relationship' => 'pid', - ), - 'title' => array( - 'label' => 'Summary', - 'link_to_node' => 1, - 'exclude' => 0, - 'id' => 'title', - 'table' => 'node', - 'field' => 'title', - 'relationship' => 'none', - ), - 'timestamp' => array( - 'label' => '', - 'alter' => array(), - 'link_to_node' => 0, - 'comments' => 0, - 'exclude' => 0, - 'id' => 'timestamp', - 'table' => 'history_user', - 'field' => 'timestamp', - 'relationship' => 'none', - ), - 'sid' => array( - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - ), - 'priority' => array( - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - ), - 'category' => array( - 'label' => 'Category', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - 'comment_count' => array( - 'label' => 'Replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'exclude' => 0, - 'id' => 'comment_count', - 'table' => 'node_comment_statistics', - 'field' => 'comment_count', - 'relationship' => 'none', - ), - 'new_comments' => array( - 'label' => 'New replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => ' new', - 'link_to_comment' => 1, - 'no_empty' => 1, - 'exclude' => 0, - 'id' => 'new_comments', - 'table' => 'node', - 'field' => 'new_comments', - 'relationship' => 'none', - ), - 'last_comment_timestamp' => array( - 'label' => 'Last updated', - 'date_format' => 'raw time ago', - 'custom_date_format' => '', - 'exclude' => 0, - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ), - 'name' => array( - 'label' => 'Assigned to', - 'link_to_user' => 1, - 'overwrite_anonymous' => 1, - 'anonymous_text' => '', - 'exclude' => 0, - 'id' => 'name', - 'table' => 'users', - 'field' => 'name', - 'relationship' => 'assigned', - ), - ); - if (module_exists('search')) { - $fields['score'] = array( - 'label' => 'Score', - 'alter' => array(), - 'set_precision' => 1, - 'precision' => '3', - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'alternate_sort' => 'last_comment_timestamp', - 'alternate_order' => 'desc', - 'exclude' => 0, - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('fields', $fields); - $sorts['last_comment_timestamp'] = array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ); - if (module_exists('search')) { - $sorts['score'] = array( - 'order' => 'DESC', - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('sorts', $sorts); - $filters = array( - 'status_extra' => array( - 'operator' => '=', - 'value' => '', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'status_extra', - 'table' => 'node', - 'field' => 'status_extra', - 'relationship' => 'none', - ), - 'pid' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'operator' => 'pid_op', - 'label' => 'Project', - 'use_operator' => 0, - 'identifier' => 'projects', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'widget' => 'textfield', - 'project_source' => 'all', - 'project_uid_argument' => '', - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - 'relationship' => 'none', - ), - 'sid' => array( - 'operator' => 'in', - 'value' => array( - 'Open' => 'Open', - ), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'sid_op', - 'identifier' => 'status', - 'label' => 'Status', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - 'relationship' => 'none', - ), - 'priority' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'priority_op', - 'identifier' => 'priorities', - 'label' => 'Priority', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - 'relationship' => 'none', - ), - 'category' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'category_op', - 'identifier' => 'categories', - 'label' => 'Category', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - ); - if (module_exists('search')) { - $search_filter['keys'] = array( - 'operator' => 'optional', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'keys_op', - 'identifier' => 'text', - 'label' => 'Search for', - 'optional' => 1, - 'remember' => 0, - ), - 'id' => 'keys', - 'table' => 'search_index', - 'field' => 'keys', - 'relationship' => 'none', - ); - $filters = $search_filter + $filters; - } - $handler->override_option('filters', $filters); - $handler->override_option('access', array( - 'type' => 'none', - )); - $handler->override_option('title', 'Issues for all projects'); - $handler->override_option('empty', 'No issues match your criteria.'); - $handler->override_option('empty_format', '1'); - $handler->override_option('items_per_page', 50); - $handler->override_option('use_pager', '1'); - $handler->override_option('style_plugin', 'project_issue_table'); - $handler->override_option('style_options', array( - 'grouping' => '', - 'override' => 1, - 'sticky' => 1, - 'order' => 'desc', - 'columns' => array( - 'project_issue_queue' => 'project_issue_queue', - 'title' => 'title', - 'timestamp' => 'title', - 'sid' => 'sid', - 'priority' => 'priority', - 'category' => 'category', - 'comment_count' => 'comment_count', - 'new_comments' => 'comment_count', - 'last_comment_timestamp' => 'last_comment_timestamp', - 'name' => 'name', - 'score' => 'score', - ), - 'info' => array( - 'project_issue_queue' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'title' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'timestamp' => array( - 'separator' => '', - ), - 'sid' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'priority' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'category' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'comment_count' => array( - 'sortable' => 1, - 'separator' => '<br />', - ), - 'new_comments' => array( - 'separator' => '', - ), - 'last_comment_timestamp' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'name' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'score' => array( - 'sortable' => 1, - 'separator' => '', - ), - ), - 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', - )); - $handler = $view->new_display('page', 'Page', 'page_1'); - $handler->override_option('path', 'project/issues'); - $handler->override_option('menu', array( - 'type' => 'normal', - 'title' => 'Issues', - 'description' => '', - 'weight' => '0', - 'name' => 'navigation', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler = $view->new_display('feed', 'Feed', 'feed_1'); - $handler->override_option('sorts', array( - 'last_comment_timestamp' => array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'override' => array( - 'button' => 'Use default', - ), - 'relationship' => 'none', - ), - )); - $handler->override_option('style_plugin', 'rss'); - $handler->override_option('style_options', array( - 'mission_description' => FALSE, - 'description' => '', - )); - $handler->override_option('row_plugin', 'node_rss'); - $handler->override_option('path', 'project/issues/rss'); - $handler->override_option('menu', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - 'name' => '', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler->override_option('displays', array( - 'page_1' => 'page_1', - 'default' => 0, - )); - $handler->override_option('sitename_title', FALSE); - - $views[$view->name] = $view; - - - // ---------------------------------------- - // Issue queue for a specific project - // ---------------------------------------- - $view = new view; - $view->name = 'project_issue_project'; - $view->description = 'Project issues by project'; - $view->tag = 'Project issue'; - $view->view_php = ''; - $view->base_table = 'node'; - $view->is_cacheable = FALSE; - $view->api_version = 2; - $view->disabled = FALSE; - $handler = $view->new_display('default', 'Defaults', 'default'); - $handler->override_option('relationships', array( - 'assigned' => array( - 'label' => 'Assigned user', - 'required' => 1, - 'id' => 'assigned', - 'table' => 'project_issues', - 'field' => 'assigned', - 'relationship' => 'none', - ), - 'rid' => array( - 'label' => 'Version', - 'required' => 0, - 'id' => 'rid', - 'table' => 'project_issues', - 'field' => 'rid', - 'relationship' => 'none', - ), - )); - $fields = array( - 'title' => array( - 'label' => 'Summary', - 'link_to_node' => 1, - 'exclude' => 0, - 'id' => 'title', - 'table' => 'node', - 'field' => 'title', - 'relationship' => 'none', - ), - 'timestamp' => array( - 'label' => '', - 'alter' => array(), - 'link_to_node' => 0, - 'comments' => 0, - 'exclude' => 0, - 'id' => 'timestamp', - 'table' => 'history_user', - 'field' => 'timestamp', - 'relationship' => 'none', - ), - 'sid' => array( - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - ), - 'priority' => array( - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - ), - 'category' => array( - 'label' => 'Category', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - 'version' => array( - 'label' => 'Version', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'version', - 'table' => 'project_release_nodes', - 'field' => 'version', - 'relationship' => 'rid', - ), - 'component' => array( - 'label' => 'Component', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'component', - 'table' => 'project_issues', - 'field' => 'component', - 'relationship' => 'none', - ), - 'comment_count' => array( - 'label' => 'Replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'exclude' => 0, - 'id' => 'comment_count', - 'table' => 'node_comment_statistics', - 'field' => 'comment_count', - 'relationship' => 'none', - ), - 'new_comments' => array( - 'label' => 'New replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => ' new', - 'link_to_comment' => 1, - 'no_empty' => 1, - 'exclude' => 0, - 'id' => 'new_comments', - 'table' => 'node', - 'field' => 'new_comments', - 'relationship' => 'none', - ), - 'last_comment_timestamp' => array( - 'label' => 'Last updated', - 'date_format' => 'raw time ago', - 'custom_date_format' => '', - 'exclude' => 0, - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ), - 'name' => array( - 'label' => 'Assigned to', - 'link_to_user' => 1, - 'overwrite_anonymous' => 1, - 'anonymous_text' => '', - 'exclude' => 0, - 'id' => 'name', - 'table' => 'users', - 'field' => 'name', - 'relationship' => 'assigned', - ), - ); - if (module_exists('search')) { - $fields['score'] = array( - 'label' => 'Score', - 'alter' => array(), - 'set_precision' => 1, - 'precision' => '3', - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'alternate_sort' => 'last_comment_timestamp', - 'alternate_order' => 'desc', - 'exclude' => 0, - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('fields', $fields); - $handler->override_option('arguments', array( - 'pid' => array( - 'default_action' => 'not found', - 'style_plugin' => 'default_summary', - 'style_options' => array(), - 'wildcard' => '', - 'wildcard_substitution' => '', - 'title' => 'Issues for %1', - 'default_argument_type' => 'fixed', - 'default_argument' => '', - 'validate_type' => 'project_nid', - 'validate_fail' => 'not found', - 'break_phrase' => 0, - 'not' => 0, - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - 'relationship' => 'none', - 'default_options_div_prefix' => '', - 'default_argument_user' => 0, - 'default_argument_fixed' => '', - 'default_argument_php' => '', - ), - )); - $sorts['last_comment_timestamp'] = array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ); - if (module_exists('search')) { - $sorts['score'] = array( - 'order' => 'DESC', - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('sorts', $sorts); - $filters = array( - 'status_extra' => array( - 'operator' => '=', - 'value' => '', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'status_extra', - 'table' => 'node', - 'field' => 'status_extra', - 'relationship' => 'none', - ), - 'sid' => array( - 'operator' => 'in', - 'value' => array( - 'Open' => 'Open', - ), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'sid_op', - 'identifier' => 'status', - 'label' => 'Status', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - 'relationship' => 'none', - ), - 'priority' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'priority_op', - 'identifier' => 'priorities', - 'label' => 'Priority', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - 'relationship' => 'none', - ), - 'category' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'category_op', - 'identifier' => 'categories', - 'label' => 'Category', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - 'rid' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'rid_op', - 'identifier' => 'version', - 'label' => 'Version', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'rid', - 'table' => 'project_issues', - 'field' => 'rid', - 'relationship' => 'none', - ), - 'component' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'component_op', - 'identifier' => 'component', - 'label' => 'Component', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'component', - 'table' => 'project_issues', - 'field' => 'component', - 'relationship' => 'none', - ), - ); - if (module_exists('search')) { - $search_filter['keys'] = array( - 'operator' => 'optional', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'keys_op', - 'identifier' => 'text', - 'label' => 'Search for', - 'optional' => 1, - 'remember' => 0, - ), - 'id' => 'keys', - 'table' => 'search_index', - 'field' => 'keys', - 'relationship' => 'none', - ); - $filters = $search_filter + $filters; - } - $handler->override_option('filters', $filters); - $handler->override_option('access', array( - 'type' => 'none', - )); - $handler->override_option('title', 'Issues by project'); - $handler->override_option('empty', 'No issues match your criteria.'); - $handler->override_option('empty_format', '1'); - $handler->override_option('items_per_page', 50); - $handler->override_option('use_pager', '1'); - $handler->override_option('style_plugin', 'project_issue_table'); - $handler->override_option('style_options', array( - 'grouping' => '', - 'override' => 1, - 'sticky' => 1, - 'order' => 'desc', - 'columns' => array( - 'title' => 'title', - 'timestamp' => 'title', - 'sid' => 'sid', - 'priority' => 'priority', - 'category' => 'category', - 'version' => 'version', - 'component' => 'component', - 'comment_count' => 'comment_count', - 'new_comments' => 'comment_count', - 'last_comment_timestamp' => 'last_comment_timestamp', - 'name' => 'name', - 'score' => 'score', - ), - 'info' => array( - 'title' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'timestamp' => array( - 'separator' => '', - ), - 'sid' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'priority' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'category' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'version' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'component' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'comment_count' => array( - 'sortable' => 1, - 'separator' => '<br />', - ), - 'new_comments' => array( - 'separator' => '', - ), - 'last_comment_timestamp' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'name' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'score' => array( - 'sortable' => 1, - 'separator' => '', - ), - ), - 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', - )); - $handler = $view->new_display('page', 'Page', 'page_1'); - $handler->override_option('path', 'project/issues/%'); - $handler->override_option('menu', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => '0', - 'name' => '', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler = $view->new_display('feed', 'Feed', 'feed_1'); - $handler->override_option('sorts', array( - 'last_comment_timestamp' => array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'override' => array( - 'button' => 'Use default', - ), - 'relationship' => 'none', - ), - )); - $handler->override_option('style_plugin', 'rss'); - $handler->override_option('style_options', array( - 'mission_description' => FALSE, - 'description' => '', - )); - $handler->override_option('row_plugin', 'node_rss'); - $handler->override_option('path', 'project/issues/rss/%'); - $handler->override_option('menu', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - 'name' => '', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler->override_option('displays', array( - 'page_1' => 'page_1', - 'default' => 0, - )); - $handler->override_option('sitename_title', FALSE); - $handler = $view->new_display('block', 'Block', 'block_1'); - $handler->override_option('title', 'Recent issues'); - $handler->override_option('relationships', array()); - $handler->override_option('fields', array( - 'title' => array( - 'label' => '', - 'alter' => array(), - 'link_to_node' => 1, - 'exclude' => 0, - 'id' => 'title', - 'table' => 'node', - 'field' => 'title', - 'relationship' => 'none', - 'override' => array( - 'button' => 'Use default', - ), - ), - 'timestamp' => array( - 'label' => '', - 'alter' => array(), - 'link_to_node' => 0, - 'comments' => 0, - 'exclude' => 0, - 'id' => 'timestamp', - 'table' => 'history_user', - 'field' => 'timestamp', - 'relationship' => 'none', - ), - )); - $handler->override_option('sorts', array( - 'last_comment_timestamp' => array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ), - )); - $handler->override_option('arguments', array( - 'pid' => array( - 'default_action' => 'default', - 'style_plugin' => 'default_summary', - 'style_options' => array(), - 'wildcard' => '', - 'wildcard_substitution' => '', - 'default_argument_type' => 'node', - 'default_argument' => '', - 'validate_type' => 'project_nid', - 'validate_fail' => 'not found', - 'break_phrase' => 0, - 'not' => 0, - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - 'relationship' => 'none', - ), - )); - $handler->override_option('filters', array( - 'status_extra' => array( - 'operator' => '=', - 'value' => '', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array(), - 'id' => 'status_extra', - 'table' => 'node', - 'field' => 'status_extra', - 'relationship' => 'none', - ), - 'sid' => array( - 'operator' => 'in', - 'value' => array( - 'Open' => 'Open', - ), - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array(), - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - 'relationship' => 'none', - ), - )); - $handler->override_option('items_per_page', 5); - $handler->override_option('use_pager', '0'); - $handler->override_option('style_plugin', 'list'); - $handler->override_option('style_options', array( - 'grouping' => '', - 'type' => 'ul', - )); - $handler->override_option('row_options', array( - 'inline' => array( - 'title' => 'title', - 'timestamp' => 'timestamp', - ), - 'separator' => ' ', - )); - $handler->override_option('block_description', 'Project: recent issues'); - $handler->override_option('block_caching', -1); - - $views[$view->name] = $view; - - - // --------------------------------------------- - // All issues a user has created or commented on - // --------------------------------------------- - $view = new view; - $view->name = 'project_issue_user_issues'; - $view->description = 'Project issues for a specific user'; - $view->tag = 'Project issue'; - $view->view_php = ''; - $view->base_table = 'node'; - $view->is_cacheable = FALSE; - $view->api_version = 2; - $view->disabled = FALSE; - $handler = $view->new_display('default', 'Defaults', 'default'); - $handler->override_option('relationships', array( - 'assigned' => array( - 'label' => 'Assigned user', - 'required' => 1, - 'id' => 'assigned', - 'table' => 'project_issues', - 'field' => 'assigned', - 'relationship' => 'none', - ), - 'rid' => array( - 'label' => 'Version', - 'required' => 0, - 'id' => 'rid', - 'table' => 'project_issues', - 'field' => 'rid', - 'relationship' => 'none', - ), - 'pid' => array( - 'label' => 'Project node', - 'required' => 1, - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - ), - )); - $fields = array( - 'project_issue_queue' => array( - 'label' => 'Project', - 'link_type' => 'issues', - 'exclude' => 0, - 'id' => 'project_issue_queue', - 'table' => 'node', - 'field' => 'project_issue_queue', - 'relationship' => 'pid', - ), - 'title' => array( - 'label' => 'Summary', - 'link_to_node' => 1, - 'exclude' => 0, - 'id' => 'title', - 'table' => 'node', - 'field' => 'title', - 'relationship' => 'none', - ), - 'timestamp' => array( - 'label' => '', - 'alter' => array(), - 'link_to_node' => 0, - 'comments' => 0, - 'exclude' => 0, - 'id' => 'timestamp', - 'table' => 'history_user', - 'field' => 'timestamp', - 'relationship' => 'none', - ), - 'sid' => array( - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - ), - 'priority' => array( - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - ), - 'category' => array( - 'label' => 'Category', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - 'version' => array( - 'label' => 'Version', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'version', - 'table' => 'project_release_nodes', - 'field' => 'version', - 'relationship' => 'rid', - ), - 'comment_count' => array( - 'label' => 'Replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'exclude' => 0, - 'id' => 'comment_count', - 'table' => 'node_comment_statistics', - 'field' => 'comment_count', - 'relationship' => 'none', - ), - 'new_comments' => array( - 'label' => '', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => ' new', - 'link_to_comment' => 1, - 'no_empty' => 1, - 'exclude' => 0, - 'id' => 'new_comments', - 'table' => 'node', - 'field' => 'new_comments', - 'relationship' => 'none', - ), - 'last_comment_timestamp' => array( - 'label' => 'Last updated', - 'date_format' => 'raw time ago', - 'custom_date_format' => '', - 'exclude' => 0, - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ), - 'name' => array( - 'label' => 'Assigned to', - 'link_to_user' => 1, - 'overwrite_anonymous' => 1, - 'anonymous_text' => '', - 'exclude' => 0, - 'id' => 'name', - 'table' => 'users', - 'field' => 'name', - 'relationship' => 'assigned', - ), - ); - if (module_exists('search')) { - $fields['score'] = array( - 'label' => 'Score', - 'alter' => array(), - 'set_precision' => 1, - 'precision' => '3', - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'alternate_sort' => 'last_comment_timestamp', - 'alternate_order' => 'desc', - 'exclude' => 0, - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('fields', $fields); - $handler->override_option('arguments', array( - 'uid_touch' => array( - 'default_action' => 'default', - 'style_plugin' => 'default_summary', - 'style_options' => array(), - 'wildcard' => 'all', - 'wildcard_substitution' => 'All', - 'title' => 'Issues for %1', - 'default_argument_type' => 'current_user', - 'default_argument' => '', - 'validate_type' => 'user', - 'validate_fail' => 'not found', - 'id' => 'uid_touch', - 'table' => 'node', - 'field' => 'uid_touch', - 'relationship' => 'none', - 'default_options_div_prefix' => '', - 'default_argument_user' => 0, - 'default_argument_fixed' => '', - 'default_argument_php' => '', - 'validate_user_argument_type' => 'either', - 'validate_user_restrict_roles' => 1, - 'validate_user_roles' => array('2' => 2), - ), - )); - $sorts['last_comment_timestamp'] = array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ); - if (module_exists('search')) { - $sorts['score'] = array( - 'order' => 'DESC', - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('sorts', $sorts); - $filters = array( - 'status_extra' => array( - 'operator' => '=', - 'value' => '', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'status_extra', - 'table' => 'node', - 'field' => 'status_extra', - 'relationship' => 'none', - ), - 'pid' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'operator' => 'pid_op', - 'label' => 'Project', - 'use_operator' => 0, - 'identifier' => 'projects', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'widget' => 'textfield', - 'project_source' => 'participant', - 'project_uid_argument' => 'uid_touch', - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - 'relationship' => 'none', - ), - 'sid' => array( - 'operator' => 'in', - 'value' => array( - 'Open' => 'Open', - ), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'sid_op', - 'identifier' => 'status', - 'label' => 'Status', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - 'relationship' => 'none', - ), - 'priority' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'priority_op', - 'identifier' => 'priorities', - 'label' => 'Priority', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - 'relationship' => 'none', - ), - 'category' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'category_op', - 'identifier' => 'categories', - 'label' => 'Category', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - ); - if (module_exists('search')) { - $search_filter['keys'] = array( - 'operator' => 'optional', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'keys_op', - 'identifier' => 'text', - 'label' => 'Search for', - 'optional' => 1, - 'remember' => 0, - ), - 'id' => 'keys', - 'table' => 'search_index', - 'field' => 'keys', - 'relationship' => 'none', - ); - $filters = $search_filter + $filters; - } - $handler->override_option('filters', $filters); - $handler->override_option('access', array( - 'type' => 'project_issue_access_per_user_queue', - 'project_issue_user_argument' => 'uid_touch', - )); - $handler->override_option('title', 'My issues'); - $handler->override_option('empty', 'No issues match your criteria.'); - $handler->override_option('empty_format', '1'); - $handler->override_option('items_per_page', 50); - $handler->override_option('use_pager', '1'); - $handler->override_option('style_plugin', 'project_issue_table'); - $handler->override_option('style_options', array( - 'grouping' => '', - 'override' => 1, - 'sticky' => 1, - 'order' => 'desc', - 'columns' => array( - 'project_issue_queue' => 'project_issue_queue', - 'title' => 'title', - 'timestamp' => 'title', - 'sid' => 'sid', - 'priority' => 'priority', - 'category' => 'category', - 'version' => 'version', - 'comment_count' => 'comment_count', - 'new_comments' => 'comment_count', - 'last_comment_timestamp' => 'last_comment_timestamp', - 'name' => 'name', - 'score' => 'score', - ), - 'info' => array( - 'project_issue_queue' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'title' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'timestamp' => array( - 'separator' => '', - ), - 'sid' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'priority' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'category' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'version' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'comment_count' => array( - 'sortable' => 1, - 'separator' => '<br />', - ), - 'new_comments' => array( - 'separator' => '', - ), - 'last_comment_timestamp' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'name' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'score' => array( - 'sortable' => 1, - 'separator' => '', - ), - ), - 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', - )); - $handler = $view->new_display('page', 'Page', 'page_1'); - $handler->override_option('path', 'project/issues/user'); - $handler->override_option('menu', array( - 'type' => 'normal', - 'title' => 'My issues', - 'description' => '', - 'weight' => '0', - 'name' => 'navigation', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler = $view->new_display('feed', 'Feed', 'feed_1'); - $handler->override_option('style_plugin', 'rss'); - $handler->override_option('style_options', array( - 'mission_description' => FALSE, - 'description' => '', - )); - $handler->override_option('row_plugin', 'node_rss'); - $handler->override_option('path', 'project/issues/user/%/feed'); - $handler->override_option('menu', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - 'name' => 'navigation', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler->override_option('displays', array( - 'page_1' => 'page_1', - 'default' => 0, - )); - $handler->override_option('sitename_title', FALSE); - - $views[$view->name] = $view; - - - // ------------------------------------------ - // Issues across all projects owned by a user - // ------------------------------------------ - $view = new view; - $view->name = 'project_issue_user_projects'; - $view->description = "Project issues for a specific user's projects"; - $view->tag = 'Project issue'; - $view->view_php = ''; - $view->base_table = 'node'; - $view->is_cacheable = FALSE; - $view->api_version = 2; - $view->disabled = FALSE; - $handler = $view->new_display('default', 'Defaults', 'default'); - $handler->override_option('relationships', array( - 'assigned' => array( - 'label' => 'Assigned user', - 'required' => 1, - 'id' => 'assigned', - 'table' => 'project_issues', - 'field' => 'assigned', - 'relationship' => 'none', - ), - 'rid' => array( - 'label' => 'Version', - 'required' => 0, - 'id' => 'rid', - 'table' => 'project_issues', - 'field' => 'rid', - 'relationship' => 'none', - ), - 'pid' => array( - 'label' => 'Project node', - 'required' => 1, - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - ), - )); - $fields = array( - 'project_issue_queue' => array( - 'label' => 'Project', - 'link_type' => 'issues', - 'exclude' => 0, - 'id' => 'project_issue_queue', - 'table' => 'node', - 'field' => 'project_issue_queue', - 'relationship' => 'pid', - ), - 'title' => array( - 'label' => 'Summary', - 'link_to_node' => 1, - 'exclude' => 0, - 'id' => 'title', - 'table' => 'node', - 'field' => 'title', - 'relationship' => 'none', - ), - 'timestamp' => array( - 'label' => '', - 'alter' => array(), - 'link_to_node' => 0, - 'comments' => 0, - 'exclude' => 0, - 'id' => 'timestamp', - 'table' => 'history_user', - 'field' => 'timestamp', - 'relationship' => 'none', - ), - 'sid' => array( - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - ), - 'priority' => array( - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - ), - 'category' => array( - 'label' => 'Category', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - 'version' => array( - 'label' => 'Version', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'version', - 'table' => 'project_release_nodes', - 'field' => 'version', - 'relationship' => 'rid', - ), - 'comment_count' => array( - 'label' => 'Replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'exclude' => 0, - 'id' => 'comment_count', - 'table' => 'node_comment_statistics', - 'field' => 'comment_count', - 'relationship' => 'none', - ), - 'new_comments' => array( - 'label' => '', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => ' new', - 'link_to_comment' => 1, - 'no_empty' => 1, - 'exclude' => 0, - 'id' => 'new_comments', - 'table' => 'node', - 'field' => 'new_comments', - 'relationship' => 'none', - ), - 'last_comment_timestamp' => array( - 'label' => 'Last updated', - 'date_format' => 'raw time ago', - 'custom_date_format' => '', - 'exclude' => 0, - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ), - 'name' => array( - 'label' => 'Assigned to', - 'link_to_user' => 1, - 'overwrite_anonymous' => 1, - 'anonymous_text' => '', - 'exclude' => 0, - 'id' => 'name', - 'table' => 'users', - 'field' => 'name', - 'relationship' => 'assigned', - ), - ); - if (module_exists('search')) { - $fields['score'] = array( - 'label' => 'Score', - 'alter' => array(), - 'set_precision' => 1, - 'precision' => '3', - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'alternate_sort' => 'last_comment_timestamp', - 'alternate_order' => 'desc', - 'exclude' => 0, - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('fields', $fields); - $sorts['last_comment_timestamp'] = array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ); - if (module_exists('search')) { - $sorts['score'] = array( - 'order' => 'DESC', - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('sorts', $sorts); - $handler->override_option('arguments', array( - 'uid' => array( - 'default_action' => 'default', - 'style_plugin' => 'default_summary', - 'style_options' => array(), - 'wildcard' => 'all', - 'wildcard_substitution' => 'All', - 'title' => 'Projects by %1', - 'default_argument_type' => 'current_user', - 'default_argument' => '', - 'validate_type' => 'user', - 'validate_fail' => 'not found', - 'break_phrase' => 0, - 'not' => 0, - 'id' => 'uid', - 'table' => 'users', - 'field' => 'uid', - 'relationship' => 'pid', - 'default_options_div_prefix' => '', - 'default_argument_user' => 0, - 'default_argument_fixed' => '', - 'default_argument_php' => '', - 'validate_user_argument_type' => 'either', - 'validate_user_restrict_roles' => 1, - 'validate_user_roles' => array('2' => 2), - ), - )); - $filters = array( - 'status_extra' => array( - 'operator' => '=', - 'value' => '', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'status_extra', - 'table' => 'node', - 'field' => 'status_extra', - 'relationship' => 'none', - ), - 'pid' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'operator' => 'pid_op', - 'label' => 'Project', - 'use_operator' => 0, - 'identifier' => 'projects', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'widget' => 'select', - 'project_source' => 'owner', - 'project_uid_argument' => 'uid', - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - 'relationship' => 'none', - ), - 'sid' => array( - 'operator' => 'in', - 'value' => array( - 'Open' => 'Open', - ), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'sid_op', - 'identifier' => 'status', - 'label' => 'Status', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - 'relationship' => 'none', - ), - 'priority' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'priority_op', - 'identifier' => 'priorities', - 'label' => 'Priority', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - 'relationship' => 'none', - ), - 'category' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'category_op', - 'identifier' => 'categories', - 'label' => 'Category', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - ); - if (module_exists('search')) { - $search_filter['keys'] = array( - 'operator' => 'optional', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'keys_op', - 'identifier' => 'text', - 'label' => 'Search for', - 'optional' => 1, - 'remember' => 0, - ), - 'id' => 'keys', - 'table' => 'search_index', - 'field' => 'keys', - 'relationship' => 'none', - ); - $filters = $search_filter + $filters; - } - $handler->override_option('filters', $filters); - $handler->override_option('access', array( - 'type' => 'project_issue_access_per_user_queue', - 'project_issue_user_argument' => 'uid', - )); - $handler->override_option('empty', 'No issues match your criteria.'); - $handler->override_option('empty_format', '1'); - $handler->override_option('items_per_page', 50); - $handler->override_option('use_pager', '1'); - $handler->override_option('style_plugin', 'project_issue_table'); - $handler->override_option('style_options', array( - 'grouping' => '', - 'override' => 1, - 'sticky' => 1, - 'order' => 'desc', - 'columns' => array( - 'project_issue_queue' => 'project_issue_queue', - 'title' => 'title', - 'timestamp' => 'title', - 'sid' => 'sid', - 'priority' => 'priority', - 'category' => 'category', - 'version' => 'version', - 'comment_count' => 'comment_count', - 'new_comments' => 'comment_count', - 'last_comment_timestamp' => 'last_comment_timestamp', - 'name' => 'name', - 'score' => 'score', - ), - 'info' => array( - 'project_issue_queue' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'title' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'timestamp' => array( - 'separator' => '', - ), - 'sid' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'priority' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'category' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'version' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'comment_count' => array( - 'sortable' => 1, - 'separator' => '<br />', - ), - 'new_comments' => array( - 'separator' => '', - ), - 'last_comment_timestamp' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'name' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'score' => array( - 'sortable' => 1, - 'separator' => '', - ), - ), - 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', - )); - $handler = $view->new_display('page', 'Page', 'page_1'); - $handler->override_option('path', 'project/user'); - $handler->override_option('menu', array( - 'type' => 'normal', - 'title' => 'My projects', - 'description' => '', - 'weight' => '0', - 'name' => 'navigation', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler = $view->new_display('feed', 'Feed', 'feed_1'); - $handler->override_option('style_plugin', 'rss'); - $handler->override_option('style_options', array( - 'mission_description' => FALSE, - 'description' => '', - )); - $handler->override_option('row_plugin', 'node_rss'); - $handler->override_option('row_options', array( - 'item_length' => 'default', - )); - $handler->override_option('path', 'project/user/%/feed'); - $handler->override_option('menu', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - 'name' => 'navigation', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler->override_option('displays', array( - 'page_1' => 'page_1', - 'default' => 0, - )); - $handler->override_option('sitename_title', FALSE); - - $views[$view->name] = $view; - - - // ------------------------------------------ - // Advanced issue search for all projects - // ------------------------------------------ - $view = new view; - $view->name = 'project_issue_search_all'; - $view->description = 'Project issue advanced search for all projects'; - $view->tag = 'Project issue'; - $view->view_php = ''; - $view->base_table = 'node'; - $view->is_cacheable = FALSE; - $view->api_version = 2; - $view->disabled = FALSE; - $handler = $view->new_display('default', 'Defaults', 'default'); - $handler->override_option('relationships', array( - 'assigned' => array( - 'label' => 'Assigned user', - 'required' => 1, - 'id' => 'assigned', - 'table' => 'project_issues', - 'field' => 'assigned', - 'relationship' => 'none', - ), - 'rid' => array( - 'label' => 'Version', - 'required' => 0, - 'id' => 'rid', - 'table' => 'project_issues', - 'field' => 'rid', - 'relationship' => 'none', - ), - 'pid' => array( - 'label' => 'Project node', - 'required' => 1, - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - ), - )); - $fields = array( - 'project_issue_queue' => array( - 'label' => 'Project', - 'link_type' => 'search', - 'exclude' => 0, - 'id' => 'project_issue_queue', - 'table' => 'node', - 'field' => 'project_issue_queue', - 'relationship' => 'pid', - ), - 'title' => array( - 'label' => 'Summary', - 'link_to_node' => 1, - 'exclude' => 0, - 'id' => 'title', - 'table' => 'node', - 'field' => 'title', - 'relationship' => 'none', - ), - 'timestamp' => array( - 'label' => '', - 'alter' => array(), - 'link_to_node' => 0, - 'comments' => 0, - 'exclude' => 0, - 'id' => 'timestamp', - 'table' => 'history_user', - 'field' => 'timestamp', - 'relationship' => 'none', - ), - 'sid' => array( - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - ), - 'priority' => array( - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - ), - 'category' => array( - 'label' => 'Category', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - 'version' => array( - 'label' => 'Version', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'version', - 'table' => 'project_release_nodes', - 'field' => 'version', - 'relationship' => 'rid', - ), - 'comment_count' => array( - 'label' => 'Replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'exclude' => 0, - 'id' => 'comment_count', - 'table' => 'node_comment_statistics', - 'field' => 'comment_count', - 'relationship' => 'none', - ), - 'new_comments' => array( - 'label' => 'New replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => ' new', - 'link_to_comment' => 1, - 'no_empty' => 1, - 'exclude' => 0, - 'id' => 'new_comments', - 'table' => 'node', - 'field' => 'new_comments', - 'relationship' => 'none', - ), - 'last_comment_timestamp' => array( - 'label' => 'Last updated', - 'date_format' => 'raw time ago', - 'custom_date_format' => '', - 'exclude' => 0, - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ), - 'name' => array( - 'label' => 'Assigned to', - 'link_to_user' => 1, - 'overwrite_anonymous' => 1, - 'anonymous_text' => '', - 'exclude' => 0, - 'id' => 'name', - 'table' => 'users', - 'field' => 'name', - 'relationship' => 'assigned', - ), - ); - if (module_exists('search')) { - $fields['score'] = array( - 'label' => 'Score', - 'alter' => array(), - 'set_precision' => 1, - 'precision' => '3', - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'alternate_sort' => 'last_comment_timestamp', - 'alternate_order' => 'desc', - 'exclude' => 0, - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('fields', $fields); - $sorts['last_comment_timestamp'] = array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ); - if (module_exists('search')) { - $sorts['score'] = array( - 'order' => 'DESC', - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('sorts', $sorts); - $filters = array( - 'status_extra' => array( - 'operator' => '=', - 'value' => '', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'status_extra', - 'table' => 'node', - 'field' => 'status_extra', - 'relationship' => 'none', - ), - 'pid' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'operator' => 'pid_op', - 'label' => 'Project', - 'use_operator' => 0, - 'identifier' => 'projects', - 'optional' => 1, - 'single' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'widget' => 'textfield', - 'project_source' => 'all', - 'project_uid_argument' => '', - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - 'relationship' => 'none', - ), - 'uid' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'uid_op', - 'identifier' => 'assigned', - 'label' => 'Assigned', - 'optional' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'uid', - 'table' => 'users', - 'field' => 'uid', - 'relationship' => 'assigned', - ), - 'uid_1' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'uid_1_op', - 'identifier' => 'submitted', - 'label' => 'Submitted by', - 'optional' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'uid_1', - 'table' => 'users', - 'field' => 'uid', - 'relationship' => 'none', - ), - 'uid_touch' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'uid_touch_op', - 'identifier' => 'participant', - 'label' => 'Participant', - 'optional' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'uid_touch', - 'table' => 'node', - 'field' => 'uid_touch', - 'relationship' => 'none', - ), - 'sid' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'sid_op', - 'identifier' => 'status', - 'label' => 'Status', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - 'relationship' => 'none', - ), - 'priority' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'priority_op', - 'identifier' => 'priorities', - 'label' => 'Priority', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - 'relationship' => 'none', - ), - 'category' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'category_op', - 'identifier' => 'categories', - 'label' => 'Category', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - ); - if (module_exists('search')) { - $search_filter['keys'] = array( - 'operator' => 'optional', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'keys_op', - 'identifier' => 'text', - 'label' => 'Search for', - 'optional' => 1, - 'remember' => 0, - ), - 'id' => 'keys', - 'table' => 'search_index', - 'field' => 'keys', - 'relationship' => 'none', - ); - $filters = $search_filter + $filters; - } - _project_issue_views_add_taxonomy_filters($filters); - $handler->override_option('filters', $filters); - $handler->override_option('access', array( - 'type' => 'none', - )); - $handler->override_option('title', 'Search issues for all projects'); - $handler->override_option('empty', 'No issues match your criteria.'); - $handler->override_option('empty_format', '1'); - $handler->override_option('items_per_page', 50); - $handler->override_option('use_pager', '1'); - $handler->override_option('style_plugin', 'project_issue_table'); - $handler->override_option('style_options', array( - 'grouping' => '', - 'override' => 1, - 'sticky' => 1, - 'order' => 'desc', - 'columns' => array( - 'project_issue_queue' => 'project_issue_queue', - 'title' => 'title', - 'timestamp' => 'title', - 'sid' => 'sid', - 'priority' => 'priority', - 'category' => 'category', - 'version' => 'version', - 'comment_count' => 'comment_count', - 'new_comments' => 'comment_count', - 'last_comment_timestamp' => 'last_comment_timestamp', - 'name' => 'name', - 'score' => 'score', - ), - 'info' => array( - 'project_issue_queue' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'title' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'timestamp' => array( - 'separator' => '', - ), - 'sid' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'priority' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'category' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'version' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'comment_count' => array( - 'sortable' => 1, - 'separator' => '<br />', - ), - 'new_comments' => array( - 'separator' => '', - ), - 'last_comment_timestamp' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'name' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'score' => array( - 'sortable' => 1, - 'separator' => '', - ), - ), - 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', - )); - $handler = $view->new_display('page', 'Page', 'page_1'); - $handler->override_option('path', 'project/issues/search'); - $handler->override_option('menu', array( - 'type' => 'normal', - 'title' => 'Advanced search', - 'description' => '', - 'weight' => '0', - 'name' => 'navigation', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler = $view->new_display('feed', 'Feed', 'feed_1'); - $handler->override_option('sorts', array( - 'last_comment_timestamp' => array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'override' => array( - 'button' => 'Use default', - ), - 'relationship' => 'none', - ), - )); - $handler->override_option('style_plugin', 'rss'); - $handler->override_option('style_options', array( - 'mission_description' => FALSE, - 'description' => '', - )); - $handler->override_option('row_plugin', 'node_rss'); - $handler->override_option('path', 'project/issues/search/rss'); - $handler->override_option('menu', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - 'name' => '', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler->override_option('displays', array( - 'page_1' => 'page_1', - 'default' => 0, - )); - $handler->override_option('sitename_title', FALSE); - - $views[$view->name] = $view; - - - // -------------------------------------------- - // Advanced issue search for a specific project - // -------------------------------------------- - $view = new view; - $view->name = 'project_issue_search_project'; - $view->description = 'Project issue advanced search for specific projects'; - $view->tag = 'Project issue'; - $view->view_php = ''; - $view->base_table = 'node'; - $view->is_cacheable = FALSE; - $view->api_version = 2; - $view->disabled = FALSE; - $handler = $view->new_display('default', 'Defaults', 'default'); - $handler->override_option('relationships', array( - 'assigned' => array( - 'label' => 'Assigned user', - 'required' => 1, - 'id' => 'assigned', - 'table' => 'project_issues', - 'field' => 'assigned', - 'relationship' => 'none', - ), - 'rid' => array( - 'label' => 'Version', - 'required' => 0, - 'id' => 'rid', - 'table' => 'project_issues', - 'field' => 'rid', - 'relationship' => 'none', - ), - 'pid' => array( - 'label' => 'Project node', - 'required' => 1, - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - ), - )); - $fields = array( - 'title' => array( - 'label' => 'Summary', - 'link_to_node' => 1, - 'exclude' => 0, - 'id' => 'title', - 'table' => 'node', - 'field' => 'title', - 'relationship' => 'none', - ), - 'timestamp' => array( - 'label' => '', - 'alter' => array(), - 'link_to_node' => 0, - 'comments' => 0, - 'exclude' => 0, - 'id' => 'timestamp', - 'table' => 'history_user', - 'field' => 'timestamp', - 'relationship' => 'none', - ), - 'sid' => array( - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - ), - 'priority' => array( - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - ), - 'category' => array( - 'label' => 'Category', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - 'version' => array( - 'label' => 'Version', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'version', - 'table' => 'project_release_nodes', - 'field' => 'version', - 'relationship' => 'rid', - ), - 'component' => array( - 'label' => 'Component', - 'link_to_node' => 0, - 'exclude' => 0, - 'id' => 'component', - 'table' => 'project_issues', - 'field' => 'component', - 'relationship' => 'none', - ), - 'comment_count' => array( - 'label' => 'Replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'exclude' => 0, - 'id' => 'comment_count', - 'table' => 'node_comment_statistics', - 'field' => 'comment_count', - 'relationship' => 'none', - ), - 'new_comments' => array( - 'label' => 'New replies', - 'set_precision' => FALSE, - 'precision' => 0, - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => ' new', - 'link_to_comment' => 1, - 'no_empty' => 1, - 'exclude' => 0, - 'id' => 'new_comments', - 'table' => 'node', - 'field' => 'new_comments', - 'relationship' => 'none', - ), - 'last_comment_timestamp' => array( - 'label' => 'Last updated', - 'date_format' => 'raw time ago', - 'custom_date_format' => '', - 'exclude' => 0, - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ), - 'name' => array( - 'label' => 'Assigned to', - 'link_to_user' => 1, - 'overwrite_anonymous' => 1, - 'anonymous_text' => '', - 'exclude' => 0, - 'id' => 'name', - 'table' => 'users', - 'field' => 'name', - 'relationship' => 'assigned', - ), - ); - if (module_exists('search')) { - $fields['score'] = array( - 'label' => 'Score', - 'alter' => array(), - 'set_precision' => 1, - 'precision' => '3', - 'decimal' => '.', - 'separator' => ',', - 'prefix' => '', - 'suffix' => '', - 'alternate_sort' => 'last_comment_timestamp', - 'alternate_order' => 'desc', - 'exclude' => 0, - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('fields', $fields); - $handler->override_option('arguments', array( - 'pid' => array( - 'default_action' => 'not found', - 'style_plugin' => 'default_summary', - 'style_options' => array(), - 'wildcard' => '', - 'wildcard_substitution' => '', - 'title' => 'Search issues for %1', - 'default_argument_type' => 'fixed', - 'default_argument' => '', - 'validate_type' => 'project_nid', - 'validate_fail' => 'not found', - 'break_phrase' => 0, - 'not' => 0, - 'id' => 'pid', - 'table' => 'project_issues', - 'field' => 'pid', - 'relationship' => 'none', - 'default_options_div_prefix' => '', - 'default_argument_user' => 0, - 'default_argument_fixed' => '', - 'default_argument_php' => '', - 'validate_argument_node_type' => array(), - 'validate_argument_node_access' => 0, - 'validate_argument_nid_type' => 'nid', - 'validate_argument_vocabulary' => array(), - 'validate_argument_type' => 'tid', - 'validate_argument_project_term_vocabulary' => array( - '1' => 0, - ), - 'validate_argument_project_term_argument_type' => 'tid', - 'validate_argument_project_term_argument_action_top_without' => 'pass', - 'validate_argument_project_term_argument_action_top_with' => 'pass', - 'validate_argument_project_term_argument_action_child' => 'pass', - 'validate_argument_php' => '', - ), - )); - $sorts['last_comment_timestamp'] = array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'relationship' => 'none', - ); - if (module_exists('search')) { - $sorts['score'] = array( - 'order' => 'DESC', - 'id' => 'score', - 'table' => 'search_index', - 'field' => 'score', - 'relationship' => 'none', - ); - } - $handler->override_option('sorts', $sorts); - $filters = array( - 'status_extra' => array( - 'operator' => '=', - 'value' => '', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'status_extra', - 'table' => 'node', - 'field' => 'status_extra', - 'relationship' => 'none', - ), - 'uid' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'uid_op', - 'identifier' => 'assigned', - 'label' => 'Assigned', - 'optional' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'uid', - 'table' => 'users', - 'field' => 'uid', - 'relationship' => 'assigned', - ), - 'uid_1' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'uid_1_op', - 'identifier' => 'submitted', - 'label' => 'Submitted by', - 'optional' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'uid_1', - 'table' => 'users', - 'field' => 'uid', - 'relationship' => 'none', - ), - 'uid_touch' => array( - 'operator' => 'in', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'uid_touch_op', - 'identifier' => 'participant', - 'label' => 'Participant', - 'optional' => 1, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'uid_touch', - 'table' => 'node', - 'field' => 'uid_touch', - 'relationship' => 'none', - ), - 'sid' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'sid_op', - 'identifier' => 'status', - 'label' => 'Status', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'sid', - 'table' => 'project_issues', - 'field' => 'sid', - 'relationship' => 'none', - ), - 'priority' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'priority_op', - 'identifier' => 'priorities', - 'label' => 'Priority', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'priority', - 'table' => 'project_issues', - 'field' => 'priority', - 'relationship' => 'none', - ), - 'category' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'category_op', - 'identifier' => 'categories', - 'label' => 'Category', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'category', - 'table' => 'project_issues', - 'field' => 'category', - 'relationship' => 'none', - ), - 'rid' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'rid_op', - 'identifier' => 'version', - 'label' => 'Version', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'rid', - 'table' => 'project_issues', - 'field' => 'rid', - 'relationship' => 'none', - ), - 'component' => array( - 'operator' => 'in', - 'value' => array(), - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'component_op', - 'identifier' => 'component', - 'label' => 'Component', - 'optional' => 1, - 'single' => 0, - 'remember' => 0, - 'reduce' => 0, - ), - 'id' => 'component', - 'table' => 'project_issues', - 'field' => 'component', - 'relationship' => 'none', - ), - ); - if (module_exists('search')) { - $search_filter['keys'] = array( - 'operator' => 'optional', - 'value' => '', - 'group' => '0', - 'exposed' => TRUE, - 'expose' => array( - 'use_operator' => 0, - 'operator' => 'keys_op', - 'identifier' => 'text', - 'label' => 'Search for', - 'optional' => 1, - 'remember' => 0, - ), - 'id' => 'keys', - 'table' => 'search_index', - 'field' => 'keys', - 'relationship' => 'none', - ); - $filters = $search_filter + $filters; + // Search the "default_views" directory for files ending in .view.php. + $files = file_scan_directory(drupal_get_path('module', 'project_issue'). '/views/default_views', 'view.php'); + foreach ($files as $absolute => $file) { + require_once $absolute; + if (isset($view)) { + // $file->name has the ".php" stripped off, but still has the ".view". + $view_name = substr($file->name, 0, strrpos($file->name, '.')); + $views[$view_name] = $view; + } } - _project_issue_views_add_taxonomy_filters($filters); - $handler->override_option('filters', $filters); - $handler->override_option('access', array( - 'type' => 'none', - )); - $handler->override_option('title', 'Search issues for a project'); - $handler->override_option('empty', 'No issues match your criteria.'); - $handler->override_option('empty_format', '1'); - $handler->override_option('items_per_page', 50); - $handler->override_option('use_pager', '1'); - $handler->override_option('style_plugin', 'project_issue_table'); - $handler->override_option('style_options', array( - 'grouping' => '', - 'override' => 1, - 'sticky' => 1, - 'order' => 'desc', - 'columns' => array( - 'title' => 'title', - 'timestamp' => 'title', - 'sid' => 'sid', - 'priority' => 'priority', - 'category' => 'category', - 'version' => 'version', - 'component' => 'component', - 'comment_count' => 'comment_count', - 'new_comments' => 'comment_count', - 'last_comment_timestamp' => 'last_comment_timestamp', - 'name' => 'name', - 'score' => 'score', - ), - 'info' => array( - 'title' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'timestamp' => array( - 'separator' => '', - ), - 'sid' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'priority' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'category' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'version' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'component' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'comment_count' => array( - 'sortable' => 1, - 'separator' => '<br />', - ), - 'new_comments' => array( - 'separator' => '', - ), - 'last_comment_timestamp' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'name' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'score' => array( - 'sortable' => 1, - 'separator' => '', - ), - ), - 'default' => module_exists('search') ? 'score' : 'last_comment_timestamp', - )); - $handler = $view->new_display('page', 'Page', 'page_1'); - $handler->override_option('path', 'project/issues/search/%'); - $handler->override_option('menu', array( - 'type' => 'none', - 'title' => 'Advanced search', - 'description' => '', - 'weight' => '0', - 'name' => 'navigation', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler = $view->new_display('feed', 'Feed', 'feed_1'); - $handler->override_option('sorts', array( - 'last_comment_timestamp' => array( - 'order' => 'DESC', - 'granularity' => 'second', - 'id' => 'last_comment_timestamp', - 'table' => 'node_comment_statistics', - 'field' => 'last_comment_timestamp', - 'override' => array( - 'button' => 'Use default', - ), - 'relationship' => 'none', - ), - )); - $handler->override_option('style_plugin', 'rss'); - $handler->override_option('style_options', array( - 'mission_description' => FALSE, - 'description' => '', - )); - $handler->override_option('row_plugin', 'node_rss'); - $handler->override_option('path', 'project/issues/search/%/rss'); - $handler->override_option('menu', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - 'name' => '', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - )); - $handler->override_option('displays', array( - 'page_1' => 'page_1', - 'default' => 0, - )); - $handler->override_option('sitename_title', FALSE); - - $views[$view->name] = $view; - return $views; } /** * Add exposed filters for every taxonomy vocabulary for project_issue nodes. + * + * This is a helper function used by a few of the default view definitions. */ function _project_issue_views_add_taxonomy_filters(&$filters) { if (!module_exists('taxonomy')) { return; } $issue_vocabularies = taxonomy_get_vocabularies('project_issue'); $i = 0; foreach ($issue_vocabularies as $vid => $vocab) { $view_key = 'tid'; if ($i) { $view_key .= "_$i"; } $i++; $identifier = project_issue_views_filter_identifier($vocab->name); $filters[$view_key] = array( 'operator' => 'or', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'tid_op', 'identifier' => $identifier, 'label' => check_plain($vocab->name), 'optional' => 1, 'single' => 1, 'remember' => 0, ), 'type' => 'textfield', 'vid' => $vid, 'id' => 'tid', 'table' => 'term_node', 'field' => 'tid', 'hierarchy' => 0, 'relationship' => 'none', 'reduce_duplicates' => 1, ); } }
Br3nda/drupal-module-project_issue
4bce12e0478a5dcd3502bdf40abbbfc4f8ff79a4
#405478 by dww: Proper page split of project_issue: Moved code related to hook_nodeapi() for project_project nodes from project_issue.module into includes/project_node.inc.
diff --git a/includes/project_node.inc b/includes/project_node.inc new file mode 100644 index 0000000..f5d1c45 --- /dev/null +++ b/includes/project_node.inc @@ -0,0 +1,71 @@ +<?php +// $Id: project_node.inc,v 1.1 2009/06/18 03:30:22 dww Exp $ + +/** + * hook_nodeapi implementation specific to "project_project" nodes + * (from the project.module) + * @see project_issue_nodeapi(). + */ +function project_issue_project_nodeapi(&$node, $op, $arg) { + switch ($op) { + case 'load': + project_issue_project_load($node, $arg); + break; + + case 'insert': + project_issue_project_insert($node); + break; + + case 'delete': + project_issue_project_delete($node); + break; + } +} + +function project_issue_project_load(&$node, $arg) { + $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $node->nid)); + // If nothing loaded, bail immediately + if (!$project) { + return $node; + } + $node->project_issue = array(); + $node->project_issue['components'] = unserialize($project->components); + $node->project_issue['default_component'] = $project->default_component; + $node->project_issue['mail_copy_filter'] = unserialize($project->mail_copy_filter); + $node->project_issue['mail_copy_filter_state'] = unserialize($project->mail_copy_filter_state); + foreach (array('issues', 'help', 'mail_digest', 'mail_copy', 'mail_reminder') as $field) { + $node->project_issue[$field] = $project->$field; + } + return $node; +} + +function project_issue_project_insert($node) { + // Setup reasonable defaults: enable issue tracker and standard + // components. If maintainers want to change these, (or any of the + // other issue-related project settings, like the email notifications) + // they'd use the "issues" subtab of the project edit tab (since none + // of these fields are present on the initial project add form). + $node->project_issue['issues'] = 1; + + // Default components are saved in the variables table as a plain + // string instead of as a serialized array since they come out of + // a textarea on a system settings form. Convert here to the more + // desirable serialized array for storage per-project. + $defaults = array(t('Code'), t('Documentation'), t('Miscellaneous'), t('User interface')); + $components = variable_get('project_issue_default_components', implode("\n", $defaults)); + $default_components = explode("\n", str_replace("\r", '', $components)); + + $node->project_issue['components'] = serialize($default_components); + db_query("INSERT INTO {project_issue_projects} (nid, issues, components) VALUES (%d, %d, '%s')", $node->nid, $node->project_issue['issues'], $node->project_issue['components']); +} + +function project_issue_project_delete($node) { + // Delete all associated issues. + $issues = db_query('SELECT nid FROM {project_issues} WHERE pid = %d', $node->nid); + while ($issue = db_fetch_object($issues)) { + node_delete($issue->nid); + } + db_query('DELETE FROM {project_issue_projects} WHERE nid = %d', $node->nid); + db_query('DELETE FROM {project_subscriptions} WHERE nid = %d', $node->nid); +} + diff --git a/project_issue.module b/project_issue.module index 087cbc1..e323622 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,1604 +1,1537 @@ <?php -// $Id: project_issue.module,v 1.172 2009/06/18 03:28:55 dww Exp $ +// $Id: project_issue.module,v 1.173 2009/06/18 03:30:22 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); foreach (array('comment', 'mail') as $file) { module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': + module_load_include('inc', 'project_issue', 'includes/project_node'); project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implement hook_delete() for project issue nodes. */ function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } /** * Implement hook_form() for project issue nodes. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_form($node, $form_state, $include_metadata_fields); } /** * Implement hook_validate() for project issue nodes. */ function project_issue_validate($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_validate($node); } /** * Implement hook_insert() for project issue nodes. */ function project_issue_insert($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_insert($node); } /** * Implement hook_view() for project issue nodes. */ function project_issue_view($node, $teaser = FALSE, $page = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_view'); return _project_issue_view($node, $teaser, $page); } /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { foreach ($nids as $nid) { project_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } -/** - * hook_nodeapi implementation specific to "project_project" nodes - * (from the project.module) - * @see project_issue_nodeapi(). - */ -function project_issue_project_nodeapi(&$node, $op, $arg) { - switch ($op) { - case 'load': - project_issue_project_load($node, $arg); - break; - - case 'insert': - project_issue_project_insert($node); - break; - - case 'delete': - project_issue_project_delete($node); - break; - } -} - -function project_issue_project_load(&$node, $arg) { - $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $node->nid)); - // If nothing loaded, bail immediately - if (!$project) { - return $node; - } - $node->project_issue = array(); - $node->project_issue['components'] = unserialize($project->components); - $node->project_issue['default_component'] = $project->default_component; - $node->project_issue['mail_copy_filter'] = unserialize($project->mail_copy_filter); - $node->project_issue['mail_copy_filter_state'] = unserialize($project->mail_copy_filter_state); - foreach (array('issues', 'help', 'mail_digest', 'mail_copy', 'mail_reminder') as $field) { - $node->project_issue[$field] = $project->$field; - } - return $node; -} - -function project_issue_project_insert($node) { - // Setup reasonable defaults: enable issue tracker and standard - // components. If maintainers want to change these, (or any of the - // other issue-related project settings, like the email notifications) - // they'd use the "issues" subtab of the project edit tab (since none - // of these fields are present on the initial project add form). - $node->project_issue['issues'] = 1; - - // Default components are saved in the variables table as a plain - // string instead of as a serialized array since they come out of - // a textarea on a system settings form. Convert here to the more - // desirable serialized array for storage per-project. - $defaults = array(t('Code'), t('Documentation'), t('Miscellaneous'), t('User interface')); - $components = variable_get('project_issue_default_components', implode("\n", $defaults)); - $default_components = explode("\n", str_replace("\r", '', $components)); - - $node->project_issue['components'] = serialize($default_components); - db_query("INSERT INTO {project_issue_projects} (nid, issues, components) VALUES (%d, %d, '%s')", $node->nid, $node->project_issue['issues'], $node->project_issue['components']); -} - -function project_issue_project_delete($node) { - // Delete all associated issues. - $issues = db_query('SELECT nid FROM {project_issues} WHERE pid = %d', $node->nid); - while ($issue = db_fetch_object($issues)) { - node_delete($issue->nid); - } - db_query('DELETE FROM {project_issue_projects} WHERE nid = %d', $node->nid); - db_query('DELETE FROM {project_subscriptions} WHERE nid = %d', $node->nid); -} - /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes)); } $output = '<span class="project-issue-status-'. $node->project_issue['sid'] .' project-issue-status-info">'. $link; if ($include_assigned && !empty($username)) { $output .= ' <span class="project-issue-assigned-user">'. t('Assigned to: @username', array('@username' => $username)) .'</span>'; } $output .= '</span>'; return $output; } /** * Implementation of hook_form_filter_tips(). * @ingroup project_issue_filter */ function project_issue_filter_tips($delta, $format, $long = FALSE) { if ($long) { return t("References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically, with the title of the issue appended. The status of the issue is shown on hover. If '@' is appended (e.g. [#1234@]), the user the issue is assigned to will also be printed."); } else { return t('Project issue numbers (ex. [#12345]) turn into links automatically.'); } } /** * Implementation of hook_filter(). * @ingroup project_issue_filter */ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { switch ($op) { case 'list': return array(0 => t('Project Issue to link filter')); case 'description': return t('Converts references to project issues (in the form of [#12345]) into links. Caching should be disabled if node access control modules are used.'); case 'no cache': return FALSE; case 'prepare': return $text; case 'process': $regex = '(?:(?<!\w)\[#\d+(?:-\d+)?(@)?\](?!\w))|<pre>.*?<\/pre>|<code>.*?<\/code>|<a(?:[^>"\']|"[^"]*"|\'[^\']*\')*>.*?<\/a>'; $text = preg_replace_callback("/$regex/", 'project_issue_link_filter_callback', $text); return $text; } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); if (!empty($grants)) { $conflict_grants = TRUE; } $allowed_roles = user_roles(FALSE, 'access project issues'); if (!isset($allowed_roles[DRUPAL_ANONYMOUS_RID])) { $conflict_anonymous = TRUE; } foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if ($conflict_grants && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } } $variables['class'] .= " project-issue"; } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), );
Br3nda/drupal-module-project_issue
bd8fa2c576f80be6decf51b91ea6ba5d44248ce5
#405478 by dww: Proper page split of project_issue: Moved all code needed when viewing an issue node from issue.inc into includes/issue_node_view.inc. The core hook_view() implementation now lives in project_issue.module, but it's just a thin wrapper to load issue_node_view.inc and invoke a (quite large) private helper method to do the heavy lifting.
diff --git a/includes/issue_node_view.inc b/includes/issue_node_view.inc new file mode 100644 index 0000000..73da3d1 --- /dev/null +++ b/includes/issue_node_view.inc @@ -0,0 +1,182 @@ +<?php +// $Id: issue_node_view.inc,v 1.1 2009/06/18 03:28:55 dww Exp $ + +/** + * @file + * Code required when viewing an issue node. + */ + +/** + * Private helper to implement hook_view(). + */ +function _project_issue_view($node, $teaser = FALSE, $page = FALSE) { + $node = node_prepare($node, $teaser); + + if (!$teaser && ($page || project_issue_is_comment_reply())) { + + $node->content['#prefix'] = '<div class="project-issue">'; + $node->content['#suffix'] = '</div>'; + + $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); + $release->nid = $node->project_issue['rid']; + if (module_exists('project_release')) { + $release = project_release_load($release); + } + $assigned = ($node->project_issue['assigned'] && ($account = user_load(array('uid' => $node->project_issue['assigned']))) ? $account->name : t('Unassigned')); + + $current_data = array(); + $current_data['pid'] = array( + 'label' => t('Project'), + 'current' => $project->title, + ); + if (!empty($release->project_release['version'])) { + $current_data['rid'] = array( + 'label' => t('Version'), + 'current' => $release->project_release['version'], + ); + } + $current_data['component'] = array( + 'label' => t('Component'), + 'current' => $node->project_issue['component'], + ); + $current_data['category'] = array( + 'label' => t('Category'), + 'current' => project_issue_category($node->project_issue['category'], 0), + ); + $current_data['priority'] = array( + 'label' => t('Priority'), + 'current' => project_issue_priority($node->project_issue['priority']), + ); + $current_data['assigned'] = array( + 'label' => t('Assigned'), + 'current' => $assigned, + ); + $current_data['sid'] = array( + 'label' => t('Status'), + 'current' => project_issue_state($node->project_issue['sid']), + ); + + // Allow modules to alter the metadata displayed in the table on the actual + // issue node itself (at the very top of the issue). Modules should accept + // the $current_data parameter by reference and add additional + // elements for additional lines in the table. + // + // Modules implementing this hook should take the following parameters: + // @param $view + // A string representing the metadata view being generated. For the issue + // node main table, this will be 'current'. + // @param $node + // The project_issue node object. + // @param $current_data + // An associative array of rows in the project issue metadata table that + // will be displayed, with the following key/value pairs: + // 'label' => The metadata label. + // 'current' => The current metadata value. + // This parameter should be accepted by reference. + foreach (module_implements('project_issue_metadata') as $module) { + $function = $module .'_project_issue_metadata'; + $function('current', $node, $current_data); + } + + $node->content['project_issue_summary'] = array( + '#value' => theme('project_issue_summary', $current_data, project_issue_internal_links($node)), + '#weight' => -5, + ); + + $node->content['project_issue_header'] = array( + '#value' => '<div class="header">'. t('Description') .'</div>', + '#weight' => -3, + ); + + project_issue_set_breadcrumb($node, $project); + } + return $node; +} + +/** + * Themes the metadata table and internal page links for issue nodes. + * + * @param $current_data + * An array of current issue data for the metadata table. + * @param $summary_links + * An array of internal page links. + * @return + * An HTML string of the summary section. + */ +function theme_project_issue_summary($current_data, $summary_links) { + $allowed_tags = array('a', 'em', 'strong', 'div', 'span'); + // Fields that should be rendered as plain text, not filtered HTML. + $plain_fields = array('title', 'pid', 'rid'); + + $rows = array(); + foreach ($current_data as $name => $values) { + $row = array(); + $row[] = filter_xss($values['label'], $allowed_tags) .':'; + if (in_array($name, $plain_fields)) { + $row[] = check_plain($values['current']); + } + else { + $row[] = filter_xss($values['current'], $allowed_tags); + } + $rows[] = $row; + } + + $output = '<div id="project-summary-container" class="clear-block">'; + $output .= '<div id="project-issue-summary-table" class="summary">'. theme('table', array(), $rows) .'</div>'; + if (!empty($summary_links)) { + $output .= '<div id="project-issue-summary-links">'. theme('item_list', $summary_links, t('Jump to:'), 'ul', array('class' => 'internal-links')) .'</div>'; + } + $output .= '</div>'; + + return $output; +} + +/** + * Generates internal page links for issue pages. + * + * @param $node + * The issue node. + * @return + * An array of internal page links. + */ +function project_issue_internal_links($node) { + $links = array(); + + if ($node->comment != COMMENT_NODE_DISABLED) { + // Link to the first unread, or most recent comment. + if (comment_num_new($node->nid)) { + // There are unread replies; link to first unread comment. + $links[] = l(t('First unread comment'), "node/$node->nid", array('fragment' => 'new')); + } + else { + // No unread replies; link to most recent comment. + $comment_cid = db_result(db_query_range("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {node} n on pic.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY pic.cid DESC", $node->nid, 0, 1)); + if ($comment_cid) { + $links[] = l(t('Most recent comment'), "node/$node->nid", array('fragment' => "comment-$comment_cid")); + } + } + // Link for most recent patch. + $file_cid = db_result(db_query_range("SELECT cu.cid FROM {comment_upload} cu INNER JOIN {node} n on cu.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY cu.fid DESC", $node->nid, 0, 1)); + if ($file_cid) { + $links[] = l(t('Most recent attachment'), "node/$node->nid", array('fragment' => "comment-$file_cid")); + } + } + + // Link straight to comment form. + if ($node->comment == COMMENT_NODE_READ_WRITE && (user_access('post comments') || user_access('post comments without approval'))) { + // TODO: This conditional needs to be ripped out in D6. + $comment_form_location = isset($node->project_issue['comment_form_location']) ? $node->project_issue['comment_form_location'] : variable_get('comment_form_location_' . $node->type, COMMENT_FORM_SEPARATE_PAGE); + + // Comment form isn't on the page, link to the comment reply page. + if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) { + $links[] = l(t('Add new comment'), "comment/reply/$node->nid"); + } + // Comment form is on the page, generate an internal page link for it. + else { + $links[] = l(t('Add new comment'), "node/$node->nid", array('fragment' => "comment-form")); + } + } + + return $links; +} + diff --git a/issue.inc b/issue.inc index bb98bc2..d3776b3 100644 --- a/issue.inc +++ b/issue.inc @@ -1,539 +1,368 @@ <?php -// $Id: issue.inc,v 1.353 2009/06/18 03:27:57 dww Exp $ +// $Id: issue.inc,v 1.354 2009/06/18 03:28:55 dww Exp $ /** * JS callback method to return updated elements on the issue form. * This function is called when someone changes the "Project" selector. */ function project_issue_update_project() { $form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); // Rebuild the form and cache it again. $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); // These used to be path arguments. Now they arrive via form element. $issue_nid = $form['nid']['#value']; $pid = $form_state['values']['project_info']['pid']; $rid = isset($form_state['values']['project_info']['rid']) ? $form_state['values']['project_info']['rid'] : 0; $cid = $form_state['values']['cid']; $assigned_uid = $form_state['values']['project_info']['assigned']; $project_info = $form['original_issue']['project_info']; // Only generate release stuff if the project_release module is enabled. if (module_exists('project_release')) { $project->nid = $pid; if ($releases = project_release_get_releases($project, 0)) { $old_version = db_result(db_query("SELECT version FROM {project_release_nodes} WHERE nid = %d", $rid)); $releases = array(t('<none>')) + $releases; // Since the value of releases is by nid, try to match release // based on the label instead. $default = 0; foreach ($releases as $key => $label) { if ($old_version == $label) { $default = $key; } } // Element is tree'd here to match the original form layout. $project_info['#tree'] = TRUE; $project_info['rid']['#options'] = $releases; $project_info['rid']['#disabled'] = FALSE; if (!empty($default)) { $project_info['rid']['#value'] = $default; $project_info['rid']['#default_value'] = $default; } } else { $project_info['rid']['#disabled'] = TRUE; $project_info['rid']['#options'] = array(); } } // Assigned. if (is_numeric($issue_nid)) { $issue = node_load(array('nid' => $issue_nid, 'type' => 'project_issue')); } else { // @TODO: This case should not ever be hit until // http://drupal.org/node/197281 lands. $issue = new stdClass; } $issue->project_issue['pid'] = $pid; $assigned_choices = project_issue_assigned_choices($issue); $project_info['assigned']['#default_value'] = $assigned_uid; $project_info['assigned']['#options'] = $assigned_choices; // Components. $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $pid)); $components = array(); if ($project->components) { $components = array(t('<none>')); foreach (unserialize($project->components) as $component) { $component = check_plain($component); $components[$component] = $component; } } $project_info['component']['#default_value'] = $cid; $project_info['component']['#options'] = $components; // Build the HTML output for the component select. $output = theme('status_messages') . drupal_render($project_info); drupal_json(array('status' => TRUE, 'data' => $output)); exit; } /** * Build an array of users to whom an issue may be assigned. * * @param $issue * The fully loaded issue node object. * @return * A keyed array in the form uid => name containing users * to whom an issue may be assigned. */ function project_issue_assigned_choices($issue) { // Setup the array of choices for who the issue is assigned to. $assigned = array(); foreach (module_implements('project_issue_assignees') as $module) { $function = "{$module}_project_issue_assignees"; $function($assigned, $issue); } natcasesort($assigned); $assigned = array(0 => empty($issue->project_issue['assigned']) ? t('Unassigned') : t('Unassign')) + $assigned; return $assigned; } -function project_issue_view($node, $teaser = false, $page = false) { - $node = node_prepare($node, $teaser); - - if (!$teaser && ($page || project_issue_is_comment_reply())) { - - $node->content['#prefix'] = '<div class="project-issue">'; - $node->content['#suffix'] = '</div>'; - - $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); - $release->nid = $node->project_issue['rid']; - if (module_exists('project_release')) { - $release = project_release_load($release); - } - $assigned = ($node->project_issue['assigned'] && ($account = user_load(array('uid' => $node->project_issue['assigned']))) ? $account->name : t('Unassigned')); - - $current_data = array(); - $current_data['pid'] = array( - 'label' => t('Project'), - 'current' => $project->title, - ); - if (!empty($release->project_release['version'])) { - $current_data['rid'] = array( - 'label' => t('Version'), - 'current' => $release->project_release['version'], - ); - } - $current_data['component'] = array( - 'label' => t('Component'), - 'current' => $node->project_issue['component'], - ); - $current_data['category'] = array( - 'label' => t('Category'), - 'current' => project_issue_category($node->project_issue['category'], 0), - ); - $current_data['priority'] = array( - 'label' => t('Priority'), - 'current' => project_issue_priority($node->project_issue['priority']), - ); - $current_data['assigned'] = array( - 'label' => t('Assigned'), - 'current' => $assigned, - ); - $current_data['sid'] = array( - 'label' => t('Status'), - 'current' => project_issue_state($node->project_issue['sid']), - ); - - // Allow modules to alter the metadata displayed in the table on the actual - // issue node itself (at the very top of the issue). Modules should accept - // the $current_data parameter by reference and add additional - // elements for additional lines in the table. - // - // Modules implementing this hook should take the following parameters: - // @param $view - // A string representing the metadata view being generated. For the issue - // node main table, this will be 'current'. - // @param $node - // The project_issue node object. - // @param $current_data - // An associative array of rows in the project issue metadata table that - // will be displayed, with the following key/value pairs: - // 'label' => The metadata label. - // 'current' => The current metadata value. - // This parameter should be accepted by reference. - foreach (module_implements('project_issue_metadata') as $module) { - $function = $module .'_project_issue_metadata'; - $function('current', $node, $current_data); - } - - $node->content['project_issue_summary'] = array( - '#value' => theme('project_issue_summary', $current_data, project_issue_internal_links($node)), - '#weight' => -5, - ); - - $node->content['project_issue_header'] = array( - '#value' => '<div class="header">'. t('Description') .'</div>', - '#weight' => -3, - ); - - project_issue_set_breadcrumb($node, $project); - } - return $node; -} - /** * Implementation of hook_project_issue_assignees(). * * This hook is used to modify the list of 'Assigned' users when creating or * commenting on an issue. * * @param $assigned * An array of key => value pairs in the format of uid => name that represents * the list of users that the issue may be assigned to. This parameter * is passed by reference so the hook may make changes, such as adding or * removing elements. * @param $node * The node object for the issue. */ function project_issue_project_issue_assignees(&$assigned, $node) { global $user; if ($user->uid) { if (isset($node->project_issue['assigned']) && $user->uid != $node->project_issue['assigned']) { // Assigned to someone else, add the currently assigned user. $account = user_load(array('uid' => $node->project_issue['assigned'])); $assigned[$node->project_issue['assigned']] = $account->name; } // Always let the person replying assign it to themselves. $assigned[$user->uid] = $user->name; } if (user_access('assign and be assigned project issues')) { // All users are included if either anon or auth user has the perm. if (db_result(db_query("SELECT rid FROM {permission} WHERE perm LIKE '%%%s%%' AND rid IN(%d, %d)", 'assign and be assigned project issues', DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $result = db_query("SELECT uid, name FROM {users}"); } else { $result = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {role} r ON ur.rid = r.rid INNER JOIN {permission} p ON p.rid = r.rid WHERE p.perm LIKE '%%%s%%'", 'assign and be assigned project issues'); } while ($assignee = db_fetch_object($result)) { $assigned[$assignee->uid] = $assignee->name; } } } -/** - * Themes the metadata table and internal page links for issue nodes. - * - * @param $current_data - * An array of current issue data for the metadata table. - * @param $summary_links - * An array of internal page links. - * @return - * An HTML string of the summary section. - */ -function theme_project_issue_summary($current_data, $summary_links) { - $allowed_tags = array('a', 'em', 'strong', 'div', 'span'); - // Fields that should be rendered as plain text, not filtered HTML. - $plain_fields = array('title', 'pid', 'rid'); - - $rows = array(); - foreach ($current_data as $name => $values) { - $row = array(); - $row[] = filter_xss($values['label'], $allowed_tags) .':'; - if (in_array($name, $plain_fields)) { - $row[] = check_plain($values['current']); - } - else { - $row[] = filter_xss($values['current'], $allowed_tags); - } - $rows[] = $row; - } - - $output = '<div id="project-summary-container" class="clear-block">'; - $output .= '<div id="project-issue-summary-table" class="summary">'. theme('table', array(), $rows) .'</div>'; - if (!empty($summary_links)) { - $output .= '<div id="project-issue-summary-links">'. theme('item_list', $summary_links, t('Jump to:'), 'ul', array('class' => 'internal-links')) .'</div>'; - } - $output .= '</div>'; - - return $output; -} - -/** - * Generates internal page links for issue pages. - * - * @param $node - * The issue node. - * @return - * An array of internal page links. - */ -function project_issue_internal_links($node) { - $links = array(); - - if ($node->comment != COMMENT_NODE_DISABLED) { - // Link to the first unread, or most recent comment. - if (comment_num_new($node->nid)) { - // There are unread replies; link to first unread comment. - $links[] = l(t('First unread comment'), "node/$node->nid", array('fragment' => 'new')); - } - else { - // No unread replies; link to most recent comment. - $comment_cid = db_result(db_query_range("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {node} n on pic.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY pic.cid DESC", $node->nid, 0, 1)); - if ($comment_cid) { - $links[] = l(t('Most recent comment'), "node/$node->nid", array('fragment' => "comment-$comment_cid")); - } - } - // Link for most recent patch. - $file_cid = db_result(db_query_range("SELECT cu.cid FROM {comment_upload} cu INNER JOIN {node} n on cu.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY cu.fid DESC", $node->nid, 0, 1)); - if ($file_cid) { - $links[] = l(t('Most recent attachment'), "node/$node->nid", array('fragment' => "comment-$file_cid")); - } - } - - // Link straight to comment form. - if ($node->comment == COMMENT_NODE_READ_WRITE && (user_access('post comments') || user_access('post comments without approval'))) { - // TODO: This conditional needs to be ripped out in D6. - $comment_form_location = isset($node->project_issue['comment_form_location']) ? $node->project_issue['comment_form_location'] : variable_get('comment_form_location_' . $node->type, COMMENT_FORM_SEPARATE_PAGE); - - // Comment form isn't on the page, link to the comment reply page. - if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) { - $links[] = l(t('Add new comment'), "comment/reply/$node->nid"); - } - // Comment form is on the page, generate an internal page link for it. - else { - $links[] = l(t('Add new comment'), "node/$node->nid", array('fragment' => "comment-form")); - } - } - - return $links; -} - // Support stuff /** * Return information about project issue state values. * * @param $sid * Integer state id to return information about, or 0 for all states. * @param $restrict * Boolean to determine if states should be restricted based on the * permissions of the current user or $account if that parameter * is provided. * @param $is_author * Boolean that indicates if the current user is the author of the * issue, which can potentially grant a wider selection of states. * @param $current_sid * The current integer state id for the issue. * @param $defaults * Boolean to request the states used for default issue queries. * @param $account * Account of a user to pass to user_access() for access checking. * This parameter will have no effect unless $restrict is also * set to TRUE. * * @return * An array of states (sid as key, name as value) that match the * given filters, or the name of the requested state. * NOTE: The state name returned is raw text, and should be filtered via * check_plain() or filter_xss() before being printed as HTML output. */ function project_issue_state($sid = 0, $restrict = false, $is_author = false, $current_sid = 0, $defaults = false, $account = NULL) { static $options; if (!$options) { $result = db_query('SELECT * FROM {project_issue_state} ORDER BY weight'); while ($state = db_fetch_object($result)) { $options[] = $state; } } foreach($options as $state) { if ($restrict) { // Check if user has access, // or if status is default status and therefore available to all, // or if user is original issue author and author has access, // or if the issue is already in a state, even if the user doesn't have // access to that state themselves. if (user_access('set issue status '. str_replace("'", "", $state->name), $account) || user_access('administer projects', $account) || ($state->sid == variable_get('project_issue_default_state', 1)) || ($state->author_has && $is_author) || ($state->sid == $current_sid) ) { $states[$state->sid] = $state->name; } } else if ($defaults) { if ($state->default_query) { $states[$state->sid] = $state->name; } } else { $states[$state->sid] = $state->name; } } return $sid ? $states[$sid] : $states; } /** * Return an array of state ids that should be used for default queries. */ function project_issue_default_states() { static $defaults; if (empty($defaults)) { $states = project_issue_state(0, false, false, 0, true); $defaults = !empty($states) ? array_keys($states) : array(1, 2, 4); } return $defaults; } function project_issue_priority($priority = 0) { $priorities = array(1 => t('critical'), t('normal'), t('minor')); return $priority ? $priorities[$priority] : $priorities; } function project_issue_category($category = 0, $plural = 1) { if ($plural) { $categories = array('bug' => t('bug reports'), 'task' => t('tasks'), 'feature' => t('feature requests'), 'support' => t('support requests')); } else { $categories = array('bug' => t('bug report'), 'task' => t('task'), 'feature' => t('feature request'), 'support' => t('support request')); } return $category ? $categories[$category] : $categories; } function project_issue_count($pid) { $state = array(); $result = db_query('SELECT p.sid, count(p.sid) AS count FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid WHERE n.status = 1 AND p.pid = %d GROUP BY p.sid', $pid); while ($data = db_fetch_object($result)) { $state[$data->sid] = $data->count; } return $state; } /** * Return the HTML to use for the links at the top of issue query pages. * * @param $links * Array of links, indexed by the action ('create', 'search', etc). * * @see project_issue_query_result() * @see theme_links() */ function theme_project_issue_query_result_links($links) { return theme('links', $links); } /** * Provide an array of project issue summary fields. * @param $context * The context in which the fields will be displayed. * 'web' for project_issue node and comment summary tables. * 'email' for project_issue notification e-mail messages. */ function project_issue_field_labels($context) { if ($context == 'web') { $labels = array('title' => t('Title')); } else { $labels = array(); } $labels += array( 'pid' => t('Project'), 'rid' => t('Version'), 'component' => t('Component'), 'category' => t('Category'), 'priority' => t('Priority'), 'assigned' => t('Assigned to'), 'sid' => t('Status'), ); if ($context == 'email') { $labels += array( 'name' => t('Reported by'), 'updator' => t('Updated by'), ); } return $labels; } /** * Provide the text displayed to a user for a specific metadata field. * * @param $field * Name of the field. * @param $value * Value of the field. * * @return * Text to display to user. NOTE: This is unfiltered text! If this output is * being sent over the web, you must use check_plain(). */ function project_issue_change_summary($field, $value) { switch ($field) { case 'pid': $project = node_load(array('nid' => $value, 'type' => 'project_project')); return $project->title; case 'category': return $value ? project_issue_category($value, 0) : t('<none>'); case 'priority': return $value ? project_issue_priority($value) : t('<none>'); case 'rid': if ($value) { $release->nid = $value; if (module_exists('project_release')) { $release = project_release_load($release); } else { $release->project_release['version'] = t('Unknown'); } return $release->project_release['version']; } return t('<none>'); case 'assigned': $user = user_load(array('uid' => $value)); return (int) $value === 0 ? variable_get('anonymous', t('Anonymous')) : $user->name; case 'sid': return $value ? project_issue_state($value) : t('<none>'); default: return $value; } } function theme_project_issue_create_forbidden($uri = '') { global $user; if ($user->uid) { return ''; } // We cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages. $destination = "destination=". drupal_urlencode("node/add/project-issue/$uri"); if (variable_get('user_register', 1)) { return t('<a href="@login">Login</a> or <a href="@register">register</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination)))); } else { return t('<a href="@login">Login</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)))); } } diff --git a/project_issue.module b/project_issue.module index 9ea1558..087cbc1 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,1319 +1,1327 @@ <?php -// $Id: project_issue.module,v 1.171 2009/06/18 03:27:57 dww Exp $ +// $Id: project_issue.module,v 1.172 2009/06/18 03:28:55 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); foreach (array('comment', 'mail') as $file) { module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( - 'file' => 'issue.inc', + 'file' => 'includes/issue_node_view.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implement hook_delete() for project issue nodes. */ function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } /** * Implement hook_form() for project issue nodes. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_form($node, $form_state, $include_metadata_fields); } /** * Implement hook_validate() for project issue nodes. */ function project_issue_validate($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_validate($node); } /** * Implement hook_insert() for project issue nodes. */ function project_issue_insert($node) { module_load_include('inc', 'project_issue', 'includes/issue_node_form'); return _project_issue_insert($node); } +/** + * Implement hook_view() for project issue nodes. + */ +function project_issue_view($node, $teaser = FALSE, $page = FALSE) { + module_load_include('inc', 'project_issue', 'includes/issue_node_view'); + return _project_issue_view($node, $teaser, $page); +} + /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { foreach ($nids as $nid) { project_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * hook_nodeapi implementation specific to "project_project" nodes * (from the project.module) * @see project_issue_nodeapi(). */ function project_issue_project_nodeapi(&$node, $op, $arg) { switch ($op) { case 'load': project_issue_project_load($node, $arg); break; case 'insert': project_issue_project_insert($node); break; case 'delete': project_issue_project_delete($node); break; } } function project_issue_project_load(&$node, $arg) { $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $node->nid)); // If nothing loaded, bail immediately if (!$project) { return $node; } $node->project_issue = array(); $node->project_issue['components'] = unserialize($project->components); $node->project_issue['default_component'] = $project->default_component; $node->project_issue['mail_copy_filter'] = unserialize($project->mail_copy_filter); $node->project_issue['mail_copy_filter_state'] = unserialize($project->mail_copy_filter_state); foreach (array('issues', 'help', 'mail_digest', 'mail_copy', 'mail_reminder') as $field) { $node->project_issue[$field] = $project->$field; } return $node; } function project_issue_project_insert($node) { // Setup reasonable defaults: enable issue tracker and standard // components. If maintainers want to change these, (or any of the // other issue-related project settings, like the email notifications) // they'd use the "issues" subtab of the project edit tab (since none // of these fields are present on the initial project add form). $node->project_issue['issues'] = 1; // Default components are saved in the variables table as a plain // string instead of as a serialized array since they come out of // a textarea on a system settings form. Convert here to the more // desirable serialized array for storage per-project. $defaults = array(t('Code'), t('Documentation'), t('Miscellaneous'), t('User interface')); $components = variable_get('project_issue_default_components', implode("\n", $defaults)); $default_components = explode("\n", str_replace("\r", '', $components)); $node->project_issue['components'] = serialize($default_components); db_query("INSERT INTO {project_issue_projects} (nid, issues, components) VALUES (%d, %d, '%s')", $node->nid, $node->project_issue['issues'], $node->project_issue['components']); } function project_issue_project_delete($node) { // Delete all associated issues. $issues = db_query('SELECT nid FROM {project_issues} WHERE pid = %d', $node->nid); while ($issue = db_fetch_object($issues)) { node_delete($issue->nid); } db_query('DELETE FROM {project_issue_projects} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_subscriptions} WHERE nid = %d', $node->nid); } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes)); } $output = '<span class="project-issue-status-'. $node->project_issue['sid'] .' project-issue-status-info">'. $link; if ($include_assigned && !empty($username)) { $output .= ' <span class="project-issue-assigned-user">'. t('Assigned to: @username', array('@username' => $username)) .'</span>'; } $output .= '</span>'; return $output; } /** * Implementation of hook_form_filter_tips(). * @ingroup project_issue_filter */ function project_issue_filter_tips($delta, $format, $long = FALSE) { if ($long) { return t("References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically, with the title of the issue appended. The status of the issue is shown on hover. If '@' is appended (e.g. [#1234@]), the user the issue is assigned to will also be printed."); } else { return t('Project issue numbers (ex. [#12345]) turn into links automatically.'); } } /** * Implementation of hook_filter(). * @ingroup project_issue_filter */ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { switch ($op) { case 'list': return array(0 => t('Project Issue to link filter')); case 'description': return t('Converts references to project issues (in the form of [#12345]) into links. Caching should be disabled if node access control modules are used.'); case 'no cache': return FALSE; case 'prepare': return $text; case 'process': $regex = '(?:(?<!\w)\[#\d+(?:-\d+)?(@)?\](?!\w))|<pre>.*?<\/pre>|<code>.*?<\/code>|<a(?:[^>"\']|"[^"]*"|\'[^\']*\')*>.*?<\/a>'; $text = preg_replace_callback("/$regex/", 'project_issue_link_filter_callback', $text); return $text; } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); if (!empty($grants)) { $conflict_grants = TRUE; } $allowed_roles = user_roles(FALSE, 'access project issues'); if (!isset($allowed_roles[DRUPAL_ANONYMOUS_RID])) { $conflict_anonymous = TRUE; } foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if ($conflict_grants && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'.
Br3nda/drupal-module-project_issue
ab178bd203d066bf9fbcbd07b97e7918925f8fce
#405478 by dww: Proper page split of project_issue: Moved all code related to the issue node form into includes/issue_node_form.inc from issue.inc. The core node hooks now live in project_issue.module, but hook_form(), hook_validate() and hook_insert() all just load issue_node_form.inc and call private methods in there (since they're pretty huge).
diff --git a/includes/issue_node_form.inc b/includes/issue_node_form.inc new file mode 100644 index 0000000..079526f --- /dev/null +++ b/includes/issue_node_form.inc @@ -0,0 +1,437 @@ +<?php +// $Id: issue_node_form.inc,v 1.1 2009/06/18 03:27:57 dww Exp $ + +/** + * @file + * Code required for the issue node form. + */ + +/** + * Redirect node/add/project_issue/* to node/add/project-issue/*. + */ +function project_issue_add_redirect_page($project = NULL, $category = NULL) { + $path = 'node/add/project-issue'; + if (!empty($project)) { + $path .= "/$project"; + } + if (!empty($category)) { + $path .= "/$category"; + } + drupal_goto($path); +} + +function project_issue_pick_project_page() { + drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); + return drupal_get_form('project_issue_pick_project_form'); +} + +/** + * Form builder for a simple form to select a project when creating a new + * issue (as the first "page", but this is not really a multi-page form). + */ +function project_issue_pick_project_form(&$form_state) { + $form = array(); + + // Fetch a list of all projects. + $uris = NULL; + $projects = array(t('<none>')) + project_projects_select_options($uris); + if (count($projects) == 1) { + drupal_set_message(t('You do not have access to any projects.'), 'error'); + } + + $form['pid'] = array( + '#type' => 'select', + '#title' => t('Project'), + '#options' => $projects, + '#required' => TRUE, + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Next'), + ); + return $form; +} + +function project_issue_pick_project_form_validate($form, &$form_state) { + if (empty($form_state['values']['pid'])) { + form_set_error('pid', t('You must select a project.')); + } + $node = node_load($form_state['values']['pid']); + if (empty($node) || $node->type != 'project_project') { + form_set_error('pid', t('Invalid project selected.')); + } +} + +function project_issue_pick_project_form_submit($form, &$form_state) { + $project = node_load($form_state['values']['pid']); + $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; +} + +/** + * Private helper to implement hook_form(). + * + * Create the project issue node form. + * + * @param $node + * The project issue node object. + * @param $include_metadata_fields + * If set, metadata fields (eg. status, assigned, title) will + * be included in the form regardless of whether $node->nid is set. + * Otherwise, metadata fields will only be included in the form + * if $node->nid is empty. + */ +function _project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { + global $user; + + $defaults = array( + 'rid', + 'component', + 'category', + 'priority', + 'assigned', + 'sid', + ); + + // Set some defaults for new forms. + if (!isset($node->nid)) { + foreach ($defaults as $default) { + $node->project_issue[$default] = 0; + } + } + + // In the case of an issue preview, get our defaults from the submitted form. + // TODO: do we want to #tree our form so we don't need this hack? + if (isset($form_state['node'])) { + foreach ($defaults as $default) { + if (isset($form_state['node'][$default])) { + $node->project_issue[$default] = $form_state['node'][$default]; + } + } + } + + // If this function is being called as a result of CCK building the form + // in content_admin_field_overview_form(), just return an empty array, since + // CCK only grabs the top level fields and this form has none of those anyway. + if (!empty($node->cck_dummy_node_form)) { + return array(); + } + + if (arg(0) == 'node' && arg(1) == 'add') { + $breadcrumb = array(); + $breadcrumb[] = l(t('Home'), NULL); + $breadcrumb[] = l(t('Create content'), 'node/add'); + drupal_set_breadcrumb($breadcrumb); + } + + $default_state = variable_get('project_issue_default_state', 1); + + // Fetch a list of all projects to test for access. + $uris = NULL; + $projects = array(t('<none>')) + project_projects_select_options($uris); + if (count($projects) == 1) { + drupal_set_message(t('You do not have access to any projects.'), 'error'); + drupal_goto('node/add/project-issue'); + return; + } + + // Figure out what project we should use for the issue metadata. + if (!empty($form_state['values']['project_info']['pid'])) { + // The project has been selected in the form itself (e.g. it's been + // changed and we're previewing, etc.) + $pid = $form_state['values']['project_info']['pid']; + } + elseif (!empty($node->project_issue['pid'])) { + // The issue node already knows what project it belongs to. + $pid = $node->project_issue['pid']; + } + else { + // Fallback and try to learn the project from the URL -- evil. + $pid = arg(3); + if (!empty($pid)) { + if (is_numeric($pid)) { + $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); + } + else { + $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); + } + } + $pid = $node->project_issue['pid']; + } + + if (empty($pid)) { + drupal_set_message(t('Invalid project selected.'), 'error'); + drupal_goto('node/add/project-issue'); + } + + // If this issue has already been created and is just being + // edited, we want to prevent any metadata changes. However, allow + // the $include_metadata_fields parameter to override this check. + if ($include_metadata_fields) { + $allow_metadata_changes = TRUE; + } + else { + $allow_metadata_changes = empty($node->nid); + } + + // Load the project and initialize some support arrays. + $project = node_load($pid); + if ($project->type != 'project_project') { + drupal_set_message(t('Invalid project selected.'), 'error'); + // Not sure the best place to go here... + drupal_goto('node/add/project-issue'); + } + if ($allow_metadata_changes) { + if (module_exists('project_release') && isset($node->project_issue['rid']) && + $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { + $releases = array(t('<none>')) + $releases; + } + // Remove releases marked as invalid release nodes for user selection. + foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { + unset($releases[$rid]); + } + // Setup components and default component. + if (!empty($node->project_issue['component'])) { + $default_component = $node->project_issue['component']; + } + else { + $default_component = $project->project_issue['default_component']; + } + $components = empty($default_component) ? array(t('<none>')) : array(); + if ($project->project_issue['components']) { + foreach ($project->project_issue['components'] as $component) { + $component = check_plain($component); + $components[$component] = $component; + } + } + $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); + $priorities = project_issue_priority(); + $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); + $assigned = project_issue_assigned_choices($node); + } + + // Display the site-wide and/or per-project help text. + $site_help = trim(variable_get('project_issue_site_help', '')); + if (!empty($site_help)) { + $form['project_help']['site'] = array( + '#prefix' => '<div class="messages status site">', + '#value' => filter_xss($site_help), + '#suffix' => '</div>', + ); + } + $project_help = trim($project->project_issue['help']); + if (!empty($project_help)) { + $form['project_help']['project'] = array( + '#prefix' => '<div class="messages status project">', + '#value' => filter_xss($project_help), + '#suffix' => '</div>', + ); + } + + if ($allow_metadata_changes) { + $form['project_info'] = array( + '#type' => 'fieldset', + '#title' => t('Project information'), + '#prefix' => '<div class="inline-options">', + '#suffix' => '</div>', + ); + $form['project_info']['project_display'] = array( + '#type' => 'item', + '#title' => t('Project'), + '#value' => check_plain($project->title), + ); + $form['project_info']['pid'] = array( + '#type' => 'value', + '#value' => $node->project_issue['pid'], + ); + if ($releases) { + $form['project_info']['rid'] = array( + '#type' => 'select', + '#title' => t('Version'), + '#default_value' => $node->project_issue['rid'], + '#options' => $releases, + '#required' => TRUE, + ); + } + $form['project_info']['component'] = array( + '#type' => 'select', + '#title' => t('Component'), + '#default_value' => $default_component, + '#options' => $components, + '#required' => TRUE, + ); + $form['issue_info'] = array( + '#type' => 'fieldset', + '#title' => t('Issue information'), + '#prefix' => '<div class="inline-options">', + '#suffix' => '</div>', + ); + $form['issue_info']['category'] = array( + '#type' => 'select', + '#title' => t('Category'), + '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), + '#options' => $categories, + '#required' => TRUE, + ); + $form['issue_info']['priority'] = array( + '#type' => 'select', + '#title' => t('Priority'), + '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, + '#options' => $priorities, + ); + $form['issue_info']['assigned'] = array( + '#type' => 'select', + '#title' => t('Assigned'), + '#default_value' => $node->project_issue['assigned'], + '#options' => $assigned, + ); + if (count($states) > 1) { + $form['issue_info']['sid'] = array( + '#type' => 'select', + '#title' => t('Status'), + '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, + '#options' => $states, + ); + } + else { + $form['issue_info']['sid'] = array( + '#type' => 'hidden', + '#value' => $default_state, + ); + $form['issue_info']['status'] = array( + '#type' => 'item', + '#title' => t('Status'), + '#value' => check_plain(project_issue_state($default_state)), + ); + } + } + + $form['issue_details'] = array( + '#type' => 'fieldset', + '#title' => t('Issue details'), + '#prefix' => '</div><div class="standard">', + ); + + if ($allow_metadata_changes) { + $form['issue_details']['title'] = array( + '#type' => 'textfield', + '#title' => t('Title'), + '#default_value' => $node->title, + '#size' => 60, + '#maxlength' => 128, + '#required' => TRUE, + ); + } + else { + $form['issue_details']['title'] = array( + '#type' => 'value', + '#value' => $node->title, + ); + } + + $form['issue_details']['body'] = array( + '#type' => 'textarea', + '#title' => t('Description'), + '#default_value' => $node->body, + '#rows' => 10, + '#required' => TRUE, + ); + $form['issue_details']['format'] = filter_form($node->format); + + $directory = file_create_path(variable_get('project_directory_issues', 'issues')); + if (!file_check_directory($directory, 0)) { + $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); + if (user_access('administer site configuration')) { + $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); + } + else { + $msg .= ' '. t('Please contact the site administrator.'); + } + drupal_set_message($msg, 'error'); + } + return $form; +} + +/** + * Private helper to implement hook_validate(). + * + * Ensures that the issue node form has valid values for all required fields. + * We use hook_validate() here instead of a #validate handler or even defining + * project_issue_node_form_validate() since if we did, node_form_validate() + * itself would not be invoked, which would lead to all kinds of problems, + * including hook_nodeapi('validate') never being invoked. + * + * @param $node + * An object of form values from the project_issue node form, not a fully + * loaded issue node object. Therefore, the fields are not in the usual + * $node->project_issue array. + */ +function _project_issue_validate($node) { + // If $node->nid is set, that means that the node was being + // edited and not created. If that's the case, the user was + // not presented with any of the metadata fields, so there's no + // need to validate them here. + if (empty($node->nid)) { + if (empty($node->pid)) { + form_set_error('pid', t('You have to specify a valid project.')); + } + elseif ($project = node_load($node->pid)) { + if (module_exists('project_release') && + $releases = project_release_get_releases($project, 0)) { + if (empty($node->rid)) { + form_set_error('rid', t('You have to specify a valid version.')); + } + } + if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { + $node->component = 0; + } + if (empty($node->component)) { + form_set_error('component', t('You have to specify a valid component.')); + } + if (empty($node->category)) { + form_set_error('category', t('You have to specify a valid category.')); + } + } + } +} + +/** + * Private helper to implement hook_insert(). + * + * @param $node + * Object containing form values from the project_issue node form. This is + * NOT a fully loaded $node object, so the issue-related values are directly + * in $node, not in the $node->project_issue array. + */ +function _project_issue_insert($node) { + // Permanently store the original issue states in a serialized array. This + // is a bit yucky, but we need them for proper handling of states workflow. + // The current states need to be stored in {project_issues} as well for + // query efficiency in issue queue searches, and it seems too messy to add a + // bunch of new columns to the {project_issues} table for the original + // states. + $original_issue_data = new stdClass(); + $fields = array( + 'pid' => 0, + 'rid' => 0, + 'component' => '', + 'category' => '', + 'priority' => 0, + 'assigned' => 0, + 'sid' => 0, + 'title' => '', + ); + foreach ($fields as $field => $default) { + // Some of the incoming data may not have the correct default. + if (empty($node->$field)) { + $node->$field = $default; + } + $original_issue_data->$field = $node->$field; + } + + db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); + + // Invalidate the "Issue cockpit" block cache for this project, since the + // new issue will have altered the summary totals. + cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); +} + diff --git a/issue.inc b/issue.inc index 0a660e4..bb98bc2 100644 --- a/issue.inc +++ b/issue.inc @@ -1,959 +1,539 @@ <?php -// $Id: issue.inc,v 1.352 2009/06/18 03:24:59 dww Exp $ +// $Id: issue.inc,v 1.353 2009/06/18 03:27:57 dww Exp $ /** * JS callback method to return updated elements on the issue form. * This function is called when someone changes the "Project" selector. */ function project_issue_update_project() { $form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); // Rebuild the form and cache it again. $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); // These used to be path arguments. Now they arrive via form element. $issue_nid = $form['nid']['#value']; $pid = $form_state['values']['project_info']['pid']; $rid = isset($form_state['values']['project_info']['rid']) ? $form_state['values']['project_info']['rid'] : 0; $cid = $form_state['values']['cid']; $assigned_uid = $form_state['values']['project_info']['assigned']; $project_info = $form['original_issue']['project_info']; // Only generate release stuff if the project_release module is enabled. if (module_exists('project_release')) { $project->nid = $pid; if ($releases = project_release_get_releases($project, 0)) { $old_version = db_result(db_query("SELECT version FROM {project_release_nodes} WHERE nid = %d", $rid)); $releases = array(t('<none>')) + $releases; // Since the value of releases is by nid, try to match release // based on the label instead. $default = 0; foreach ($releases as $key => $label) { if ($old_version == $label) { $default = $key; } } // Element is tree'd here to match the original form layout. $project_info['#tree'] = TRUE; $project_info['rid']['#options'] = $releases; $project_info['rid']['#disabled'] = FALSE; if (!empty($default)) { $project_info['rid']['#value'] = $default; $project_info['rid']['#default_value'] = $default; } } else { $project_info['rid']['#disabled'] = TRUE; $project_info['rid']['#options'] = array(); } } // Assigned. if (is_numeric($issue_nid)) { $issue = node_load(array('nid' => $issue_nid, 'type' => 'project_issue')); } else { // @TODO: This case should not ever be hit until // http://drupal.org/node/197281 lands. $issue = new stdClass; } $issue->project_issue['pid'] = $pid; $assigned_choices = project_issue_assigned_choices($issue); $project_info['assigned']['#default_value'] = $assigned_uid; $project_info['assigned']['#options'] = $assigned_choices; // Components. $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $pid)); $components = array(); if ($project->components) { $components = array(t('<none>')); foreach (unserialize($project->components) as $component) { $component = check_plain($component); $components[$component] = $component; } } $project_info['component']['#default_value'] = $cid; $project_info['component']['#options'] = $components; // Build the HTML output for the component select. $output = theme('status_messages') . drupal_render($project_info); drupal_json(array('status' => TRUE, 'data' => $output)); exit; } -function project_issue_pick_project_page() { - drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); - return drupal_get_form('project_issue_pick_project_form'); -} - -/** - * Form builder for a simple form to select a project when creating a new - * issue (as the first "page", but this is not really a multi-page form). - */ -function project_issue_pick_project_form(&$form_state) { - $form = array(); - - // Fetch a list of all projects. - $uris = NULL; - $projects = array(t('<none>')) + project_projects_select_options($uris); - if (count($projects) == 1) { - drupal_set_message(t('You do not have access to any projects.'), 'error'); - } - - $form['pid'] = array( - '#type' => 'select', - '#title' => t('Project'), - '#options' => $projects, - '#required' => TRUE, - ); - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Next'), - ); - return $form; -} - -function project_issue_pick_project_form_validate($form, &$form_state) { - if (empty($form_state['values']['pid'])) { - form_set_error('pid', t('You must select a project.')); - } - $node = node_load($form_state['values']['pid']); - if (empty($node) || $node->type != 'project_project') { - form_set_error('pid', t('Invalid project selected.')); - } -} - -function project_issue_pick_project_form_submit($form, &$form_state) { - $project = node_load($form_state['values']['pid']); - $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; -} - -/** - * Implementation of hook_form(). - * - * Create the project issue node form. - * - * @param $node - * The project issue node object. - * @param $include_metadata_fields - * If set, metadata fields (eg. status, assigned, title) will - * be included in the form regardless of whether $node->nid is set. - * Otherwise, metadata fields will only be included in the form - * if $node->nid is empty. - */ -function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { - global $user; - - $defaults = array( - 'rid', - 'component', - 'category', - 'priority', - 'assigned', - 'sid', - ); - - // Set some defaults for new forms. - if (!isset($node->nid)) { - foreach ($defaults as $default) { - $node->project_issue[$default] = 0; - } - } - - // In the case of an issue preview, get our defaults from the submitted form. - // TODO: do we want to #tree our form so we don't need this hack? - if (isset($form_state['node'])) { - foreach ($defaults as $default) { - if (isset($form_state['node'][$default])) { - $node->project_issue[$default] = $form_state['node'][$default]; - } - } - } - - // If this function is being called as a result of CCK building the form - // in content_admin_field_overview_form(), just return an empty array, since - // CCK only grabs the top level fields and this form has none of those anyway. - if (!empty($node->cck_dummy_node_form)) { - return array(); - } - - if (arg(0) == 'node' && arg(1) == 'add') { - $breadcrumb = array(); - $breadcrumb[] = l(t('Home'), NULL); - $breadcrumb[] = l(t('Create content'), 'node/add'); - drupal_set_breadcrumb($breadcrumb); - } - - $default_state = variable_get('project_issue_default_state', 1); - - // Fetch a list of all projects to test for access. - $uris = NULL; - $projects = array(t('<none>')) + project_projects_select_options($uris); - if (count($projects) == 1) { - drupal_set_message(t('You do not have access to any projects.'), 'error'); - drupal_goto('node/add/project-issue'); - return; - } - - // Figure out what project we should use for the issue metadata. - if (!empty($form_state['values']['project_info']['pid'])) { - // The project has been selected in the form itself (e.g. it's been - // changed and we're previewing, etc.) - $pid = $form_state['values']['project_info']['pid']; - } - elseif (!empty($node->project_issue['pid'])) { - // The issue node already knows what project it belongs to. - $pid = $node->project_issue['pid']; - } - else { - // Fallback and try to learn the project from the URL -- evil. - $pid = arg(3); - if (!empty($pid)) { - if (is_numeric($pid)) { - $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); - } - else { - $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); - } - } - $pid = $node->project_issue['pid']; - } - - if (empty($pid)) { - drupal_set_message(t('Invalid project selected.'), 'error'); - drupal_goto('node/add/project-issue'); - } - - // If this issue has already been created and is just being - // edited, we want to prevent any metadata changes. However, allow - // the $include_metadata_fields parameter to override this check. - if ($include_metadata_fields) { - $allow_metadata_changes = TRUE; - } - else { - $allow_metadata_changes = empty($node->nid); - } - - // Load the project and initialize some support arrays. - $project = node_load($pid); - if ($project->type != 'project_project') { - drupal_set_message(t('Invalid project selected.'), 'error'); - // Not sure the best place to go here... - drupal_goto('node/add/project-issue'); - } - if ($allow_metadata_changes) { - if (module_exists('project_release') && isset($node->project_issue['rid']) && - $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { - $releases = array(t('<none>')) + $releases; - } - // Remove releases marked as invalid release nodes for user selection. - foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { - unset($releases[$rid]); - } - // Setup components and default component. - if (!empty($node->project_issue['component'])) { - $default_component = $node->project_issue['component']; - } - else { - $default_component = $project->project_issue['default_component']; - } - $components = empty($default_component) ? array(t('<none>')) : array(); - if ($project->project_issue['components']) { - foreach ($project->project_issue['components'] as $component) { - $component = check_plain($component); - $components[$component] = $component; - } - } - $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); - $priorities = project_issue_priority(); - $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); - $assigned = project_issue_assigned_choices($node); - } - - // Display the site-wide and/or per-project help text. - $site_help = trim(variable_get('project_issue_site_help', '')); - if (!empty($site_help)) { - $form['project_help']['site'] = array( - '#prefix' => '<div class="messages status site">', - '#value' => filter_xss($site_help), - '#suffix' => '</div>', - ); - } - $project_help = trim($project->project_issue['help']); - if (!empty($project_help)) { - $form['project_help']['project'] = array( - '#prefix' => '<div class="messages status project">', - '#value' => filter_xss($project_help), - '#suffix' => '</div>', - ); - } - - if ($allow_metadata_changes) { - $form['project_info'] = array( - '#type' => 'fieldset', - '#title' => t('Project information'), - '#prefix' => '<div class="inline-options">', - '#suffix' => '</div>', - ); - $form['project_info']['project_display'] = array( - '#type' => 'item', - '#title' => t('Project'), - '#value' => check_plain($project->title), - ); - $form['project_info']['pid'] = array( - '#type' => 'value', - '#value' => $node->project_issue['pid'], - ); - if ($releases) { - $form['project_info']['rid'] = array( - '#type' => 'select', - '#title' => t('Version'), - '#default_value' => $node->project_issue['rid'], - '#options' => $releases, - '#required' => TRUE, - ); - } - $form['project_info']['component'] = array( - '#type' => 'select', - '#title' => t('Component'), - '#default_value' => $default_component, - '#options' => $components, - '#required' => TRUE, - ); - $form['issue_info'] = array( - '#type' => 'fieldset', - '#title' => t('Issue information'), - '#prefix' => '<div class="inline-options">', - '#suffix' => '</div>', - ); - $form['issue_info']['category'] = array( - '#type' => 'select', - '#title' => t('Category'), - '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), - '#options' => $categories, - '#required' => TRUE, - ); - $form['issue_info']['priority'] = array( - '#type' => 'select', - '#title' => t('Priority'), - '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, - '#options' => $priorities, - ); - $form['issue_info']['assigned'] = array( - '#type' => 'select', - '#title' => t('Assigned'), - '#default_value' => $node->project_issue['assigned'], - '#options' => $assigned, - ); - if (count($states) > 1) { - $form['issue_info']['sid'] = array( - '#type' => 'select', - '#title' => t('Status'), - '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, - '#options' => $states, - ); - } - else { - $form['issue_info']['sid'] = array( - '#type' => 'hidden', - '#value' => $default_state, - ); - $form['issue_info']['status'] = array( - '#type' => 'item', - '#title' => t('Status'), - '#value' => check_plain(project_issue_state($default_state)), - ); - } - } - - $form['issue_details'] = array( - '#type' => 'fieldset', - '#title' => t('Issue details'), - '#prefix' => '</div><div class="standard">', - ); - - if ($allow_metadata_changes) { - $form['issue_details']['title'] = array( - '#type' => 'textfield', - '#title' => t('Title'), - '#default_value' => $node->title, - '#size' => 60, - '#maxlength' => 128, - '#required' => TRUE, - ); - } - else { - $form['issue_details']['title'] = array( - '#type' => 'value', - '#value' => $node->title, - ); - } - - $form['issue_details']['body'] = array( - '#type' => 'textarea', - '#title' => t('Description'), - '#default_value' => $node->body, - '#rows' => 10, - '#required' => TRUE, - ); - $form['issue_details']['format'] = filter_form($node->format); - - $directory = file_create_path(variable_get('project_directory_issues', 'issues')); - if (!file_check_directory($directory, 0)) { - $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); - if (user_access('administer site configuration')) { - $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); - } - else { - $msg .= ' '. t('Please contact the site administrator.'); - } - drupal_set_message($msg, 'error'); - } - return $form; -} - /** * Build an array of users to whom an issue may be assigned. * * @param $issue * The fully loaded issue node object. * @return * A keyed array in the form uid => name containing users * to whom an issue may be assigned. */ function project_issue_assigned_choices($issue) { // Setup the array of choices for who the issue is assigned to. $assigned = array(); foreach (module_implements('project_issue_assignees') as $module) { $function = "{$module}_project_issue_assignees"; $function($assigned, $issue); } natcasesort($assigned); $assigned = array(0 => empty($issue->project_issue['assigned']) ? t('Unassigned') : t('Unassign')) + $assigned; return $assigned; } -/** - * Implmentation of hook_validate(). - * - * Ensures that the issue node form has valid values for all required fields. - * We use hook_validate() here instead of a #validate handler or even defining - * project_issue_node_form_validate() since if we did, node_form_validate() - * itself would not be invoked, which would lead to all kinds of problems, - * including hook_nodeapi('validate') never being invoked. - * - * @param $node - * An object of form values from the project_issue node form, not a fully - * loaded issue node object. Therefore, the fields are not in the usual - * $node->project_issue array. - */ -function project_issue_validate($node) { - // If $node->nid is set, that means that the node was being - // edited and not created. If that's the case, the user was - // not presented with any of the metadata fields, so there's no - // need to validate them here. - if (empty($node->nid)) { - if (empty($node->pid)) { - form_set_error('pid', t('You have to specify a valid project.')); - } - elseif ($project = node_load($node->pid)) { - if (module_exists('project_release') && - $releases = project_release_get_releases($project, 0)) { - if (empty($node->rid)) { - form_set_error('rid', t('You have to specify a valid version.')); - } - } - if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { - $node->component = 0; - } - if (empty($node->component)) { - form_set_error('component', t('You have to specify a valid component.')); - } - if (empty($node->category)) { - form_set_error('category', t('You have to specify a valid category.')); - } - } - } -} - function project_issue_view($node, $teaser = false, $page = false) { $node = node_prepare($node, $teaser); if (!$teaser && ($page || project_issue_is_comment_reply())) { $node->content['#prefix'] = '<div class="project-issue">'; $node->content['#suffix'] = '</div>'; $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); $release->nid = $node->project_issue['rid']; if (module_exists('project_release')) { $release = project_release_load($release); } $assigned = ($node->project_issue['assigned'] && ($account = user_load(array('uid' => $node->project_issue['assigned']))) ? $account->name : t('Unassigned')); $current_data = array(); $current_data['pid'] = array( 'label' => t('Project'), 'current' => $project->title, ); if (!empty($release->project_release['version'])) { $current_data['rid'] = array( 'label' => t('Version'), 'current' => $release->project_release['version'], ); } $current_data['component'] = array( 'label' => t('Component'), 'current' => $node->project_issue['component'], ); $current_data['category'] = array( 'label' => t('Category'), 'current' => project_issue_category($node->project_issue['category'], 0), ); $current_data['priority'] = array( 'label' => t('Priority'), 'current' => project_issue_priority($node->project_issue['priority']), ); $current_data['assigned'] = array( 'label' => t('Assigned'), 'current' => $assigned, ); $current_data['sid'] = array( 'label' => t('Status'), 'current' => project_issue_state($node->project_issue['sid']), ); // Allow modules to alter the metadata displayed in the table on the actual // issue node itself (at the very top of the issue). Modules should accept // the $current_data parameter by reference and add additional // elements for additional lines in the table. // // Modules implementing this hook should take the following parameters: // @param $view // A string representing the metadata view being generated. For the issue // node main table, this will be 'current'. // @param $node // The project_issue node object. // @param $current_data // An associative array of rows in the project issue metadata table that // will be displayed, with the following key/value pairs: // 'label' => The metadata label. // 'current' => The current metadata value. // This parameter should be accepted by reference. foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('current', $node, $current_data); } $node->content['project_issue_summary'] = array( '#value' => theme('project_issue_summary', $current_data, project_issue_internal_links($node)), '#weight' => -5, ); $node->content['project_issue_header'] = array( '#value' => '<div class="header">'. t('Description') .'</div>', '#weight' => -3, ); project_issue_set_breadcrumb($node, $project); } return $node; } /** * Implementation of hook_project_issue_assignees(). * * This hook is used to modify the list of 'Assigned' users when creating or * commenting on an issue. * * @param $assigned * An array of key => value pairs in the format of uid => name that represents * the list of users that the issue may be assigned to. This parameter * is passed by reference so the hook may make changes, such as adding or * removing elements. * @param $node * The node object for the issue. */ function project_issue_project_issue_assignees(&$assigned, $node) { global $user; if ($user->uid) { if (isset($node->project_issue['assigned']) && $user->uid != $node->project_issue['assigned']) { // Assigned to someone else, add the currently assigned user. $account = user_load(array('uid' => $node->project_issue['assigned'])); $assigned[$node->project_issue['assigned']] = $account->name; } // Always let the person replying assign it to themselves. $assigned[$user->uid] = $user->name; } if (user_access('assign and be assigned project issues')) { // All users are included if either anon or auth user has the perm. if (db_result(db_query("SELECT rid FROM {permission} WHERE perm LIKE '%%%s%%' AND rid IN(%d, %d)", 'assign and be assigned project issues', DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $result = db_query("SELECT uid, name FROM {users}"); } else { $result = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {role} r ON ur.rid = r.rid INNER JOIN {permission} p ON p.rid = r.rid WHERE p.perm LIKE '%%%s%%'", 'assign and be assigned project issues'); } while ($assignee = db_fetch_object($result)) { $assigned[$assignee->uid] = $assignee->name; } } } /** * Themes the metadata table and internal page links for issue nodes. * * @param $current_data * An array of current issue data for the metadata table. * @param $summary_links * An array of internal page links. * @return * An HTML string of the summary section. */ function theme_project_issue_summary($current_data, $summary_links) { $allowed_tags = array('a', 'em', 'strong', 'div', 'span'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); $rows = array(); foreach ($current_data as $name => $values) { $row = array(); $row[] = filter_xss($values['label'], $allowed_tags) .':'; if (in_array($name, $plain_fields)) { $row[] = check_plain($values['current']); } else { $row[] = filter_xss($values['current'], $allowed_tags); } $rows[] = $row; } $output = '<div id="project-summary-container" class="clear-block">'; $output .= '<div id="project-issue-summary-table" class="summary">'. theme('table', array(), $rows) .'</div>'; if (!empty($summary_links)) { $output .= '<div id="project-issue-summary-links">'. theme('item_list', $summary_links, t('Jump to:'), 'ul', array('class' => 'internal-links')) .'</div>'; } $output .= '</div>'; return $output; } /** * Generates internal page links for issue pages. * * @param $node * The issue node. * @return * An array of internal page links. */ function project_issue_internal_links($node) { $links = array(); if ($node->comment != COMMENT_NODE_DISABLED) { // Link to the first unread, or most recent comment. if (comment_num_new($node->nid)) { // There are unread replies; link to first unread comment. $links[] = l(t('First unread comment'), "node/$node->nid", array('fragment' => 'new')); } else { // No unread replies; link to most recent comment. $comment_cid = db_result(db_query_range("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {node} n on pic.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY pic.cid DESC", $node->nid, 0, 1)); if ($comment_cid) { $links[] = l(t('Most recent comment'), "node/$node->nid", array('fragment' => "comment-$comment_cid")); } } // Link for most recent patch. $file_cid = db_result(db_query_range("SELECT cu.cid FROM {comment_upload} cu INNER JOIN {node} n on cu.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY cu.fid DESC", $node->nid, 0, 1)); if ($file_cid) { $links[] = l(t('Most recent attachment'), "node/$node->nid", array('fragment' => "comment-$file_cid")); } } // Link straight to comment form. if ($node->comment == COMMENT_NODE_READ_WRITE && (user_access('post comments') || user_access('post comments without approval'))) { // TODO: This conditional needs to be ripped out in D6. $comment_form_location = isset($node->project_issue['comment_form_location']) ? $node->project_issue['comment_form_location'] : variable_get('comment_form_location_' . $node->type, COMMENT_FORM_SEPARATE_PAGE); // Comment form isn't on the page, link to the comment reply page. if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) { $links[] = l(t('Add new comment'), "comment/reply/$node->nid"); } // Comment form is on the page, generate an internal page link for it. else { $links[] = l(t('Add new comment'), "node/$node->nid", array('fragment' => "comment-form")); } } return $links; } -/** - * Implementation of hook_insert(). - * - * @param $node - * Object containing form values from the project_issue node form. This is - * NOT a fully loaded $node object, so the issue-related values are directly - * in $node, not in the $node->project_issue array. - */ -function project_issue_insert($node) { - // Permanently store the original issue states in a serialized array. This - // is a bit yucky, but we need them for proper handling of states workflow. - // The current states need to be stored in {project_issues} as well for - // query efficiency in issue queue searches, and it seems too messy to add a - // bunch of new columns to the {project_issues} table for the original - // states. - $original_issue_data = new stdClass(); - $fields = array( - 'pid' => 0, - 'rid' => 0, - 'component' => '', - 'category' => '', - 'priority' => 0, - 'assigned' => 0, - 'sid' => 0, - 'title' => '', - ); - foreach ($fields as $field => $default) { - // Some of the incoming data may not have the correct default. - if (empty($node->$field)) { - $node->$field = $default; - } - $original_issue_data->$field = $node->$field; - } - - db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); - - // Invalidate the "Issue cockpit" block cache for this project, since the - // new issue will have altered the summary totals. - cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); -} - -function project_issue_delete($node) { - db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); - db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); -} - // Support stuff /** * Return information about project issue state values. * * @param $sid * Integer state id to return information about, or 0 for all states. * @param $restrict * Boolean to determine if states should be restricted based on the * permissions of the current user or $account if that parameter * is provided. * @param $is_author * Boolean that indicates if the current user is the author of the * issue, which can potentially grant a wider selection of states. * @param $current_sid * The current integer state id for the issue. * @param $defaults * Boolean to request the states used for default issue queries. * @param $account * Account of a user to pass to user_access() for access checking. * This parameter will have no effect unless $restrict is also * set to TRUE. * * @return * An array of states (sid as key, name as value) that match the * given filters, or the name of the requested state. * NOTE: The state name returned is raw text, and should be filtered via * check_plain() or filter_xss() before being printed as HTML output. */ function project_issue_state($sid = 0, $restrict = false, $is_author = false, $current_sid = 0, $defaults = false, $account = NULL) { static $options; if (!$options) { $result = db_query('SELECT * FROM {project_issue_state} ORDER BY weight'); while ($state = db_fetch_object($result)) { $options[] = $state; } } foreach($options as $state) { if ($restrict) { // Check if user has access, // or if status is default status and therefore available to all, // or if user is original issue author and author has access, // or if the issue is already in a state, even if the user doesn't have // access to that state themselves. if (user_access('set issue status '. str_replace("'", "", $state->name), $account) || user_access('administer projects', $account) || ($state->sid == variable_get('project_issue_default_state', 1)) || ($state->author_has && $is_author) || ($state->sid == $current_sid) ) { $states[$state->sid] = $state->name; } } else if ($defaults) { if ($state->default_query) { $states[$state->sid] = $state->name; } } else { $states[$state->sid] = $state->name; } } return $sid ? $states[$sid] : $states; } /** * Return an array of state ids that should be used for default queries. */ function project_issue_default_states() { static $defaults; if (empty($defaults)) { $states = project_issue_state(0, false, false, 0, true); $defaults = !empty($states) ? array_keys($states) : array(1, 2, 4); } return $defaults; } function project_issue_priority($priority = 0) { $priorities = array(1 => t('critical'), t('normal'), t('minor')); return $priority ? $priorities[$priority] : $priorities; } function project_issue_category($category = 0, $plural = 1) { if ($plural) { $categories = array('bug' => t('bug reports'), 'task' => t('tasks'), 'feature' => t('feature requests'), 'support' => t('support requests')); } else { $categories = array('bug' => t('bug report'), 'task' => t('task'), 'feature' => t('feature request'), 'support' => t('support request')); } return $category ? $categories[$category] : $categories; } function project_issue_count($pid) { $state = array(); $result = db_query('SELECT p.sid, count(p.sid) AS count FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid WHERE n.status = 1 AND p.pid = %d GROUP BY p.sid', $pid); while ($data = db_fetch_object($result)) { $state[$data->sid] = $data->count; } return $state; } /** * Return the HTML to use for the links at the top of issue query pages. * * @param $links * Array of links, indexed by the action ('create', 'search', etc). * * @see project_issue_query_result() * @see theme_links() */ function theme_project_issue_query_result_links($links) { return theme('links', $links); } /** * Provide an array of project issue summary fields. * @param $context * The context in which the fields will be displayed. * 'web' for project_issue node and comment summary tables. * 'email' for project_issue notification e-mail messages. */ function project_issue_field_labels($context) { if ($context == 'web') { $labels = array('title' => t('Title')); } else { $labels = array(); } $labels += array( 'pid' => t('Project'), 'rid' => t('Version'), 'component' => t('Component'), 'category' => t('Category'), 'priority' => t('Priority'), 'assigned' => t('Assigned to'), 'sid' => t('Status'), ); if ($context == 'email') { $labels += array( 'name' => t('Reported by'), 'updator' => t('Updated by'), ); } return $labels; } /** * Provide the text displayed to a user for a specific metadata field. * * @param $field * Name of the field. * @param $value * Value of the field. * * @return * Text to display to user. NOTE: This is unfiltered text! If this output is * being sent over the web, you must use check_plain(). */ function project_issue_change_summary($field, $value) { switch ($field) { case 'pid': $project = node_load(array('nid' => $value, 'type' => 'project_project')); return $project->title; case 'category': return $value ? project_issue_category($value, 0) : t('<none>'); case 'priority': return $value ? project_issue_priority($value) : t('<none>'); case 'rid': if ($value) { $release->nid = $value; if (module_exists('project_release')) { $release = project_release_load($release); } else { $release->project_release['version'] = t('Unknown'); } return $release->project_release['version']; } return t('<none>'); case 'assigned': $user = user_load(array('uid' => $value)); return (int) $value === 0 ? variable_get('anonymous', t('Anonymous')) : $user->name; case 'sid': return $value ? project_issue_state($value) : t('<none>'); default: return $value; } } function theme_project_issue_create_forbidden($uri = '') { global $user; if ($user->uid) { return ''; } // We cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages. $destination = "destination=". drupal_urlencode("node/add/project-issue/$uri"); if (variable_get('user_register', 1)) { return t('<a href="@login">Login</a> or <a href="@register">register</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination)))); } else { return t('<a href="@login">Login</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)))); } } diff --git a/project_issue.module b/project_issue.module index 7bc7e25..9ea1558 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,1300 +1,1319 @@ <?php -// $Id: project_issue.module,v 1.170 2009/06/18 03:24:59 dww Exp $ +// $Id: project_issue.module,v 1.171 2009/06/18 03:27:57 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); foreach (array('comment', 'mail') as $file) { module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), + 'file' => 'includes/issue_node_form.inc', 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; - $callbacks['node/add/project-issue']['file'] = 'issue.inc'; - $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue'); + $callbacks['node/add/project-issue']['file'] = 'issue_node_form.inc'; + $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue') . '/includes'; } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } -/** - * Redirect node/add/project_issue/* to node/add/project-issue/*. - */ -function project_issue_add_redirect_page($project = NULL, $category = NULL) { - $path = 'node/add/project-issue'; - if (!empty($project)) { - $path .= "/$project"; - } - if (!empty($category)) { - $path .= "/$category"; - } - drupal_goto($path); -} - function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'issue.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } +/** + * Implement hook_delete() for project issue nodes. + */ +function project_issue_delete($node) { + db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); + db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); +} + +/** + * Implement hook_form() for project issue nodes. + */ +function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { + module_load_include('inc', 'project_issue', 'includes/issue_node_form'); + return _project_issue_form($node, $form_state, $include_metadata_fields); +} + +/** + * Implement hook_validate() for project issue nodes. + */ +function project_issue_validate($node) { + module_load_include('inc', 'project_issue', 'includes/issue_node_form'); + return _project_issue_validate($node); +} + +/** + * Implement hook_insert() for project issue nodes. + */ +function project_issue_insert($node) { + module_load_include('inc', 'project_issue', 'includes/issue_node_form'); + return _project_issue_insert($node); +} + /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { foreach ($nids as $nid) { project_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * hook_nodeapi implementation specific to "project_project" nodes * (from the project.module) * @see project_issue_nodeapi(). */ function project_issue_project_nodeapi(&$node, $op, $arg) { switch ($op) { case 'load': project_issue_project_load($node, $arg); break; case 'insert': project_issue_project_insert($node); break; case 'delete': project_issue_project_delete($node); break; } } function project_issue_project_load(&$node, $arg) { $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $node->nid)); // If nothing loaded, bail immediately if (!$project) { return $node; } $node->project_issue = array(); $node->project_issue['components'] = unserialize($project->components); $node->project_issue['default_component'] = $project->default_component; $node->project_issue['mail_copy_filter'] = unserialize($project->mail_copy_filter); $node->project_issue['mail_copy_filter_state'] = unserialize($project->mail_copy_filter_state); foreach (array('issues', 'help', 'mail_digest', 'mail_copy', 'mail_reminder') as $field) { $node->project_issue[$field] = $project->$field; } return $node; } function project_issue_project_insert($node) { // Setup reasonable defaults: enable issue tracker and standard // components. If maintainers want to change these, (or any of the // other issue-related project settings, like the email notifications) // they'd use the "issues" subtab of the project edit tab (since none // of these fields are present on the initial project add form). $node->project_issue['issues'] = 1; // Default components are saved in the variables table as a plain // string instead of as a serialized array since they come out of // a textarea on a system settings form. Convert here to the more // desirable serialized array for storage per-project. $defaults = array(t('Code'), t('Documentation'), t('Miscellaneous'), t('User interface')); $components = variable_get('project_issue_default_components', implode("\n", $defaults)); $default_components = explode("\n", str_replace("\r", '', $components)); $node->project_issue['components'] = serialize($default_components); db_query("INSERT INTO {project_issue_projects} (nid, issues, components) VALUES (%d, %d, '%s')", $node->nid, $node->project_issue['issues'], $node->project_issue['components']); } function project_issue_project_delete($node) { // Delete all associated issues. $issues = db_query('SELECT nid FROM {project_issues} WHERE pid = %d', $node->nid); while ($issue = db_fetch_object($issues)) { node_delete($issue->nid); } db_query('DELETE FROM {project_issue_projects} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_subscriptions} WHERE nid = %d', $node->nid); } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes)); } $output = '<span class="project-issue-status-'. $node->project_issue['sid'] .' project-issue-status-info">'. $link; if ($include_assigned && !empty($username)) { $output .= ' <span class="project-issue-assigned-user">'. t('Assigned to: @username', array('@username' => $username)) .'</span>'; } $output .= '</span>'; return $output; } /** * Implementation of hook_form_filter_tips(). * @ingroup project_issue_filter */ function project_issue_filter_tips($delta, $format, $long = FALSE) { if ($long) { return t("References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically, with the title of the issue appended. The status of the issue is shown on hover. If '@' is appended (e.g. [#1234@]), the user the issue is assigned to will also be printed."); } else { return t('Project issue numbers (ex. [#12345]) turn into links automatically.'); } } /** * Implementation of hook_filter(). * @ingroup project_issue_filter */ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { switch ($op) { case 'list': return array(0 => t('Project Issue to link filter')); case 'description': return t('Converts references to project issues (in the form of [#12345]) into links. Caching should be disabled if node access control modules are used.'); case 'no cache': return FALSE; case 'prepare': return $text; case 'process': $regex = '(?:(?<!\w)\[#\d+(?:-\d+)?(@)?\](?!\w))|<pre>.*?<\/pre>|<code>.*?<\/code>|<a(?:[^>"\']|"[^"]*"|\'[^\']*\')*>.*?<\/a>'; $text = preg_replace_callback("/$regex/", 'project_issue_link_filter_callback', $text); return $text; } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); if (!empty($grants)) { $conflict_grants = TRUE; } $allowed_roles = user_roles(FALSE, 'access project issues'); if (!isset($allowed_roles[DRUPAL_ANONYMOUS_RID])) { $conflict_anonymous = TRUE; } foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if ($conflict_grants && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'.
Br3nda/drupal-module-project_issue
00a6bf173dfd4996647db10c26fd6170fd2b7090
#405478 by dww: Proper page split of project_issue: Moved code for the issue subscription page from issue.inc to includes/subscribe.inc.
diff --git a/includes/subscribe.inc b/includes/subscribe.inc new file mode 100644 index 0000000..e3fae4d --- /dev/null +++ b/includes/subscribe.inc @@ -0,0 +1,165 @@ +<?php +// $Id: subscribe.inc,v 1.1 2009/06/18 03:24:59 dww Exp $ + +function project_issue_subscribe($form_state, $project_nid = 0) { + global $user; + + if (!valid_email_address($user->mail)) { + drupal_set_message(t('You need to provide a valid e-mail address to subscribe to issue e-mails. Please edit your user information.'), 'error'); + drupal_goto('user/'. $user->uid .'/edit'); + } + + $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); + + if ($project_nid) { + if (!is_numeric($project_nid)) { + $project_nid = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $project_nid)); + } + if (!$project_nid) { + return drupal_not_found(); + } + + $project = node_load($project_nid); + project_project_set_breadcrumb($project, TRUE); + + $level = db_result(db_query('SELECT level FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $project->nid, $user->uid)); + $form['single'] = array( + '#type' => 'value', + '#value' => $project->nid, + ); + $form['#project'] = array( + '#type' => 'value', + '#value' => $project, + ); + $form['subscribe'] = array( + '#type' => 'markup', + '#value' => '<p>'. t('Subscribe to receive e-mail notification when an issue for this project is updated.') .'</p>', + ); + $form['options']['#tree'] = TRUE; + $form['options'][$project->nid] = array( + '#type' => 'radios', + '#title' => t('Subscribe to @project issues', array('@project' => $project->title)), + '#default_value' => isset($level) ? $level : 0, + '#options' => $levels, + ); + + } + else { + + $form['buttons']['all'] = array( + '#type' => 'markup', + '#value' => t('All projects'), + ); + foreach ($levels as $key => $level) { + $form['buttons'][$level] = array( + '#type' => 'submit', + '#name' => 'all', + '#value' => $level, + ); + } + $nids = array(); + + $result = db_query(db_rewrite_sql("SELECT s.nid, n.title, s.level, p.uri FROM {project_subscriptions} s INNER JOIN {node} n ON n.nid = s.nid INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1 AND s.uid = %d ORDER BY n.title", 's'), $user->uid); + while ($project = db_fetch_object($result)) { + $form['project'][$project->nid]['title'] = array( + '#value' => l($project->title, "node/$project->nid"), + ); + foreach ($levels as $key => $level) { + if ($project->level == $key) { + $status[$project->nid] = $key; + } + } + $nids[] = $project->nid; + } + + if (empty($nids)) { + $placeholders = ''; + } + else { + $placeholders = " AND n.nid NOT IN (". implode(',', array_fill(0, count($nids), '%d')) .")"; + } + + $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, p.uri FROM {node} n INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1". ($nids ? $placeholders : "") ." ORDER BY n.title"), $nids); + while ($project = db_fetch_object($result)) { + $form['project'][$project->nid]['title'] = array( + '#value' => l($project->title, "node/$project->nid"), + ); + $nids[] = $project->nid; + } + + foreach ($nids as $nid) { + $form['options']['#tree'] = TRUE; + $form['options'][$nid] = array( + '#type' => 'radios', + '#default_value' => isset($status[$nid]) ? $status[$nid] : 0, + '#options' => $levels, + ); + } + } + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Subscribe'), + ); + return $form; +} + +function theme_project_issue_subscribe($form) { + global $user; + + $output = ''; + + if (!isset($form['single'])) { + $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); + $headers = array_merge(array(t('Project')), $levels); + + $row = array(); + foreach (element_children($form['buttons']) as $key) { + $row[] = drupal_render($form['buttons'][$key]); + } + $rows = array($row); + + foreach (element_children($form['project']) as $key) { + $row = array(drupal_render($form['project'][$key]['title'])); + foreach ($levels as $level => $name) { + $row[] = drupal_render($form['options'][$key][$level]); + } + $rows[] = $row; + } + $output = theme('table', $headers, $rows); + } + + $output .= drupal_render($form); + return $output; +} + +function project_issue_subscribe_submit($form, &$form_state) { + + global $user; + $all = $form_state['clicked_button']['#value']; + + $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); + + // Remove previous subscriptions for user. + if (isset($form_state['values']['single'])) { + db_query('DELETE FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $form_state['values']['single'], $user->uid); + } + else { + db_query('DELETE FROM {project_subscriptions} WHERE uid = %d', $user->uid); + } + + $_level = array_search($all, $levels); + + foreach ($form_state['values']['options'] as $nid => $level) { + if ($_level !== 0 && $level !== 0) { + db_query('INSERT INTO {project_subscriptions} (nid, uid, level) VALUES (%d, %d, %d)', $nid, $user->uid, $_level ? $_level : $level); + } + } + drupal_set_message(t('Subscription settings saved.')); + + if (isset($form['single'])) { + $form_state['redirect'] = 'project/issues/subscribe-mail/'. $form['#project']['#value']->project['uri']; + } + else { + $form_state['redirect'] = 'project/issues/subscribe-mail'; + } +} diff --git a/issue.inc b/issue.inc index 9fa60bc..0a660e4 100644 --- a/issue.inc +++ b/issue.inc @@ -1,772 +1,608 @@ <?php -// $Id: issue.inc,v 1.351 2009/06/18 03:24:02 dww Exp $ +// $Id: issue.inc,v 1.352 2009/06/18 03:24:59 dww Exp $ /** * JS callback method to return updated elements on the issue form. * This function is called when someone changes the "Project" selector. */ function project_issue_update_project() { $form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); // Rebuild the form and cache it again. $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); // These used to be path arguments. Now they arrive via form element. $issue_nid = $form['nid']['#value']; $pid = $form_state['values']['project_info']['pid']; $rid = isset($form_state['values']['project_info']['rid']) ? $form_state['values']['project_info']['rid'] : 0; $cid = $form_state['values']['cid']; $assigned_uid = $form_state['values']['project_info']['assigned']; $project_info = $form['original_issue']['project_info']; // Only generate release stuff if the project_release module is enabled. if (module_exists('project_release')) { $project->nid = $pid; if ($releases = project_release_get_releases($project, 0)) { $old_version = db_result(db_query("SELECT version FROM {project_release_nodes} WHERE nid = %d", $rid)); $releases = array(t('<none>')) + $releases; // Since the value of releases is by nid, try to match release // based on the label instead. $default = 0; foreach ($releases as $key => $label) { if ($old_version == $label) { $default = $key; } } // Element is tree'd here to match the original form layout. $project_info['#tree'] = TRUE; $project_info['rid']['#options'] = $releases; $project_info['rid']['#disabled'] = FALSE; if (!empty($default)) { $project_info['rid']['#value'] = $default; $project_info['rid']['#default_value'] = $default; } } else { $project_info['rid']['#disabled'] = TRUE; $project_info['rid']['#options'] = array(); } } // Assigned. if (is_numeric($issue_nid)) { $issue = node_load(array('nid' => $issue_nid, 'type' => 'project_issue')); } else { // @TODO: This case should not ever be hit until // http://drupal.org/node/197281 lands. $issue = new stdClass; } $issue->project_issue['pid'] = $pid; $assigned_choices = project_issue_assigned_choices($issue); $project_info['assigned']['#default_value'] = $assigned_uid; $project_info['assigned']['#options'] = $assigned_choices; // Components. $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $pid)); $components = array(); if ($project->components) { $components = array(t('<none>')); foreach (unserialize($project->components) as $component) { $component = check_plain($component); $components[$component] = $component; } } $project_info['component']['#default_value'] = $cid; $project_info['component']['#options'] = $components; // Build the HTML output for the component select. $output = theme('status_messages') . drupal_render($project_info); drupal_json(array('status' => TRUE, 'data' => $output)); exit; } -function project_issue_subscribe_submit($form, &$form_state) { - - global $user; - $all = $form_state['clicked_button']['#value']; - - $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); - - // Remove previous subscriptions for user. - if (isset($form_state['values']['single'])) { - db_query('DELETE FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $form_state['values']['single'], $user->uid); - } - else { - db_query('DELETE FROM {project_subscriptions} WHERE uid = %d', $user->uid); - } - - $_level = array_search($all, $levels); - - foreach ($form_state['values']['options'] as $nid => $level) { - if ($_level !== 0 && $level !== 0) { - db_query('INSERT INTO {project_subscriptions} (nid, uid, level) VALUES (%d, %d, %d)', $nid, $user->uid, $_level ? $_level : $level); - } - } - drupal_set_message(t('Subscription settings saved.')); - - if (isset($form['single'])) { - $form_state['redirect'] = 'project/issues/subscribe-mail/'. $form['#project']['#value']->project['uri']; - } - else { - $form_state['redirect'] = 'project/issues/subscribe-mail'; - } -} - - -function project_issue_subscribe($form_state, $project_nid = 0) { - global $user; - - if (!valid_email_address($user->mail)) { - drupal_set_message(t('You need to provide a valid e-mail address to subscribe to issue e-mails. Please edit your user information.'), 'error'); - drupal_goto('user/'. $user->uid .'/edit'); - } - - $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); - - if ($project_nid) { - if (!is_numeric($project_nid)) { - $project_nid = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $project_nid)); - } - if (!$project_nid) { - return drupal_not_found(); - } - - $project = node_load($project_nid); - project_project_set_breadcrumb($project, TRUE); - - $level = db_result(db_query('SELECT level FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $project->nid, $user->uid)); - $form['single'] = array( - '#type' => 'value', - '#value' => $project->nid, - ); - $form['#project'] = array( - '#type' => 'value', - '#value' => $project, - ); - $form['subscribe'] = array( - '#type' => 'markup', - '#value' => '<p>'. t('Subscribe to receive e-mail notification when an issue for this project is updated.') .'</p>', - ); - $form['options']['#tree'] = TRUE; - $form['options'][$project->nid] = array( - '#type' => 'radios', - '#title' => t('Subscribe to @project issues', array('@project' => $project->title)), - '#default_value' => isset($level) ? $level : 0, - '#options' => $levels, - ); - - } - else { - - $form['buttons']['all'] = array( - '#type' => 'markup', - '#value' => t('All projects'), - ); - foreach ($levels as $key => $level) { - $form['buttons'][$level] = array( - '#type' => 'submit', - '#name' => 'all', - '#value' => $level, - ); - } - $nids = array(); - - $result = db_query(db_rewrite_sql("SELECT s.nid, n.title, s.level, p.uri FROM {project_subscriptions} s INNER JOIN {node} n ON n.nid = s.nid INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1 AND s.uid = %d ORDER BY n.title", 's'), $user->uid); - while ($project = db_fetch_object($result)) { - $form['project'][$project->nid]['title'] = array( - '#value' => l($project->title, "node/$project->nid"), - ); - foreach ($levels as $key => $level) { - if ($project->level == $key) { - $status[$project->nid] = $key; - } - } - $nids[] = $project->nid; - } - - if (empty($nids)) { - $placeholders = ''; - } - else { - $placeholders = " AND n.nid NOT IN (". implode(',', array_fill(0, count($nids), '%d')) .")"; - } - - $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, p.uri FROM {node} n INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1". ($nids ? $placeholders : "") ." ORDER BY n.title"), $nids); - while ($project = db_fetch_object($result)) { - $form['project'][$project->nid]['title'] = array( - '#value' => l($project->title, "node/$project->nid"), - ); - $nids[] = $project->nid; - } - - foreach ($nids as $nid) { - $form['options']['#tree'] = TRUE; - $form['options'][$nid] = array( - '#type' => 'radios', - '#default_value' => isset($status[$nid]) ? $status[$nid] : 0, - '#options' => $levels, - ); - } - } - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Subscribe'), - ); - return $form; -} - -function theme_project_issue_subscribe($form) { - global $user; - - $output = ''; - - if (!isset($form['single'])) { - $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); - $headers = array_merge(array(t('Project')), $levels); - - $row = array(); - foreach (element_children($form['buttons']) as $key) { - $row[] = drupal_render($form['buttons'][$key]); - } - $rows = array($row); - - foreach (element_children($form['project']) as $key) { - $row = array(drupal_render($form['project'][$key]['title'])); - foreach ($levels as $level => $name) { - $row[] = drupal_render($form['options'][$key][$level]); - } - $rows[] = $row; - } - $output = theme('table', $headers, $rows); - } - - $output .= drupal_render($form); - return $output; -} - function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); } $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Implementation of hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => filter_xss($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => filter_xss($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if ($releases) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'hidden', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Build an array of users to whom an issue may be assigned. * * @param $issue * The fully loaded issue node object. * @return * A keyed array in the form uid => name containing users * to whom an issue may be assigned. */ function project_issue_assigned_choices($issue) { // Setup the array of choices for who the issue is assigned to. $assigned = array(); foreach (module_implements('project_issue_assignees') as $module) { $function = "{$module}_project_issue_assignees"; $function($assigned, $issue); } natcasesort($assigned); $assigned = array(0 => empty($issue->project_issue['assigned']) ? t('Unassigned') : t('Unassign')) + $assigned; return $assigned; } /** * Implmentation of hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } function project_issue_view($node, $teaser = false, $page = false) { $node = node_prepare($node, $teaser); if (!$teaser && ($page || project_issue_is_comment_reply())) { $node->content['#prefix'] = '<div class="project-issue">'; $node->content['#suffix'] = '</div>'; $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); $release->nid = $node->project_issue['rid']; if (module_exists('project_release')) { $release = project_release_load($release); } $assigned = ($node->project_issue['assigned'] && ($account = user_load(array('uid' => $node->project_issue['assigned']))) ? $account->name : t('Unassigned')); $current_data = array(); $current_data['pid'] = array( 'label' => t('Project'), 'current' => $project->title, ); if (!empty($release->project_release['version'])) { $current_data['rid'] = array( 'label' => t('Version'), 'current' => $release->project_release['version'], ); } $current_data['component'] = array( 'label' => t('Component'), 'current' => $node->project_issue['component'], ); $current_data['category'] = array( 'label' => t('Category'), 'current' => project_issue_category($node->project_issue['category'], 0), ); $current_data['priority'] = array( 'label' => t('Priority'), 'current' => project_issue_priority($node->project_issue['priority']), ); $current_data['assigned'] = array( 'label' => t('Assigned'), 'current' => $assigned, ); $current_data['sid'] = array( 'label' => t('Status'), 'current' => project_issue_state($node->project_issue['sid']), ); // Allow modules to alter the metadata displayed in the table on the actual // issue node itself (at the very top of the issue). Modules should accept // the $current_data parameter by reference and add additional // elements for additional lines in the table. // // Modules implementing this hook should take the following parameters: // @param $view // A string representing the metadata view being generated. For the issue // node main table, this will be 'current'. // @param $node // The project_issue node object. // @param $current_data // An associative array of rows in the project issue metadata table that // will be displayed, with the following key/value pairs: // 'label' => The metadata label. // 'current' => The current metadata value. // This parameter should be accepted by reference. foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('current', $node, $current_data); } $node->content['project_issue_summary'] = array( '#value' => theme('project_issue_summary', $current_data, project_issue_internal_links($node)), '#weight' => -5, ); $node->content['project_issue_header'] = array( '#value' => '<div class="header">'. t('Description') .'</div>', '#weight' => -3, ); project_issue_set_breadcrumb($node, $project); } return $node; } /** * Implementation of hook_project_issue_assignees(). * * This hook is used to modify the list of 'Assigned' users when creating or * commenting on an issue. * * @param $assigned * An array of key => value pairs in the format of uid => name that represents * the list of users that the issue may be assigned to. This parameter * is passed by reference so the hook may make changes, such as adding or * removing elements. * @param $node * The node object for the issue. */ function project_issue_project_issue_assignees(&$assigned, $node) { global $user; if ($user->uid) { if (isset($node->project_issue['assigned']) && $user->uid != $node->project_issue['assigned']) { // Assigned to someone else, add the currently assigned user. $account = user_load(array('uid' => $node->project_issue['assigned'])); $assigned[$node->project_issue['assigned']] = $account->name; } // Always let the person replying assign it to themselves. $assigned[$user->uid] = $user->name; } if (user_access('assign and be assigned project issues')) { // All users are included if either anon or auth user has the perm. if (db_result(db_query("SELECT rid FROM {permission} WHERE perm LIKE '%%%s%%' AND rid IN(%d, %d)", 'assign and be assigned project issues', DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $result = db_query("SELECT uid, name FROM {users}"); } else { $result = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {role} r ON ur.rid = r.rid INNER JOIN {permission} p ON p.rid = r.rid WHERE p.perm LIKE '%%%s%%'", 'assign and be assigned project issues'); diff --git a/project_issue.module b/project_issue.module index 0a536d5..7bc7e25 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,581 +1,581 @@ <?php -// $Id: project_issue.module,v 1.169 2009/06/18 03:24:02 dww Exp $ +// $Id: project_issue.module,v 1.170 2009/06/18 03:24:59 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); foreach (array('comment', 'mail') as $file) { module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, - 'file' => 'issue.inc', + 'file' => 'includes/subscribe.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue'); } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'issue.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key
Br3nda/drupal-module-project_issue
971027cb61cd65b53b5d1be2c4896c724568930d
#405478 by dww: Proper page split of project_issue: Moved code for the issue statistics page from issue.inc to includes/statistics.inc.
diff --git a/includes/statistics.inc b/includes/statistics.inc new file mode 100644 index 0000000..8e3de8e --- /dev/null +++ b/includes/statistics.inc @@ -0,0 +1,132 @@ +<?php +// $Id: statistics.inc,v 1.1 2009/06/18 03:24:03 dww Exp $ + +/** + * Page callback for the issue statistics page. + */ +function project_issue_statistics($project = NULL) { + $states = project_issue_state(); + if ($project->nid) { + $filter = sprintf(' AND p.pid = %d ', (int)$project->nid); + project_project_set_breadcrumb($project, TRUE); + } + + $output = '<div class="project-issue">'; + + // Issue lifetime. + $header = array(t('Category'), t('Overall'), t('Last month')); + $rows = array(); + $duration = time() - 30 * 24 * 60 * 60; + $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 GROUP BY p.category'), $filter); + while ($stat = db_fetch_object($result)) { + $rows[$stat->category][0] = project_issue_category($stat->category); + $rows[$stat->category][1] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); + $rows[$stat->category][2] = array('data' => t('N/A'), 'class' => 'numeric'); + } + + $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 AND n.created > %d GROUP BY p.category'), $filter, $duration); + while ($stat = db_fetch_object($result)) { + if ($stat->duration > 0) { + $rows[$stat->category][2] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); + } + } + $output .= '<h2>'. t('Average lifetime') .'</h2>'; + $output .= theme('table', $header, $rows); + + $header = array( + array('data' => t('Status')), + array('data' => t('Overall'), 'class' => 'project-issue-numeric'), + array('data' => '%', 'class' => 'project-issue-numeric'), + array('data' => t('Last month'), 'class' => 'project-issue-numeric'), + ); + $rows = array(); + // Activity overall. + $total = db_result(db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s', 'p'), $filter)); + $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s GROUP BY p.sid', 'p'), $filter); + while ($stat = db_fetch_object($result)) { + $rows[$stat->sid][0] = check_plain(project_issue_state($stat->sid)); + $rows[$stat->sid][1] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); + $rows[$stat->sid][2] = array('data' => number_format($stat->total / $total * 100) .'%', 'class' => 'project-issue-numeric-light'); + $rows[$stat->sid][3] = array('data' => '0', 'class' => 'project-issue-numeric'); + } + // Activity this month. + $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND n.changed > %d GROUP BY p.sid', 'p'), $filter, $duration); + while ($stat = db_fetch_object($result)) { + $rows[$stat->sid][3] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); + } + $output .= '<h2>'. t('Issue activity') .'</h2>'; + $output .= theme('table', $header, $rows); + + // Project overview. + if (!$project->nid) { + // Even though we don't use the tablesorting logic in the query itself, + // we include it anyways because we're going to leverage the $_GET arguments + // to build our own tablesorting mechanism. + $header = array(); + $header['project'] = array('data' => t('Project'), 'field' => 'title'); + foreach ($states as $key => $value) { + $header[$key] = array('data' => check_plain($value), 'field' => $key); + } + $header['total'] = array('data' => t('Total'), 'field' => 'total'); + // Force sorting arrow to appear on active first. + $header[1]['sort'] = 'desc'; + $args = array(); + + // Since we're pulling the sid to sort by here individually in the first query + // below, we can bastardize the tablesorting logic to get tablesorting. + $where = ' AND p.sid = %d'; + $column = 'total'; + if (isset($_GET['order'])) { + switch ($_GET['order']) { + case 'Project': + $where = ''; + $column = 'title'; + break; + case 'Total': + $where = ''; + break; + default: + if ($state = array_search($_GET['order'], $states)) { + $args[] = $state; + } + else { + $args[] = 1; + } + break; + } + } + else { + $args[] = 1; + } + $sort = (isset($_GET['sort']) && $_GET['sort'] == 'desc') || !isset($_GET['sort']) ? 'DESC' : 'ASC'; + + $rows = array(); + $projects = pager_query(db_rewrite_sql("SELECT pn.nid, pn.title, COUNT(n.nid) AS total FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid INNER JOIN {node} pn ON p.pid = pn.nid WHERE n.status = 1 AND pn.status = 1$where GROUP BY pn.nid, pn.title ORDER BY $column $sort"), 15, 0, db_rewrite_sql("SELECT COUNT(DISTINCT(n.nid)) FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.pid INNER JOIN {node} pin ON p.nid = pin.nid WHERE n.status = 1 AND pin.status = 1$where"), $args); + $orig = array('project' => array('data' => 0)); + foreach ($states as $key => $value) { + $orig[$key] = array('data' => '', 'class' => 'project-issue-numeric'); + } + $orig['total'] = array('data' => '', 'class' => 'project-issue-numeric'); + + while ($project = db_fetch_object($projects)) { + $rows[$project->nid] = $orig; + $rows[$project->nid]['project']['data'] = l($project->title, "node/$project->nid"); + $stats = db_query("SELECT sid, COUNT(nid) as total FROM {project_issues} WHERE pid = %d GROUP BY sid", $project->nid); + while ($stat = db_fetch_object($stats)) { + $rows[$project->nid]['total']['data'] += $stat->total; + $rows[$project->nid][$stat->sid]['data'] = $stat->total; + } + } + $output .= '<h2>'. t('Project overview') .'</h2>'; + $output .= '<div class="project-issue-statistics-overview-table">'; + $output .= theme('table', $header, $rows); + + if ($pager = theme('pager', 15, 0)) { + $output .= $pager; + } + $output .= '</div>'; + } + + $output .= '</div>'; + return $output; +} diff --git a/issue.inc b/issue.inc index 1f69089..9fa60bc 100644 --- a/issue.inc +++ b/issue.inc @@ -1,735 +1,608 @@ <?php -// $Id: issue.inc,v 1.350 2009/06/15 04:14:00 dww Exp $ +// $Id: issue.inc,v 1.351 2009/06/18 03:24:02 dww Exp $ /** * JS callback method to return updated elements on the issue form. * This function is called when someone changes the "Project" selector. */ function project_issue_update_project() { $form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); // Rebuild the form and cache it again. $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); // These used to be path arguments. Now they arrive via form element. $issue_nid = $form['nid']['#value']; $pid = $form_state['values']['project_info']['pid']; $rid = isset($form_state['values']['project_info']['rid']) ? $form_state['values']['project_info']['rid'] : 0; $cid = $form_state['values']['cid']; $assigned_uid = $form_state['values']['project_info']['assigned']; $project_info = $form['original_issue']['project_info']; // Only generate release stuff if the project_release module is enabled. if (module_exists('project_release')) { $project->nid = $pid; if ($releases = project_release_get_releases($project, 0)) { $old_version = db_result(db_query("SELECT version FROM {project_release_nodes} WHERE nid = %d", $rid)); $releases = array(t('<none>')) + $releases; // Since the value of releases is by nid, try to match release // based on the label instead. $default = 0; foreach ($releases as $key => $label) { if ($old_version == $label) { $default = $key; } } // Element is tree'd here to match the original form layout. $project_info['#tree'] = TRUE; $project_info['rid']['#options'] = $releases; $project_info['rid']['#disabled'] = FALSE; if (!empty($default)) { $project_info['rid']['#value'] = $default; $project_info['rid']['#default_value'] = $default; } } else { $project_info['rid']['#disabled'] = TRUE; $project_info['rid']['#options'] = array(); } } // Assigned. if (is_numeric($issue_nid)) { $issue = node_load(array('nid' => $issue_nid, 'type' => 'project_issue')); } else { // @TODO: This case should not ever be hit until // http://drupal.org/node/197281 lands. $issue = new stdClass; } $issue->project_issue['pid'] = $pid; $assigned_choices = project_issue_assigned_choices($issue); $project_info['assigned']['#default_value'] = $assigned_uid; $project_info['assigned']['#options'] = $assigned_choices; // Components. $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $pid)); $components = array(); if ($project->components) { $components = array(t('<none>')); foreach (unserialize($project->components) as $component) { $component = check_plain($component); $components[$component] = $component; } } $project_info['component']['#default_value'] = $cid; $project_info['component']['#options'] = $components; // Build the HTML output for the component select. $output = theme('status_messages') . drupal_render($project_info); drupal_json(array('status' => TRUE, 'data' => $output)); exit; } -function project_issue_statistics($project = NULL) { - $states = project_issue_state(); - if ($project->nid) { - $filter = sprintf(' AND p.pid = %d ', (int)$project->nid); - project_project_set_breadcrumb($project, TRUE); - } - - $output = '<div class="project-issue">'; - - // Issue lifetime. - $header = array(t('Category'), t('Overall'), t('Last month')); - $rows = array(); - $duration = time() - 30 * 24 * 60 * 60; - $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 GROUP BY p.category'), $filter); - while ($stat = db_fetch_object($result)) { - $rows[$stat->category][0] = project_issue_category($stat->category); - $rows[$stat->category][1] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); - $rows[$stat->category][2] = array('data' => t('N/A'), 'class' => 'numeric'); - } - - $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 AND n.created > %d GROUP BY p.category'), $filter, $duration); - while ($stat = db_fetch_object($result)) { - if ($stat->duration > 0) { - $rows[$stat->category][2] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); - } - } - $output .= '<h2>'. t('Average lifetime') .'</h2>'; - $output .= theme('table', $header, $rows); - - $header = array( - array('data' => t('Status')), - array('data' => t('Overall'), 'class' => 'project-issue-numeric'), - array('data' => '%', 'class' => 'project-issue-numeric'), - array('data' => t('Last month'), 'class' => 'project-issue-numeric'), - ); - $rows = array(); - // Activity overall. - $total = db_result(db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s', 'p'), $filter)); - $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s GROUP BY p.sid', 'p'), $filter); - while ($stat = db_fetch_object($result)) { - $rows[$stat->sid][0] = check_plain(project_issue_state($stat->sid)); - $rows[$stat->sid][1] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); - $rows[$stat->sid][2] = array('data' => number_format($stat->total / $total * 100) .'%', 'class' => 'project-issue-numeric-light'); - $rows[$stat->sid][3] = array('data' => '0', 'class' => 'project-issue-numeric'); - } - // Activity this month. - $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND n.changed > %d GROUP BY p.sid', 'p'), $filter, $duration); - while ($stat = db_fetch_object($result)) { - $rows[$stat->sid][3] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); - } - $output .= '<h2>'. t('Issue activity') .'</h2>'; - $output .= theme('table', $header, $rows); - - // Project overview. - if (!$project->nid) { - // Even though we don't use the tablesorting logic in the query itself, - // we include it anyways because we're going to leverage the $_GET arguments - // to build our own tablesorting mechanism. - $header = array(); - $header['project'] = array('data' => t('Project'), 'field' => 'title'); - foreach ($states as $key => $value) { - $header[$key] = array('data' => check_plain($value), 'field' => $key); - } - $header['total'] = array('data' => t('Total'), 'field' => 'total'); - // Force sorting arrow to appear on active first. - $header[1]['sort'] = 'desc'; - $args = array(); - - // Since we're pulling the sid to sort by here individually in the first query - // below, we can bastardize the tablesorting logic to get tablesorting. - $where = ' AND p.sid = %d'; - $column = 'total'; - if (isset($_GET['order'])) { - switch ($_GET['order']) { - case 'Project': - $where = ''; - $column = 'title'; - break; - case 'Total': - $where = ''; - break; - default: - if ($state = array_search($_GET['order'], $states)) { - $args[] = $state; - } - else { - $args[] = 1; - } - break; - } - } - else { - $args[] = 1; - } - $sort = (isset($_GET['sort']) && $_GET['sort'] == 'desc') || !isset($_GET['sort']) ? 'DESC' : 'ASC'; - - $rows = array(); - $projects = pager_query(db_rewrite_sql("SELECT pn.nid, pn.title, COUNT(n.nid) AS total FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid INNER JOIN {node} pn ON p.pid = pn.nid WHERE n.status = 1 AND pn.status = 1$where GROUP BY pn.nid, pn.title ORDER BY $column $sort"), 15, 0, db_rewrite_sql("SELECT COUNT(DISTINCT(n.nid)) FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.pid INNER JOIN {node} pin ON p.nid = pin.nid WHERE n.status = 1 AND pin.status = 1$where"), $args); - $orig = array('project' => array('data' => 0)); - foreach ($states as $key => $value) { - $orig[$key] = array('data' => '', 'class' => 'project-issue-numeric'); - } - $orig['total'] = array('data' => '', 'class' => 'project-issue-numeric'); - - while ($project = db_fetch_object($projects)) { - $rows[$project->nid] = $orig; - $rows[$project->nid]['project']['data'] = l($project->title, "node/$project->nid"); - $stats = db_query("SELECT sid, COUNT(nid) as total FROM {project_issues} WHERE pid = %d GROUP BY sid", $project->nid); - while ($stat = db_fetch_object($stats)) { - $rows[$project->nid]['total']['data'] += $stat->total; - $rows[$project->nid][$stat->sid]['data'] = $stat->total; - } - } - $output .= '<h2>'. t('Project overview') .'</h2>'; - $output .= '<div class="project-issue-statistics-overview-table">'; - $output .= theme('table', $header, $rows); - - if ($pager = theme('pager', 15, 0)) { - $output .= $pager; - } - $output .= '</div>'; - } - - $output .= '</div>'; - return $output; -} - function project_issue_subscribe_submit($form, &$form_state) { global $user; $all = $form_state['clicked_button']['#value']; $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); // Remove previous subscriptions for user. if (isset($form_state['values']['single'])) { db_query('DELETE FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $form_state['values']['single'], $user->uid); } else { db_query('DELETE FROM {project_subscriptions} WHERE uid = %d', $user->uid); } $_level = array_search($all, $levels); foreach ($form_state['values']['options'] as $nid => $level) { if ($_level !== 0 && $level !== 0) { db_query('INSERT INTO {project_subscriptions} (nid, uid, level) VALUES (%d, %d, %d)', $nid, $user->uid, $_level ? $_level : $level); } } drupal_set_message(t('Subscription settings saved.')); if (isset($form['single'])) { $form_state['redirect'] = 'project/issues/subscribe-mail/'. $form['#project']['#value']->project['uri']; } else { $form_state['redirect'] = 'project/issues/subscribe-mail'; } } function project_issue_subscribe($form_state, $project_nid = 0) { global $user; if (!valid_email_address($user->mail)) { drupal_set_message(t('You need to provide a valid e-mail address to subscribe to issue e-mails. Please edit your user information.'), 'error'); drupal_goto('user/'. $user->uid .'/edit'); } $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); if ($project_nid) { if (!is_numeric($project_nid)) { $project_nid = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $project_nid)); } if (!$project_nid) { return drupal_not_found(); } $project = node_load($project_nid); project_project_set_breadcrumb($project, TRUE); $level = db_result(db_query('SELECT level FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $project->nid, $user->uid)); $form['single'] = array( '#type' => 'value', '#value' => $project->nid, ); $form['#project'] = array( '#type' => 'value', '#value' => $project, ); $form['subscribe'] = array( '#type' => 'markup', '#value' => '<p>'. t('Subscribe to receive e-mail notification when an issue for this project is updated.') .'</p>', ); $form['options']['#tree'] = TRUE; $form['options'][$project->nid] = array( '#type' => 'radios', '#title' => t('Subscribe to @project issues', array('@project' => $project->title)), '#default_value' => isset($level) ? $level : 0, '#options' => $levels, ); } else { $form['buttons']['all'] = array( '#type' => 'markup', '#value' => t('All projects'), ); foreach ($levels as $key => $level) { $form['buttons'][$level] = array( '#type' => 'submit', '#name' => 'all', '#value' => $level, ); } $nids = array(); $result = db_query(db_rewrite_sql("SELECT s.nid, n.title, s.level, p.uri FROM {project_subscriptions} s INNER JOIN {node} n ON n.nid = s.nid INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1 AND s.uid = %d ORDER BY n.title", 's'), $user->uid); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); foreach ($levels as $key => $level) { if ($project->level == $key) { $status[$project->nid] = $key; } } $nids[] = $project->nid; } if (empty($nids)) { $placeholders = ''; } else { $placeholders = " AND n.nid NOT IN (". implode(',', array_fill(0, count($nids), '%d')) .")"; } $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, p.uri FROM {node} n INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1". ($nids ? $placeholders : "") ." ORDER BY n.title"), $nids); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); $nids[] = $project->nid; } foreach ($nids as $nid) { $form['options']['#tree'] = TRUE; $form['options'][$nid] = array( '#type' => 'radios', '#default_value' => isset($status[$nid]) ? $status[$nid] : 0, '#options' => $levels, ); } } $form['submit'] = array( '#type' => 'submit', '#value' => t('Subscribe'), ); return $form; } function theme_project_issue_subscribe($form) { global $user; $output = ''; if (!isset($form['single'])) { $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); $headers = array_merge(array(t('Project')), $levels); $row = array(); foreach (element_children($form['buttons']) as $key) { $row[] = drupal_render($form['buttons'][$key]); } $rows = array($row); foreach (element_children($form['project']) as $key) { $row = array(drupal_render($form['project'][$key]['title'])); foreach ($levels as $level => $name) { $row[] = drupal_render($form['options'][$key][$level]); } $rows[] = $row; } $output = theme('table', $headers, $rows); } $output .= drupal_render($form); return $output; } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); } $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Implementation of hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => filter_xss($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => filter_xss($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if ($releases) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'hidden', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Build an array of users to whom an issue may be assigned. * * @param $issue * The fully loaded issue node object. * @return * A keyed array in the form uid => name containing users * to whom an issue may be assigned. */ function project_issue_assigned_choices($issue) { // Setup the array of choices for who the issue is assigned to. $assigned = array(); foreach (module_implements('project_issue_assignees') as $module) { $function = "{$module}_project_issue_assignees"; $function($assigned, $issue); } natcasesort($assigned); diff --git a/project_issue.module b/project_issue.module index fe65c70..0a536d5 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,567 +1,567 @@ <?php -// $Id: project_issue.module,v 1.168 2009/06/18 03:23:04 dww Exp $ +// $Id: project_issue.module,v 1.169 2009/06/18 03:24:02 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. module_load_include('inc', 'project_issue', 'issue'); foreach (array('comment', 'mail') as $file) { module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, - 'file' => 'issue.inc', + 'file' => 'includes/statistics.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, - 'file' => 'issue.inc', + 'file' => 'includes/statistics.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue'); } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'issue.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing
Br3nda/drupal-module-project_issue
a7856e018f5f6529a0cf25023e31e2c1a5e38f3d
#405478 by dww: Proper page split of project_issue: - renamed comment.inc to includes/comment.inc - renamed mail.inc to includes/mail.inc
diff --git a/project_issue.module b/project_issue.module index 5c6ebc5..fe65c70 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,880 +1,881 @@ <?php -// $Id: project_issue.module,v 1.167 2009/06/15 03:53:05 dww Exp $ +// $Id: project_issue.module,v 1.168 2009/06/18 03:23:04 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. - foreach (array('issue', 'comment', 'mail') as $file) { - module_load_include('inc', 'project_issue', $file); + module_load_include('inc', 'project_issue', 'issue'); + foreach (array('comment', 'mail') as $file) { + module_load_include('inc', 'project_issue', "includes/$file"); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue'); } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( - 'file' => 'comment.inc', + 'file' => 'includes/comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( - 'file' => 'comment.inc', + 'file' => 'includes/comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'issue.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( - 'file' => 'mail.inc', + 'file' => 'includes/mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( - 'file' => 'mail.inc', + 'file' => 'includes/mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } /** * Implement hook_load() for project issue nodes. */ function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { foreach ($nids as $nid) { project_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE;
Br3nda/drupal-module-project_issue
5ee53fd16e08cd773d5b1dabd3619ef8338c4f8d
#405478: Renamed from mail.inc to includes/mail.inc
diff --git a/includes/mail.inc b/includes/mail.inc new file mode 100644 index 0000000..2ec6a19 --- /dev/null +++ b/includes/mail.inc @@ -0,0 +1,660 @@ +<?php +// $Id: mail.inc,v 1.122 2009/06/18 03:05:25 dww Exp $ + +function project_issue_mailhandler($node, $result, $i, $header, $mailbox) { + if ($node->type == 'project') { + if (node_access('create', 'project_issue')) { + $node->nid = preg_replace('/@.+/', '', $node->nid); + + if ($node->nid) { + /* + ** Base the new entry on the node it belongs to, this ensures all + ** values are initially correct. + */ + $entry = node_load(array('nid' => $node->nid, 'type' => 'project_issue')); + } + + // Possible attributes + $fields = array( + 'pid' => t('Project'), + 'category' => t('Category'), + 'component' => t('Component'), + 'priority' => t('Priority'), + 'rid' => t('Version'), + 'assigned' => t('Assigned to'), + 'sid' => t('Status') + ); + + /* + ** Only change the title if it doesn't have the old title in it. + ** This should prevent the title from changing due to added + ** prefixes. It may on occasion make false positives, but if + ** a title change is that minor who cares? + */ + $entry->title = (strpos($node->title, $entry->title)) ? $entry->title : $node->title; + + $entry->teaser = $node->teaser; + $entry->body = $node->body; + $entry->uid = $node->uid; + + foreach ($fields as $var => $text) { + $text = strtolower(str_replace(' ', '_', $text)); + if (isset($node->project_issue[$text])) { + $node->project_issue[$text] = trim($node->project_issue[$text]); + switch ($var) { + case 'pid': + $project = node_load($node->project_issue[$text]); + if ($project->nid) { + $entry->project_issue['pid'] = $project->nid; + } + break; + case 'category': + if (($category = array_search($node->project_issue[$text], project_issue_category(0, 0)))) { + $entry->project_issue['category'] = $category; + } + break; + case 'priority': + if (($priority = array_search($node->project_issue[$text], project_issue_priority()))) { + $entry->project_issue['priority'] = $priority; + } + break; + case 'rid': + if ($entry->project_issue['pid'] && ($nid = db_result(db_query("SELECT nid FROM {project_release_nodes} WHERE pid = %d AND version = '%s'", $entry->project_issue['pid'], $node->project_issue[$text]), 0))) { + $entry->project_issue['rid'] = $nid; + } + break; + case 'assigned': + if ($user = user_load(array('name' => $node->project_issue[$text]))) { + $entry->project_issue['assigned'] = $user->uid; + } + break; + case 'sid': + if (($state = array_search($node->project_issue[$text], project_issue_state()))) { + $entry->project_issue['sid'] = $state; + } + break; + case 'component': + if ($entry->project_issue['pid'] && ($project = node_load(array('nid' => $entry->project_issue['pid'], 'type' => 'project_project')))) { + if ($project && in_array($node->project_issue[$text], $project->project_issue['components'])) { + $entry->project_issue['component'] = $node->project_issue[$text]; + } + } + break; + } + } + } + + if (empty($entry->nid)) { + $entry->sid = variable_get('project_issue_default_state', 1); + $entry->type = 'project_issue'; + $entry = node_validate($entry, $error); + $error or ($entry->nid = node_save($entry)); + } + else { + $error = project_comment_validate($entry); + $error or project_comment_save($entry); + } + } + else { + $error['user'] = t('You are not authorized to access this page.'); + } + + if ($error && $mailbox['replies']) { + // Send the user his errors + $mailto = mailhandler_get_fromaddress($header, $mailbox); + $mailfrom = variable_get('site_mail', ini_get('sendmail_from')); + $headers = array( + 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', + ); + + $body = t('You had some errors in your submission:'); + foreach ($error as $field => $text) { + $body .= "\n * $field: $text"; + } + + drupal_mail('project_issue_mailhandler_error', $mailto, t('E-mail submission to !sn failed - !subj', array('!sn' => variable_get('site_name', 'Drupal'), '!subj' => $header->subject)), $body, $mailfrom, $headers); + } + + // Return a NULL result so mailhandler doesn't save the node using the default methods. + return NULL; + } + else { + return $node; + } +} + +function project_mail_urls($url = 0) { + static $urls = array(); + if ($url) { + // If $url is an internal link (eg. '/project/project'), such + // as might be returned from the url() function with the + // $absolute parameter set to FALSE, we must remove + // the leading slash before passing this path through the url() + // function again, or otherwise we'll get two slashes in a row + // and thus a bad URL. + if (substr($url, 0, 1) == '/') { + $url = substr($url, 1); + } + $urls[] = strpos($url, '://') ? $url : url($url, array('absolute' => TRUE)); + return count($urls); + } + return $urls; +} + +function project_mail_output(&$body, $html = 1, $format = FILTER_FORMAT_DEFAULT) { + static $i = 0; + + if ($html) { + $body = check_markup($body, $format, FALSE); + $pattern = '@<a +([^ >]+ )*?href *= *"([^>"]+?)"[^>]*>([^<]+?)</a>@ei'; + $body = preg_replace($pattern, "'\\3 ['. project_mail_urls('\\2') .']'", $body); + $urls = project_mail_urls(); + if (count($urls)) { + $body .= "\n"; + for ($max = count($urls); $i < $max; $i++) { + $body .= '['. ($i + 1) .'] '. $urls[$i] ."\n"; + } + } + + $body = preg_replace('!</?blockquote>!i', '"', $body); + $body = preg_replace('!</?(em|i)>!i', '/', $body); + $body = preg_replace('!</?(b|strong)>!i', '*', $body); + $body = preg_replace("@<br />(?!\n)@i", "\n", $body); + $body = preg_replace("@</p>(?!\n\n)@i", "\n\n", $body); + $body = preg_replace("@<li>@i", "* ", $body); + $body = preg_replace("@</li>\n?@i", "\n", $body); + $body = strip_tags($body); + $body = decode_entities($body); + $body = wordwrap($body, 72); + } + else { + $body = decode_entities($body); + } +} + +function project_mail_notify($nid) { + global $user; + + if (defined('PROJECT_NOMAIL')) { + return; + } + + $node = node_load($nid, NULL, TRUE); + $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); + + // Store a copy of the issue, so we can load the original issue values + // below. + $issue = drupal_clone($node); + + // Load in the original issue data here, since we want a running + // reverse history. + $original_issue_data = unserialize($node->project_issue['original_issue_data']); + $fields = project_issue_field_labels('email'); + foreach ($fields as $field => $label) { + if ($field != 'name' && $field != 'updator') { + $issue->original_issue_metadata->$field = $original_issue_data->$field; + } + } + + // Record users that are connected to this issue. + $uids = array(); + if (!empty($node->uid)) { + $uids[$node->uid] = $node->uid; + } + if (!empty($node->project_issue['assigned'])) { + $uids[$node->project_issue['assigned']] = $node->project_issue['assigned']; + } + + // Create complete history of the bug report. + $history = array($issue); + $result = db_query('SELECT u.name, c.cid, c.nid, c.subject, c.comment, c.uid, c.format, pic.* FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid INNER JOIN {users} u ON u.uid = c.uid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp', $node->nid, COMMENT_PUBLISHED); + + while ($comment = db_fetch_object($result)) { + $comment->comment = db_decode_blob($comment->comment); + $comment->files = comment_upload_load_files($comment->cid); + $history[] = $comment; + // Record users that are connected to this issue. + if ($comment->uid) { + $uids[$comment->uid] = $comment->uid; + } + } + + if (count($uids)) { + $placeholders = implode(',', array_fill(0, count($uids), '%d')); + array_unshift($uids, $node->project_issue['pid']); + $result = db_query("SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND (p.level = 2 OR (p.level = 1 AND u.uid IN ($placeholders)))", $uids); + } + else { + $result = db_query('SELECT p.*, u.uid, u.name, u.mail FROM {project_subscriptions} p INNER JOIN {users} u ON p.uid = u.uid WHERE u.status = 1 AND p.nid = %d AND p.level = 2', $node->project_issue['pid']); + } + + // To save workload, check here if either the anonymous role or the + // authenticated role has the 'view uploaded files' permission, since + // we only need to process each user's file access permission if this + // is NOT the case. + $check_file_perms = !db_result(db_query("SELECT COUNT(*) FROM {permission} WHERE perm LIKE '%view uploaded files%' AND rid IN (%d, %d)", DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID)); + + // We need to determine if node_access() checks are necessary. The + // check will be needed if any of the following is true: + // 1. The node is not published. + // 2. There is at least on node access control module enabled. + // 3. Both the anonymous and authenticated user do not have + // the 'access project issues' permission. + $allowed_roles = user_roles(FALSE, 'access project issues'); + if (isset($allowed_roles[DRUPAL_ANONYMOUS_RID]) || isset($allowed_roles[DRUPAL_AUTHENTICATED_RID])) { + $anon_auth_access = TRUE; + } + $grants = module_implements('node_grants'); + $check_node_access = $node->status != 1 || !$anon_auth_access || !empty($grants); + + $params['node'] = $node; + $params['project'] = $project; + $params['history'] = $history; + + $sender->name = t('!name (!site)', array('!name' => $user->name, '!site' => variable_get('site_name', 'Drupal'))); + $sender->mail = strtr(variable_get('project_issue_reply_to', variable_get('site_mail', ini_get('sendmail_from'))), array('%project' => $project->project['uri'])); + // The sender name is enclosed by double quotes below + // to satisfy RFC2822 <http://www.faqs.org/rfcs/rfc2822.html>, + // which requires double quotes when special characters (including + // some punctuation) are used. See example in Appendix A.1.2. + $from = '"' . mime_header_encode($sender->name) . "\" <$sender->mail>"; + + while ($recipient = db_fetch_object($result)) { + // To save work, only go through a user_load if we need it. + if ($check_file_perms || $check_node_access) { + $account = user_load(array('uid' => $recipient->uid)); + $language = user_preferred_language($account); + } + else { + $language = language_default(); + } + + $can_access = $check_node_access ? node_access('view', $node, $account) : TRUE; + + if ($can_access) { + $display_files = $check_file_perms ? user_access('view uploaded files', $account) : TRUE; + + $params['display_files'] = $display_files; + drupal_mail('project_issue', 'project_issue_update_notification', $recipient->mail, $language, $params, $from); + } + } + + if (is_array($project->project_issue['mail_copy_filter']) && count(array_filter($project->project_issue['mail_copy_filter'])) && !$project->project_issue['mail_copy_filter'][$node->project_issue['category']]) { + return; + } + + if (is_array($project->project_issue['mail_copy_filter_state']) && count(array_filter($project->project_issue['mail_copy_filter_state'])) && !$project->project_issue['mail_copy_filter_state'][$node->project_issue['sid']]) { + return; + } + + if (!empty($project->project_issue['mail_copy'])) { + $params['display_files'] = TRUE; + $message['body'][] = $links; + $message['body'][] = project_mail_generate_followup_mail_body($node, $history, TRUE); + drupal_mail('project_issue', 'project_issue_update_notification', $project->project_issue['mail_copy'], language_default(), $params, $from); + } +} + +/* + * Implementation of hook_mail() + */ +function project_issue_mail($key, &$message, $params) { + global $base_url; + + switch ($key) { + case "project_issue_update_notification": + // There could be stale data in the cached node, so reset the cache. + $node = $params['node']; + $project = $params['project']; + $history = $params['history']; + $fields = project_issue_field_labels('email'); + + $domain = preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url); + + $message['headers'] += array( + 'Date' => date('r'), + 'X-Mailer' => 'Drupal Project module (http://drupal.org/project/project)', + 'List-Id' => "$project->title <". $project->project['uri'] ."-issues-$domain>", + 'List-Archive' => '<'. url('project/issues/'. $project->project['uri'], array('absolute' => TRUE)) .'>', + 'List-Subscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>', + 'List-Unsubscribe' => '<'. url('project/issues/subscribe-mail/'. $project->project['uri'], array('absolute' => TRUE)) .'>' + ); + + // Comments exist, set headers accordingly. + if (count($history) > 1) { + foreach ($history as $comment) { + // We need the most recent cid and the next most recent cid for the + // message headers. Instead of issuing another query, just keep track + // of them here. + $previous_cid = isset($cid) ? $cid : ''; + $cid = isset($comment->cid) ? $comment->cid : 0; + } + $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&cid=$cid&host=@$domain>"; + $message['headers']['In-Reply-To'] = "<type=project&nid=$node->nid&host=@$domain>"; + $message['headers']['References'] = "<type=project&nid=$node->nid&host=@$domain> <type=project&nid=$node->nid&cid=$previous_cid&host=@$domain> <type=project&nid=$node->nid&revcount=1&host=@$domain>"; + } else { + // Only original issue in this email. + $message['headers']['Message-Id'] = "<type=project&nid=$node->nid&host=@$domain>"; + } + + project_mail_output($node->title, 0); + $message['subject'] = t('[!short_name] [!category] !title', array('!short_name' => $project->project['uri'], '!category' => $node->project_issue['category'], '!title' => $node->title)); + + // Create link to related node + $links = t('Issue status update for !link', array('!link' => "\n". url("node/$node->nid", array('absolute' => TRUE)))) ."\n"; + $links .= t('Post a follow up: !link', array('!link' => "\n". url("comment/reply/$node->nid", array('fragment' => 'comment-form', 'absolute' => TRUE)))) ."\n"; + $message['body'][] = $links; + $message['body'][] = project_mail_generate_followup_mail_body($node, $history, $params['display_files']); + + break; + + case 'project_issue_critical_summary': + $project = $params['project']; + $message['headers'] += array( + 'Date' => date('r'), + 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', + 'List-Id' => "$project->title <". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'-project-issues-digest>', + 'List-Archive' => '<'. url('project/issues', array('query' => array('priorities' => '1'), 'absolute' => TRUE)) .'>', + ); + $message['subject'] = t('Release critical bugs for !date', array('!date' => date('F d, Y', time()))); + $message['body'][] = $params['body']; + break; + + case 'project_issue_reminder': + $sender->name = variable_get('site_name', ''); + $sender->mail = variable_get('site_mail', ''); + $message['headers'] += array( + 'Return-Path' => "<$sender->mail;>", + 'Date' => date('r'), + 'From' => "$sender->name <$sender->mail>", + 'X-Mailer' => 'Drupal Project Issues module (http://drupal.org/project/project_issue)', + 'List-Id' => "$sender->name <project-reminder-". preg_replace('|.+://([a-zA-Z0-9\._-]+).*|', '\1', $base_url) .'>', + 'List-Archive' => '<'. url('project', array('absolute' => TRUE)) .'>', + ); + $message['subject'] = t('Your submitted bugs for !date', array('!date' => date('F d, Y', time()))); + $message['body'][] = $params['body']; + break; + } +} + +/** + * Format the body of an issue followup email. + * + * @param $node + * The issue node. + * @param $history + * An array containing the history of issue followups. + * @param $display_files + * Boolean indicating if file attachments should be displayed. + * @return + * A string of the email body. + */ +function project_mail_generate_followup_mail_body($node, $history, $display_files) { + global $user; + static $output_with_files = NULL, $output_without_files = NULL; + + // Return cached output if available. + if ($display_files) { + if (isset($output_with_files)) { + return $output_with_files; + } + } + else { + if (isset($output_without_files)) { + return $output_without_files; + } + } + + // Get most recent update. + $entry = array_pop($history); + + $node->project_issue['updator'] = $entry->name ? $entry->name : $user->name; + + // Check if the latest entry is actually the initial issue. + if (empty($history)) { + $metadata_previous = new stdClass(); + // Have to get the metadata into the entry object. + $metadata_entry = $entry->original_issue_metadata; + $content = $entry->body; + } + else { + $metadata_previous = end($history); + // If the previous was the original issue, then we need to pull + // out the metadata from project_issue. + if (isset($metadata_previous->original_issue_metadata)) { + $metadata_previous = $metadata_previous->original_issue_metadata; + } + $metadata_entry = $entry; + $content = $entry->comment; + } + + $fields = project_issue_field_labels('email'); + $comment_changes = project_issue_metadata_changes($node, $metadata_previous, $metadata_entry, $fields); + + // Since $node->name will always be the original issue author, and since + // $node->project_issue['updator'] isn't a property of either $previous or + // $entry, these two properties will never show up as being different when + // project_issue_metadata_changes() is called, and therefore neither of + // these will ever be elements of the $comment_changes array. Since we do + // want them to be printed in issue emails, we just need to add their labels + // back into the $comment_changes array here, so that + // theme_project_issue_mail_summary_field() will know to print the data for + // these two fields. + $comment_changes['name'] = array( + 'label' => $fields['name'], + ); + $comment_changes['updator'] = array( + 'label' => $fields['updator'], + ); + + $summary = theme('project_issue_mail_summary', $entry, $node, $comment_changes, $display_files); + + // Create main body content + project_mail_output($content, 1, $entry->format); + $body = "$content\n$entry->name\n"; + + $hr = str_repeat('-', 72); + + if (count($history)) { + + $body .= "\n\n"; + $body .= t('Original issue:') ."\n"; + $body .= project_mail_format_entry(array_shift($history), $display_files, TRUE); + if (count($history)) { + $body .= "\n". t('Previous comments (!count):', array('!count' => count($history))) ."\n"; + foreach ($history as $entry) { + $body .= project_mail_format_entry($entry, $display_files); + } + } + } + + $output = "$summary\n$body"; + + // Set cached output. + if ($display_files) { + $output_with_files = $output; + } + else { + $output_without_files = $output; + } + + return $output; +} + +/** + * Themes the display of the issue metadata summary + * that is shown at the top of an issue emai. + * + * @param $entry + * The object representing the current entry. This will be a node object + * if the current entry is the original issue node; otherwise this will be + * a comment object. + * @param $node + * The original issue node object. + * @param $changes + * A nested array containing the metadata changes between the original + * issue and the first comment, or two consecutive comments. This array + * is the output of the project_issue_metadata_changes() function. + * @param $display_files + * Boolean indicating if file attachments should be displayed. + * @return + * A string containing the themed text of the issue metadata table. + */ +function theme_project_issue_mail_summary($entry, $node, $changes, $display_files) { + // Mail summary (status values). + $summary = ''; + foreach ($changes as $field => $change) { + $summary .= theme('project_issue_mail_summary_field', $node, $field, $change); + } + + $summary .= project_mail_format_attachments($entry, $display_files); + return $summary; +} + +/** + * Theme the email output of one project issue metadata field. + * + * @param $node + * The project issue node object. + * @param $field_name + * The name of the field to theme. + * @param $change + * A nested array containing changes to project issue metadata + * for the given issue or comment. + * @return + * A themed line or lines of text ready for inclusion into the email body. + */ +function theme_project_issue_mail_summary_field($node, $field_name, $change) { + // We need to run the label name through strip_tags here so that + // the spacing isn't messed up if there are HTML tags in $change['label']. + $text = str_pad(strip_tags($change['label']). ':', 14); + $summary_row = ''; + if (!empty($change['label']) && isset($change['old']) && isset($change['new']) && $field_name != 'updator' && $field_name != 'name') { + if (is_array($change['old']) || is_array($change['new'])) { + $removed = array(); + if (is_array($change['old'])) { + foreach ($change['old'] as $item) { + $removed[] = '-'. $item; + } + } + elseif (!empty($change['old'])) { + $removed[] = '-'. $change['old']; + } + + $added = array(); + if (is_array($change['new'])) { + foreach ($change['new'] as $item) { + $added[] = '+'. $item; + } + } + elseif (!empty($change['new'])) { + $added[] = '+'. $change['new']; + } + + $summary_row = " $text". trim(implode(', ', $removed). ' ' .implode(', ', $added)) ."\n"; + } + else { + $summary_row .= "-$text". project_issue_change_summary($field_name, $change['old']) ."\n"; + $summary_row .= "+$text". project_issue_change_summary($field_name, $change['new']) ."\n"; + } + } + elseif (!empty($change['label'])) { + if (!empty($change['new'])) { + // This condition is necessary when building the first email message of an + // issue, since in this case $change['old'] should not exist. + if (is_array($change['new'])) { + $summary_row .= " $text". implode(', ', $change['new']) ."\n"; + } + else { + $summary_row .= " $text". project_issue_change_summary($field_name, $change['new']) ."\n"; + } + } + else { + // This condition is where fields that are stored in the $node object and + // which haven't changed but should be printed anyway get processed. + // For example, the project, category, etc. are printed in each email + // whether or not they have changed. + // @TODO: Should we really assume the field in is $node->project_issue[]? + if (isset($node->project_issue[$field_name])) { + $summary_row .= " $text". project_issue_change_summary($field_name, $node->project_issue[$field_name]) ."\n"; + } + } + } + // HTML tags in the email will make it hard to read, so pass + // this output through strip_tags(). + return strip_tags($summary_row); +} + +/** + * Formats attachments for issue notification e-mails. + * + * @param $entry + * An issue or followup object containing the file data. + * @param $display_files + * Boolean indicating if file attachments should be displayed. + * @return + * A formatted string of file attachments. + */ +function project_mail_format_attachments($entry, $display_files) { + $output = ''; + if ($display_files && is_array($entry->files)) { + foreach ($entry->files as $file) { + // Comment upload has it's files in an array, so cast to an object + // for consistency. + $file = (object) $file; + $output .= ' '. str_pad(t('Attachment') .':', 14) . file_create_url($file->filepath) .' ('. format_size($file->filesize) .")\n"; + } + } + return $output; +} + +/** + * Format an issue entry for display in an email. + * + * @param entry + * The entry to the formatted. + * @param $display_files + * Boolean indicating if file attachments should be displayed. + * @param is_original + * Whether this entry is the original issue or a followup. Followup issues + * will be automatically numbered. + * @return + * Formatted text for the entry. + */ +function project_mail_format_entry($entry, $display_files, $is_original = FALSE) { + static $history_count = 1; + $hr = str_repeat('-', 72); + $output = "$hr\n"; + + // Nodes and comments have different stamp fields. + $timestamp = isset($entry->created) ? $entry->created : $entry->timestamp; + + if (!$is_original) { + $output .= "$entry->subject -- "; + } + + $output .= format_date($timestamp, 'large') ." : $entry->name\n"; + + if (!$is_original) { + $output .= url("node/$entry->nid", array('fragment' => "comment-$entry->cid", 'absolute' => TRUE)) ."\n"; + } + + $output .= project_mail_format_attachments($entry, $display_files); + + // Must distinguish between nodes and comments -- here we do it + // by looking for a revision ID. + if (empty($entry->vid)) { + $content = $entry->comment; + } + else { + $content = $entry->body; + } + + project_mail_output($content, 1, $entry->format); + + if ($content) { + $output .= "\n$content"; + } + return $output; +} +
Br3nda/drupal-module-project_issue
2eef3eb80c20491f7626b00a83921e49fab366d3
#405478: Renamed from comment.inc to includes/comment.inc
diff --git a/includes/comment.inc b/includes/comment.inc new file mode 100644 index 0000000..9328fe0 --- /dev/null +++ b/includes/comment.inc @@ -0,0 +1,664 @@ +<?php +// $Id: comment.inc,v 1.154 2009/06/18 03:05:20 dww Exp $ + +function project_issue_comment(&$arg, $op) { + // $arg can be a comment object, or a form or form_values. + if (is_object($arg)) { + $nid = $arg->nid; + } + elseif (is_array($arg)) { + $nid = is_array($arg['nid']) ? $arg['nid']['#value'] : $arg['nid']; + } + $node = node_load($nid); + if ($node->type != 'project_issue') { + return; + } + // Make a copy here so we have all the original metadata, since some + // of it can change below. + $original_node = drupal_clone($node); + $old_data = (object) $original_node->project_issue; + $old_data->title = $original_node->title; + + // Maintain an array of project ids that are affected by this comment + // operation. We'll use this to invalidate the "Issue cockpit" block cache + // for any of these projects. + $affected_projects = array(); + + switch ($op) { + case 'insert': + // Get a lock on the issue in order to generate the next comment ID. + $tries = 20; + $sleep_increment = 0; + while ($tries) { + $lock = db_query("UPDATE {project_issues} SET db_lock = 1 WHERE nid = %d AND db_lock = 0", $arg['nid']); + if (db_affected_rows()) { + $id = db_result(db_query("SELECT last_comment_id FROM {project_issues} WHERE nid = %d", $arg['nid'])) + 1; + db_query("UPDATE {project_issues} SET last_comment_id = %d, db_lock = 0 WHERE nid = %d", $id, $arg['nid']); + break; + } + + // Wait a random and increasing amount of time before the next attempt. + $sleep = rand(10000, 1000000) + $sleep_increment; + usleep($sleep); + $sleep_increment += 50000; + $tries--; + } + + if (isset($id)) { + $rid = isset($arg['project_info']['rid']) ? $arg['project_info']['rid'] : 0; + db_query("INSERT INTO {project_issue_comments} (nid, cid, pid, rid, component, category, priority, assigned, sid, title, timestamp, comment_number) VALUES (%d, %d, %d, %d, '%s', '%s', %d, %d, %d, '%s', %d, %d)", $arg['nid'], $arg['cid'], $arg['project_info']['pid'], $rid, $arg['project_info']['component'], $arg['category'], $arg['priority'], $arg['project_info']['assigned'], $arg['sid'], $arg['title'], $arg['timestamp'], $id); + db_query("UPDATE {comments} SET subject = '%s' WHERE cid = %d", "#$id", $arg['cid']); + project_issue_update_by_comment($arg, 'insert'); + $affected_projects[$old_data->pid] = 1; + $affected_projects[$arg['project_info']['pid']] = 1; + } + else { + drupal_set_message(t('There was an error submitting your comment -- please try again. If the problem persists, contact the system administrator.'), 'error'); + watchdog('project_issue', 'Error obtaining lock for project issue %nid', array('%nid' => $arg['nid']), WATCHDOG_ERROR, 'node/'. $arg['nid']); + // This is a bit extreme, but we have to clean up the failed comment, + // or it will appear on the issue. + _comment_delete_thread((object) $arg); + _comment_update_node_statistics($arg['nid']); + cache_clear_all(); + // The hard redirect prevents any bogus data from being inserted for the failed comment. + drupal_goto('node/'. $arg['nid']); + } + break; + + case 'update': + project_issue_update_by_comment($arg, 'update'); + // Updating a comment can't change anything relevant about the issue for + // the purposes of the issue blocks, so we don't need to touch + // $affected_projects here. + break; + + case 'delete': + // Save the project that's specified in this comment so we can + // invalidate its issue block cache. + $deleted_comment_project_id = db_result(db_query("SELECT pid FROM {project_issue_comments} WHERE cid = %d", $arg->cid)); + $affected_projects[$deleted_comment_project_id] = 1; + // Actually delete the comment + db_query("DELETE FROM {project_issue_comments} WHERE cid = %d", $arg->cid); + $current_data = project_issue_update_by_comment($arg, 'delete'); + // We should also invalidate the block cache for whatever project is now + // used for this issue, since we might be deleting a comment that moved + // an issue from one project to another. + $affected_projects[$current_data->pid] = 1; + break; + + case 'view': + if (isset($arg->cid)) { + $project_issue_table = project_issue_comment_view($original_node, $arg); + } + else { + // Previewing a comment. + $test = drupal_clone($arg); + $test->pid = $arg->project_info['pid']; + $test->component = $arg->project_info['component']; + $test->assigned = $arg->project_info['assigned']; + // Add a dummy rid if necessary -- prevents incorrect change data. + $test->rid = isset($arg->project_info['rid']) ? $arg->project_info['rid'] : 0; + $comment_changes = project_issue_metadata_changes($node, $old_data, $test, project_issue_field_labels('web')); + $project_issue_table = theme('project_issue_comment_table', $comment_changes); + } + if ($project_issue_table) { + $arg->comment = '<div class="project-issue"><div class="summary">'. $project_issue_table .'</div></div>' . $arg->comment; + } + break; + + } + // If there are any affected projects, invalidate the block cache for those. + if (!empty($affected_projects)) { + foreach ($affected_projects as $pid => $value) { + $cid = 'project_issue_cockpit_block:'. $pid; + cache_clear_all($cid, 'cache'); + } + } +} + +/** + * Add project issue metadata to the comment form. + * + * @param $form + * Reference to form structure. + * @param $form_state + * Current form state. + */ +function project_issue_form_comment_form_alter(&$form, &$form_state) { + $nid = $form['nid']['#value']; + $node = node_load($nid); + + // Allows only project_issue + if ($node->type != 'project_issue') { + return; + } + + // Comment body is not required since we validate that ourselves. + unset($form['comment_filter']['comment']['#required']); + + // The 'your name' item just wastes screen estate. + unset($form['_author']); + + // For existing comments, we want to preserve the comment subject, + // Even if the subject field is disabled. + if ($cid = $form['cid']['#value']) { + $subject = db_result(db_query('SELECT subject FROM {comments} WHERE cid = %d', $cid)); + } + // For new comments, show the expected next number for previews. + // This is only for show, the number will be generated when the comment + // is posted. + else { + $next_id = db_result(db_query('SELECT last_comment_id FROM {project_issues} WHERE nid = %d', $form['nid']['#value'])) + 1; + $subject = "#$next_id"; + // Clobber the comment signature for new followups if necessary. + // TODO: Revamp this for Drupal 6. + if (!variable_get('project_issue_show_comment_signatures', 0)) { + $form['comment_filter']['comment']['#default_value'] = ''; + } + } + $form['subject'] = array( + '#type' => 'value', + '#value' => $subject, + ); + + // Any time we're on a reply page, show the full issue below the reply. + if (project_issue_is_comment_reply()) { + $form['#pre_render'][] = 'project_issue_comment_pre_render'; + } + + // Make sure project is current here -- it may have changed when posted. + if (!empty($form_state['values']['project_info']['pid'])) { + $node->project_issue['pid'] = $form_state['values']['project_info']['pid']; + } + $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); + + project_issue_set_breadcrumb($node, $project); + + // Only allow metadata changes on new followups. + if (isset($form['cid']['#value'])) { + return; + } + + // We have to set $form['#action'] to prevent AHAH nastiness. + if (!empty($form['pid']['#value'])) { + $form['#action'] = url('comment/reply/' . $nid . '/' . $form['pid']['#value']); + } + else { + $form['#action'] = url('comment/reply/' . $nid); + } + + // We need to ask for almost the same metadata as project issue itself + // so let's reuse the form. + $form += drupal_retrieve_form('project_issue_form', $node, $form_state, TRUE); + + // We need this otherwise pid collides with comment. + $form['project_info']['#tree'] = TRUE; + $form['project_info']['#weight'] = -2; + + // Remove the form item that displays the current project, and + // replace the static single project value with a select list + // of all projects to make swapping simpler. + unset($form['project_info']['project_display']); + $uris = NULL; + + if (variable_get('project_issue_autocomplete', 0) == 1) { + $form['project_info']['project_title'] = array( + '#type' => 'textfield', + '#title' => t('Project'), + '#default_value' => $project->title, + '#required' => TRUE, + '#weight' => -1, + '#size' => 35, + '#autocomplete_path' => 'project/autocomplete/issue/project', + '#attributes' => array( + 'onFocus' => 'project_issue_autocomplete_handler()', + ), + '#ahah' => array( + 'progress' => array( + 'type' => 'none', + ), + 'path' => 'project/issues/update_project', + 'wrapper' => 'project-info-wrapper', + ), + ); + } + else { + $projects = project_projects_select_options($uris); + $form['project_info']['pid'] = array( + '#type' => 'select', + '#title' => t('Project'), + '#default_value' => $project->nid, + '#options' => $projects, + '#required' => TRUE, + '#weight' => -1, + '#ahah' => array( + 'path' => 'project/issues/update_project', + 'wrapper' => 'project-info-wrapper', + 'event' => 'change', + ), + ); + } + + $form['issue_info']['#weight'] = -1; + $form['#prefix'] = '<div class="project-issue"><div class="node-form"><div class="standard">'; + $form['#suffix'] = '</div></div></div>'; + + $form['original_issue'] = array( + '#type' => 'fieldset', + '#title' => t('Edit issue settings'), + '#description' => t('Note: changing any of these items will update the issue\'s overall values.'), + '#collapsible' => TRUE, + '#weight' => -10, + ); + + $form['original_issue']['title'] = array( + '#type' => 'textfield', + '#title' => t('Issue title'), + '#maxlength' => 128, + '#default_value' => $node->title, + '#weight' => -30, + '#required' => TRUE, + ); + + $form['project_info']['assigned'] = $form['issue_info']['assigned']; + unset($form['issue_info']['assigned']); + + $form['project_info']['#prefix'] = '<div id="project-info-wrapper" class="inline-options">'; + $form['project_info']['#suffix'] = '</div>'; + + // Remove the 'Project information' and 'Issue information' fieldsets, + // since we'll move everything inside the 'Edit issue settings' fieldset. + unset($form['project_info']['#type'], $form['project_info']['#title']); + unset($form['issue_info']['#type'], $form['issue_info']['#title']); + + // Restructure the UI to de-emphasize the original project form inputs. + $form['original_issue']['project_info'] = $form['project_info']; + $form['original_issue']['issue_info'] = $form['issue_info']; + unset($form['project_info'], $form['issue_info']); + unset($form['issue_details'], $form['project_help']); + drupal_add_js(drupal_get_path('module', 'project_issue') .'/project_issue.js'); +} + +/** + * Validate issue metadata on the comment form. + * + * @param $form + * The Drupal form structure. + * @param $form_state + * The current state of the form. + */ +function project_issue_form_comment_validate($form, &$form_state) { + if (empty($form['cid']['#value']) && variable_get('project_issue_autocomplete', 0) == 1) { + if (empty($form_state['values']['project_info']['project_title'])) { + form_set_error('project_title', t('You must enter a project to navigate to.')); + } + else { + $pid = db_result(db_query("SELECT nid FROM {node} WHERE title = '%s' AND type = '%s'", $form_state['values']['project_info']['project_title'], 'project_project')); + if (empty($pid)) { + form_set_error('project_info][project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_info']['project_title']))); + } + else { + $form_state['values']['project_info']['pid'] = $pid; + } + } + } + + if (!empty($form_state['rebuild'])) { + return; + } + $values = $form_state['values']; + $project_info = $form_state['values']['project_info']; + $nid = $values['nid']; + $node = node_load($nid); + + // Make a copy here so we have all the original metadata, since some + // of it can change below. + $original_node = drupal_clone($node); + $old_data = (object) $original_node->project_issue; + $old_data->title = $original_node->title; + + // Adjust new file attachments to go to the issues directory. + // We have to do this during validate, otherwise we might miss + // adjusting the filename before comment upload saves it (module weighting) + // TODO: is this still true? + project_issue_change_comment_upload_path($values); + + // Only validate metadata changes on new followups. + if (isset($values['cid'])) { + return; + } + + // Make sure project is current here -- it may have changed when posted. + if (isset($project_info['pid'])) { + $node->project_issue['pid'] = $project_info['pid']; + } + $project = node_load($node->project_issue['pid']); + + if (!empty($project) && $project->type == 'project_project') { + // Force all comments to be a child of the main issue, to match the + // flat display, and also to prevent accidentally deleting a thread. + $form_state['values']['pid'] = 0; + + // Validate version. + if (module_exists('project_release') && isset($project_info['rid']) && ($releases = project_release_get_releases($project, 0, 'version', 'all', array($project_info['rid'])))) { + $rid = $project_info['rid']; + if ($rid && !in_array($rid, array_keys($releases))) { + $rid = 0; + } + // Check to make sure this release is not marked as an invalid + // release node for user selection. + $invalid_rids = variable_get('project_issue_invalid_releases', array()); + if (!empty($invalid_rids) && + ((empty($rid) && in_array($node->project_issue['rid'], $invalid_rids)) + || in_array($rid, $invalid_rids))) { + form_set_error('project_info][rid', t('%version is not a valid version, please select a different value.', array('%version' => $releases[$node->project_issue['rid']]))); + } + elseif (empty($rid)) { + form_set_error('project_info][rid', t('You have to specify a valid version.')); + } + } + // Add a dummy rid if necessary -- prevents incorrect change data. + else { + $rid = 0; + } + // Validate component. + $component = $project_info['component']; + if ($component && !in_array($component, $project->project_issue['components'])) { + $component = 0; + } + empty($component) && form_set_error('project_info][component', t('You have to specify a valid component.')); + } + else { + form_set_error('project_info][pid', t('You have to specify a valid project.')); + } + empty($values['category']) && form_set_error('category', t('You have to specify a valid category.')); + + // Now, make sure the comment changes *something* about the issue. + // If the user uploaded a file, so long as it's not marked for removal, + // we consider that a valid change to the issue, too. + $has_file = FALSE; + $files = isset($values['files']) ? $values['files'] : array(); + foreach ($files as $number => $data) { + if (empty($data['remove'])) { + $has_file = TRUE; + break; + } + } + if (!$has_file && empty($values['comment'])) { + + $comment = drupal_clone((object) $values); + $comment->pid = $project_info['pid']; + $comment->component = $component; + $comment->rid = $rid; + $comment->assigned = $project_info['assigned']; + $comment_changes = project_issue_metadata_changes($node, $old_data, $comment, project_issue_field_labels('web')); + // If the PID changed, rebuild the form + if (isset($comment_changes['pid']['new']) && $comment_changes['pid']['new'] === TRUE) { + $form_state['rebuild'] = TRUE; + } + $has_change = FALSE; + foreach ($comment_changes as $field => $changes) { + if (isset($changes['new'])) { + $has_change = TRUE; + break; + } + } + if (!$has_change) { + form_set_error('comment', t('You must either add a comment, upload a file, or change something about this issue.')); + } + } +} + +/** + * Theme a project issue metadata table. + * + * @param $comment_changes + * Array containing metadata differences between comments + * as returned by project_issue_metadata_changes(). + * @return + * The themed metadata table. + */ +function theme_project_issue_comment_table($comment_changes) { + $rows = array(); + foreach ($comment_changes as $field => $change) { + if (!empty($change['label']) && isset($change['old']) && isset($change['new'])) { + $rows[] = theme('project_issue_comment_table_row', $field, $change); + } + } + return theme('table', array(), $rows); +} + +/** + * Theme a single row of the project issue metadata changes table. + * + * @param $field + * The name of the field to theme. + * @param $change + * A nested array containing changes to project issue metadata + * for the given issue or comment. + * @return + * An array representing one row of the table. + * + * NOTE: If you override this theme function, you *must* make sure + * that you sanitize all output from this function that is displayed + * to the user. No further escaping/filtering of the data in this + * table will take place after this function. In most cases + * this means that you need to run the $change['label'], $change['old'], + * and $change['new'] values through either the check_plain() or + * filter_xss() function to prevent XSS and other types + * of problems due to any malicious input in these + * field values. + */ +function theme_project_issue_comment_table_row($field, $change) { + // Allow anchor, emphasis, and strong tags in metadata tables. + $allowed_tags = array('a', 'em', 'strong'); + // Fields that should be rendered as plain text, not filtered HTML. + $plain_fields = array('title', 'pid', 'rid'); + + if (is_array($change['old']) || is_array($change['new'])) { + $removed = array(); + if (is_array($change['old'])){ + foreach ($change['old'] as $item) { + $removed[] = '-'. $item; + } + } + elseif (!empty($change['old'])) { + $removed[] = '-'. $change['old']; + } + + $added = array(); + if (is_array($change['new'])) { + foreach ($change['new'] as $item) { + $added[] = '+'. $item; + } + } + elseif (!empty($change['new'])) { + $added[] = '+'. $change['new']; + } + + return array( + filter_xss($change['label'], $allowed_tags) .':', + filter_xss(implode(', ', $removed), $allowed_tags), + filter_xss(implode(', ', $added), $allowed_tags), + ); + } + elseif (in_array($field, $plain_fields)) { + return array( + filter_xss($change['label'], $allowed_tags) .':', + check_plain(project_issue_change_summary($field, $change['old'])), + '&raquo; '. check_plain(project_issue_change_summary($field, $change['new'])), + ); + } + else { + return array( + filter_xss($change['label'], $allowed_tags) .':', + filter_xss(project_issue_change_summary($field, $change['old']), $allowed_tags), + '&raquo; '. filter_xss(project_issue_change_summary($field, $change['new']), $allowed_tags), + ); + } +} + +/** + * Returns the issue metadata table for a comment. + * + * @param $node + * The corresponding node. + * @param $comment + * The comment, if it's set then metadata will be returned. If it's not + * set then metadata will be precalculated. + * @return + * A themed table of issue metadata. + */ +function project_issue_comment_view(&$node, $comment = NULL) { + static $project_issue_tables; + + if (isset($comment)) { + return isset($project_issue_tables[$comment->cid]) ? $project_issue_tables[$comment->cid] : ''; + } + if (!empty($node->comment_count)) { + $old = unserialize(db_result(db_query('SELECT original_issue_data FROM {project_issues} WHERE nid = %d', $node->nid))); + $labels = project_issue_field_labels('web'); + $result = db_query('SELECT p.cid, p.title, p.pid, p.rid, p.component, p.category, p.priority, p.assigned, p.sid FROM {project_issue_comments} p INNER JOIN {comments} c ON p.cid = c.cid WHERE p.nid = %d AND c.status = %d ORDER BY p.timestamp ASC', $node->nid, COMMENT_PUBLISHED); + while ($followup = db_fetch_object($result)) { + $followup_changes = project_issue_metadata_changes($node, $old, $followup, project_issue_field_labels('web')); + $project_issue_tables[$followup->cid] = theme('project_issue_comment_table', $followup_changes); + $old = $followup; + } + } +} + +/** + * Updates the project issue based on the comment inserted/updated/deleted. + * + * @param $comment_data + * The comment data that's been submitted. + * @param $op + * The comment operation performed, 'insert', 'update', 'delete'. + * @return + * An object representing the comment data used to update the issue. + */ +function project_issue_update_by_comment($comment_data, $op) { + switch ($op) { + case 'insert': + // Massage the incoming data so the structure is consistent throughout the function. + $comment_data['component'] = $comment_data['project_info']['component']; + $comment_data['pid'] = $comment_data['project_info']['pid']; + $comment_data['rid'] = isset($comment_data['project_info']['rid']) ? $comment_data['project_info']['rid'] : 0; + unset ($comment_data['project_info']); + $comment_data = (object) $comment_data; + // Mark the node for email notification during hook_exit(), so all issue + // and file data is in a consistent state before we generate the email. + if (!isset($comment_data->followup_no_mail)) { // Temporary hack to get around sending of auto-close emails. + project_issue_set_mail_notify($comment_data->nid); + } + break; + case 'update': + $comment_data = (object) $comment_data; + break; + } + + // In order to deal with deleted/unpublished comments, make sure that we're performing + // the updates to the issue with the latest available published comment. + $comment_data = project_issue_get_newest_comment($comment_data); + + // Update the issue data to reflect the new final states. + db_query("UPDATE {project_issues} SET pid = %d, category = '%s', component = '%s', priority = %d, rid = %d, assigned = %d, sid = %d WHERE nid = %d", $comment_data->pid, $comment_data->category, $comment_data->component, $comment_data->priority, $comment_data->rid, $comment_data->assigned, $comment_data->sid, $comment_data->nid); + + // Update the issue title. + $node = node_load($comment_data->nid, NULL, TRUE); // Don't use cached since we changed data above. + $node->title = $comment_data->title; + + // This also updates the changed date of the issue. + node_save($node); + + // Return the object of comment data we used to update the issue. + return $comment_data; +} + +/** + * Adjusts the filepath of issue followups so files are saved to + * the correct issues directory. + * + * @param $comment + * An array of the submitted comment values. + */ +function project_issue_change_comment_upload_path(&$comment) { + static $run = NULL; + + // Only for new comments with attachments. + if (empty($comment['cid']) && isset($comment['files']) && !isset($run)) { + $run = TRUE; // Make sure this only gets run once. + project_issue_rewrite_issue_filepath($comment['files']); + } +} + +/** + * Retrieves the newest published comment for an issue. + * + * @param $comment_data + * An object representing the current comment being edited + * @return + * An object representing the most recent published comment for the issue. + */ +function project_issue_get_newest_comment($comment_data) { + // Get the cid of the most recent comment. + $latest_cid = db_result(db_query_range('SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON c.cid = pic.cid WHERE c.nid = %d AND c.status = %d ORDER BY pic.timestamp DESC', $comment_data->nid, COMMENT_PUBLISHED, 0, 1)); + if ($latest_cid) { + $comment_data = db_fetch_object(db_query('SELECT * FROM {project_issue_comments} WHERE cid = %d', $latest_cid)); + } + // No more comments on the issue -- use the original issue metadata. + else { + // nid isn't stored in the original issue data, so capture it here and pass back + // into the object. + $nid = $comment_data->nid; + $comment_data = unserialize(db_result(db_query("SELECT original_issue_data FROM {project_issues} WHERE nid = %d", $comment_data->nid))); + $comment_data->nid = $nid; + } + return $comment_data; +} + +/** + * Test to determine if the active page is the comment reply form. + * + * @return + * TRUE if the active page is the comment reply form, FALSE otherwise. + */ +function project_issue_is_comment_reply() { + return arg(0) == 'comment' && arg(1) == 'reply'; +} + +/** + * Test to determine if the active page is the comment edit form. + * + * @return + * TRUE if the active page is the comment edit form, FALSE otherwise. + */ +function project_issue_is_comment_edit() { + return arg(0) == 'comment' && arg(1) == 'edit'; +} + +/** + * Appends the comment thread to the comment reply form. + */ +function project_issue_comment_pre_render($form) { + // Force the correct formatting. + $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; + $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; + + $suffix = empty($form['#suffix']) ? '' : $form['#suffix']; + $node = node_load($form['nid']['#value']); + + // Unfortunately, the comment module blindly puts the node view + // after the comment form on preview, in the case where the comment + // parent is 0. If we want our issue previews to be consistent, this + // ugly hack is necessary. + if (isset($form['#parameters'][1]['values']['op']) && $form['#parameters'][1]['values']['op'] == t('Preview')) { + $preview = comment_render($node, 0); + } + else { + $preview = node_show($node, 0); + } + + $form['#suffix'] = $suffix . $preview; + return $form; +}
Br3nda/drupal-module-project_issue
372cb65117a782d5fb44e270dadc82c0e7834f4b
#491802 by dww: Fixed PHP notice when adding issues that don't have all their fields (e.g. issues for projects without any releases).
diff --git a/issue.inc b/issue.inc index cd6ef61..1f69089 100644 --- a/issue.inc +++ b/issue.inc @@ -1,1250 +1,1250 @@ <?php -// $Id: issue.inc,v 1.349 2009/06/15 03:53:04 dww Exp $ +// $Id: issue.inc,v 1.350 2009/06/15 04:14:00 dww Exp $ /** * JS callback method to return updated elements on the issue form. * This function is called when someone changes the "Project" selector. */ function project_issue_update_project() { $form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); // Rebuild the form and cache it again. $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); // These used to be path arguments. Now they arrive via form element. $issue_nid = $form['nid']['#value']; $pid = $form_state['values']['project_info']['pid']; $rid = isset($form_state['values']['project_info']['rid']) ? $form_state['values']['project_info']['rid'] : 0; $cid = $form_state['values']['cid']; $assigned_uid = $form_state['values']['project_info']['assigned']; $project_info = $form['original_issue']['project_info']; // Only generate release stuff if the project_release module is enabled. if (module_exists('project_release')) { $project->nid = $pid; if ($releases = project_release_get_releases($project, 0)) { $old_version = db_result(db_query("SELECT version FROM {project_release_nodes} WHERE nid = %d", $rid)); $releases = array(t('<none>')) + $releases; // Since the value of releases is by nid, try to match release // based on the label instead. $default = 0; foreach ($releases as $key => $label) { if ($old_version == $label) { $default = $key; } } // Element is tree'd here to match the original form layout. $project_info['#tree'] = TRUE; $project_info['rid']['#options'] = $releases; $project_info['rid']['#disabled'] = FALSE; if (!empty($default)) { $project_info['rid']['#value'] = $default; $project_info['rid']['#default_value'] = $default; } } else { $project_info['rid']['#disabled'] = TRUE; $project_info['rid']['#options'] = array(); } } // Assigned. if (is_numeric($issue_nid)) { $issue = node_load(array('nid' => $issue_nid, 'type' => 'project_issue')); } else { // @TODO: This case should not ever be hit until // http://drupal.org/node/197281 lands. $issue = new stdClass; } $issue->project_issue['pid'] = $pid; $assigned_choices = project_issue_assigned_choices($issue); $project_info['assigned']['#default_value'] = $assigned_uid; $project_info['assigned']['#options'] = $assigned_choices; // Components. $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $pid)); $components = array(); if ($project->components) { $components = array(t('<none>')); foreach (unserialize($project->components) as $component) { $component = check_plain($component); $components[$component] = $component; } } $project_info['component']['#default_value'] = $cid; $project_info['component']['#options'] = $components; // Build the HTML output for the component select. $output = theme('status_messages') . drupal_render($project_info); drupal_json(array('status' => TRUE, 'data' => $output)); exit; } function project_issue_statistics($project = NULL) { $states = project_issue_state(); if ($project->nid) { $filter = sprintf(' AND p.pid = %d ', (int)$project->nid); project_project_set_breadcrumb($project, TRUE); } $output = '<div class="project-issue">'; // Issue lifetime. $header = array(t('Category'), t('Overall'), t('Last month')); $rows = array(); $duration = time() - 30 * 24 * 60 * 60; $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 GROUP BY p.category'), $filter); while ($stat = db_fetch_object($result)) { $rows[$stat->category][0] = project_issue_category($stat->category); $rows[$stat->category][1] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); $rows[$stat->category][2] = array('data' => t('N/A'), 'class' => 'numeric'); } $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 AND n.created > %d GROUP BY p.category'), $filter, $duration); while ($stat = db_fetch_object($result)) { if ($stat->duration > 0) { $rows[$stat->category][2] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); } } $output .= '<h2>'. t('Average lifetime') .'</h2>'; $output .= theme('table', $header, $rows); $header = array( array('data' => t('Status')), array('data' => t('Overall'), 'class' => 'project-issue-numeric'), array('data' => '%', 'class' => 'project-issue-numeric'), array('data' => t('Last month'), 'class' => 'project-issue-numeric'), ); $rows = array(); // Activity overall. $total = db_result(db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s', 'p'), $filter)); $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s GROUP BY p.sid', 'p'), $filter); while ($stat = db_fetch_object($result)) { $rows[$stat->sid][0] = check_plain(project_issue_state($stat->sid)); $rows[$stat->sid][1] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); $rows[$stat->sid][2] = array('data' => number_format($stat->total / $total * 100) .'%', 'class' => 'project-issue-numeric-light'); $rows[$stat->sid][3] = array('data' => '0', 'class' => 'project-issue-numeric'); } // Activity this month. $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND n.changed > %d GROUP BY p.sid', 'p'), $filter, $duration); while ($stat = db_fetch_object($result)) { $rows[$stat->sid][3] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); } $output .= '<h2>'. t('Issue activity') .'</h2>'; $output .= theme('table', $header, $rows); // Project overview. if (!$project->nid) { // Even though we don't use the tablesorting logic in the query itself, // we include it anyways because we're going to leverage the $_GET arguments // to build our own tablesorting mechanism. $header = array(); $header['project'] = array('data' => t('Project'), 'field' => 'title'); foreach ($states as $key => $value) { $header[$key] = array('data' => check_plain($value), 'field' => $key); } $header['total'] = array('data' => t('Total'), 'field' => 'total'); // Force sorting arrow to appear on active first. $header[1]['sort'] = 'desc'; $args = array(); // Since we're pulling the sid to sort by here individually in the first query // below, we can bastardize the tablesorting logic to get tablesorting. $where = ' AND p.sid = %d'; $column = 'total'; if (isset($_GET['order'])) { switch ($_GET['order']) { case 'Project': $where = ''; $column = 'title'; break; case 'Total': $where = ''; break; default: if ($state = array_search($_GET['order'], $states)) { $args[] = $state; } else { $args[] = 1; } break; } } else { $args[] = 1; } $sort = (isset($_GET['sort']) && $_GET['sort'] == 'desc') || !isset($_GET['sort']) ? 'DESC' : 'ASC'; $rows = array(); $projects = pager_query(db_rewrite_sql("SELECT pn.nid, pn.title, COUNT(n.nid) AS total FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid INNER JOIN {node} pn ON p.pid = pn.nid WHERE n.status = 1 AND pn.status = 1$where GROUP BY pn.nid, pn.title ORDER BY $column $sort"), 15, 0, db_rewrite_sql("SELECT COUNT(DISTINCT(n.nid)) FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.pid INNER JOIN {node} pin ON p.nid = pin.nid WHERE n.status = 1 AND pin.status = 1$where"), $args); $orig = array('project' => array('data' => 0)); foreach ($states as $key => $value) { $orig[$key] = array('data' => '', 'class' => 'project-issue-numeric'); } $orig['total'] = array('data' => '', 'class' => 'project-issue-numeric'); while ($project = db_fetch_object($projects)) { $rows[$project->nid] = $orig; $rows[$project->nid]['project']['data'] = l($project->title, "node/$project->nid"); $stats = db_query("SELECT sid, COUNT(nid) as total FROM {project_issues} WHERE pid = %d GROUP BY sid", $project->nid); while ($stat = db_fetch_object($stats)) { $rows[$project->nid]['total']['data'] += $stat->total; $rows[$project->nid][$stat->sid]['data'] = $stat->total; } } $output .= '<h2>'. t('Project overview') .'</h2>'; $output .= '<div class="project-issue-statistics-overview-table">'; $output .= theme('table', $header, $rows); if ($pager = theme('pager', 15, 0)) { $output .= $pager; } $output .= '</div>'; } $output .= '</div>'; return $output; } function project_issue_subscribe_submit($form, &$form_state) { global $user; $all = $form_state['clicked_button']['#value']; $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); // Remove previous subscriptions for user. if (isset($form_state['values']['single'])) { db_query('DELETE FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $form_state['values']['single'], $user->uid); } else { db_query('DELETE FROM {project_subscriptions} WHERE uid = %d', $user->uid); } $_level = array_search($all, $levels); foreach ($form_state['values']['options'] as $nid => $level) { if ($_level !== 0 && $level !== 0) { db_query('INSERT INTO {project_subscriptions} (nid, uid, level) VALUES (%d, %d, %d)', $nid, $user->uid, $_level ? $_level : $level); } } drupal_set_message(t('Subscription settings saved.')); if (isset($form['single'])) { $form_state['redirect'] = 'project/issues/subscribe-mail/'. $form['#project']['#value']->project['uri']; } else { $form_state['redirect'] = 'project/issues/subscribe-mail'; } } function project_issue_subscribe($form_state, $project_nid = 0) { global $user; if (!valid_email_address($user->mail)) { drupal_set_message(t('You need to provide a valid e-mail address to subscribe to issue e-mails. Please edit your user information.'), 'error'); drupal_goto('user/'. $user->uid .'/edit'); } $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); if ($project_nid) { if (!is_numeric($project_nid)) { $project_nid = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $project_nid)); } if (!$project_nid) { return drupal_not_found(); } $project = node_load($project_nid); project_project_set_breadcrumb($project, TRUE); $level = db_result(db_query('SELECT level FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $project->nid, $user->uid)); $form['single'] = array( '#type' => 'value', '#value' => $project->nid, ); $form['#project'] = array( '#type' => 'value', '#value' => $project, ); $form['subscribe'] = array( '#type' => 'markup', '#value' => '<p>'. t('Subscribe to receive e-mail notification when an issue for this project is updated.') .'</p>', ); $form['options']['#tree'] = TRUE; $form['options'][$project->nid] = array( '#type' => 'radios', '#title' => t('Subscribe to @project issues', array('@project' => $project->title)), '#default_value' => isset($level) ? $level : 0, '#options' => $levels, ); } else { $form['buttons']['all'] = array( '#type' => 'markup', '#value' => t('All projects'), ); foreach ($levels as $key => $level) { $form['buttons'][$level] = array( '#type' => 'submit', '#name' => 'all', '#value' => $level, ); } $nids = array(); $result = db_query(db_rewrite_sql("SELECT s.nid, n.title, s.level, p.uri FROM {project_subscriptions} s INNER JOIN {node} n ON n.nid = s.nid INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1 AND s.uid = %d ORDER BY n.title", 's'), $user->uid); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); foreach ($levels as $key => $level) { if ($project->level == $key) { $status[$project->nid] = $key; } } $nids[] = $project->nid; } if (empty($nids)) { $placeholders = ''; } else { $placeholders = " AND n.nid NOT IN (". implode(',', array_fill(0, count($nids), '%d')) .")"; } $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, p.uri FROM {node} n INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1". ($nids ? $placeholders : "") ." ORDER BY n.title"), $nids); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); $nids[] = $project->nid; } foreach ($nids as $nid) { $form['options']['#tree'] = TRUE; $form['options'][$nid] = array( '#type' => 'radios', '#default_value' => isset($status[$nid]) ? $status[$nid] : 0, '#options' => $levels, ); } } $form['submit'] = array( '#type' => 'submit', '#value' => t('Subscribe'), ); return $form; } function theme_project_issue_subscribe($form) { global $user; $output = ''; if (!isset($form['single'])) { $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); $headers = array_merge(array(t('Project')), $levels); $row = array(); foreach (element_children($form['buttons']) as $key) { $row[] = drupal_render($form['buttons'][$key]); } $rows = array($row); foreach (element_children($form['project']) as $key) { $row = array(drupal_render($form['project'][$key]['title'])); foreach ($levels as $level => $name) { $row[] = drupal_render($form['options'][$key][$level]); } $rows[] = $row; } $output = theme('table', $headers, $rows); } $output .= drupal_render($form); return $output; } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); } $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Implementation of hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => filter_xss($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => filter_xss($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if ($releases) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'hidden', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Build an array of users to whom an issue may be assigned. * * @param $issue * The fully loaded issue node object. * @return * A keyed array in the form uid => name containing users * to whom an issue may be assigned. */ function project_issue_assigned_choices($issue) { // Setup the array of choices for who the issue is assigned to. $assigned = array(); foreach (module_implements('project_issue_assignees') as $module) { $function = "{$module}_project_issue_assignees"; $function($assigned, $issue); } natcasesort($assigned); $assigned = array(0 => empty($issue->project_issue['assigned']) ? t('Unassigned') : t('Unassign')) + $assigned; return $assigned; } /** * Implmentation of hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } function project_issue_view($node, $teaser = false, $page = false) { $node = node_prepare($node, $teaser); if (!$teaser && ($page || project_issue_is_comment_reply())) { $node->content['#prefix'] = '<div class="project-issue">'; $node->content['#suffix'] = '</div>'; $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); $release->nid = $node->project_issue['rid']; if (module_exists('project_release')) { $release = project_release_load($release); } $assigned = ($node->project_issue['assigned'] && ($account = user_load(array('uid' => $node->project_issue['assigned']))) ? $account->name : t('Unassigned')); $current_data = array(); $current_data['pid'] = array( 'label' => t('Project'), 'current' => $project->title, ); if (!empty($release->project_release['version'])) { $current_data['rid'] = array( 'label' => t('Version'), 'current' => $release->project_release['version'], ); } $current_data['component'] = array( 'label' => t('Component'), 'current' => $node->project_issue['component'], ); $current_data['category'] = array( 'label' => t('Category'), 'current' => project_issue_category($node->project_issue['category'], 0), ); $current_data['priority'] = array( 'label' => t('Priority'), 'current' => project_issue_priority($node->project_issue['priority']), ); $current_data['assigned'] = array( 'label' => t('Assigned'), 'current' => $assigned, ); $current_data['sid'] = array( 'label' => t('Status'), 'current' => project_issue_state($node->project_issue['sid']), ); // Allow modules to alter the metadata displayed in the table on the actual // issue node itself (at the very top of the issue). Modules should accept // the $current_data parameter by reference and add additional // elements for additional lines in the table. // // Modules implementing this hook should take the following parameters: // @param $view // A string representing the metadata view being generated. For the issue // node main table, this will be 'current'. // @param $node // The project_issue node object. // @param $current_data // An associative array of rows in the project issue metadata table that // will be displayed, with the following key/value pairs: // 'label' => The metadata label. // 'current' => The current metadata value. // This parameter should be accepted by reference. foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('current', $node, $current_data); } $node->content['project_issue_summary'] = array( '#value' => theme('project_issue_summary', $current_data, project_issue_internal_links($node)), '#weight' => -5, ); $node->content['project_issue_header'] = array( '#value' => '<div class="header">'. t('Description') .'</div>', '#weight' => -3, ); project_issue_set_breadcrumb($node, $project); } return $node; } /** * Implementation of hook_project_issue_assignees(). * * This hook is used to modify the list of 'Assigned' users when creating or * commenting on an issue. * * @param $assigned * An array of key => value pairs in the format of uid => name that represents * the list of users that the issue may be assigned to. This parameter * is passed by reference so the hook may make changes, such as adding or * removing elements. * @param $node * The node object for the issue. */ function project_issue_project_issue_assignees(&$assigned, $node) { global $user; if ($user->uid) { if (isset($node->project_issue['assigned']) && $user->uid != $node->project_issue['assigned']) { // Assigned to someone else, add the currently assigned user. $account = user_load(array('uid' => $node->project_issue['assigned'])); $assigned[$node->project_issue['assigned']] = $account->name; } // Always let the person replying assign it to themselves. $assigned[$user->uid] = $user->name; } if (user_access('assign and be assigned project issues')) { // All users are included if either anon or auth user has the perm. if (db_result(db_query("SELECT rid FROM {permission} WHERE perm LIKE '%%%s%%' AND rid IN(%d, %d)", 'assign and be assigned project issues', DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $result = db_query("SELECT uid, name FROM {users}"); } else { $result = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {role} r ON ur.rid = r.rid INNER JOIN {permission} p ON p.rid = r.rid WHERE p.perm LIKE '%%%s%%'", 'assign and be assigned project issues'); } while ($assignee = db_fetch_object($result)) { $assigned[$assignee->uid] = $assignee->name; } } } /** * Themes the metadata table and internal page links for issue nodes. * * @param $current_data * An array of current issue data for the metadata table. * @param $summary_links * An array of internal page links. * @return * An HTML string of the summary section. */ function theme_project_issue_summary($current_data, $summary_links) { $allowed_tags = array('a', 'em', 'strong', 'div', 'span'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); $rows = array(); foreach ($current_data as $name => $values) { $row = array(); $row[] = filter_xss($values['label'], $allowed_tags) .':'; if (in_array($name, $plain_fields)) { $row[] = check_plain($values['current']); } else { $row[] = filter_xss($values['current'], $allowed_tags); } $rows[] = $row; } $output = '<div id="project-summary-container" class="clear-block">'; $output .= '<div id="project-issue-summary-table" class="summary">'. theme('table', array(), $rows) .'</div>'; if (!empty($summary_links)) { $output .= '<div id="project-issue-summary-links">'. theme('item_list', $summary_links, t('Jump to:'), 'ul', array('class' => 'internal-links')) .'</div>'; } $output .= '</div>'; return $output; } /** * Generates internal page links for issue pages. * * @param $node * The issue node. * @return * An array of internal page links. */ function project_issue_internal_links($node) { $links = array(); if ($node->comment != COMMENT_NODE_DISABLED) { // Link to the first unread, or most recent comment. if (comment_num_new($node->nid)) { // There are unread replies; link to first unread comment. $links[] = l(t('First unread comment'), "node/$node->nid", array('fragment' => 'new')); } else { // No unread replies; link to most recent comment. $comment_cid = db_result(db_query_range("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {node} n on pic.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY pic.cid DESC", $node->nid, 0, 1)); if ($comment_cid) { $links[] = l(t('Most recent comment'), "node/$node->nid", array('fragment' => "comment-$comment_cid")); } } // Link for most recent patch. $file_cid = db_result(db_query_range("SELECT cu.cid FROM {comment_upload} cu INNER JOIN {node} n on cu.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY cu.fid DESC", $node->nid, 0, 1)); if ($file_cid) { $links[] = l(t('Most recent attachment'), "node/$node->nid", array('fragment' => "comment-$file_cid")); } } // Link straight to comment form. if ($node->comment == COMMENT_NODE_READ_WRITE && (user_access('post comments') || user_access('post comments without approval'))) { // TODO: This conditional needs to be ripped out in D6. $comment_form_location = isset($node->project_issue['comment_form_location']) ? $node->project_issue['comment_form_location'] : variable_get('comment_form_location_' . $node->type, COMMENT_FORM_SEPARATE_PAGE); // Comment form isn't on the page, link to the comment reply page. if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) { $links[] = l(t('Add new comment'), "comment/reply/$node->nid"); } // Comment form is on the page, generate an internal page link for it. else { $links[] = l(t('Add new comment'), "node/$node->nid", array('fragment' => "comment-form")); } } return $links; } /** * Implementation of hook_insert(). * * @param $node * Object containing form values from the project_issue node form. This is * NOT a fully loaded $node object, so the issue-related values are directly * in $node, not in the $node->project_issue array. */ function project_issue_insert($node) { // Permanently store the original issue states in a serialized array. This // is a bit yucky, but we need them for proper handling of states workflow. // The current states need to be stored in {project_issues} as well for // query efficiency in issue queue searches, and it seems too messy to add a // bunch of new columns to the {project_issues} table for the original // states. $original_issue_data = new stdClass(); $fields = array( 'pid' => 0, 'rid' => 0, 'component' => '', 'category' => '', 'priority' => 0, 'assigned' => 0, 'sid' => 0, 'title' => '', ); foreach ($fields as $field => $default) { // Some of the incoming data may not have the correct default. - if (!$node->$field) { + if (empty($node->$field)) { $node->$field = $default; } $original_issue_data->$field = $node->$field; } db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); // Invalidate the "Issue cockpit" block cache for this project, since the // new issue will have altered the summary totals. cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); } function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } // Support stuff /** * Return information about project issue state values. * * @param $sid * Integer state id to return information about, or 0 for all states. * @param $restrict * Boolean to determine if states should be restricted based on the * permissions of the current user or $account if that parameter * is provided. * @param $is_author * Boolean that indicates if the current user is the author of the * issue, which can potentially grant a wider selection of states. * @param $current_sid * The current integer state id for the issue. * @param $defaults * Boolean to request the states used for default issue queries. * @param $account * Account of a user to pass to user_access() for access checking. * This parameter will have no effect unless $restrict is also * set to TRUE. * * @return * An array of states (sid as key, name as value) that match the * given filters, or the name of the requested state. * NOTE: The state name returned is raw text, and should be filtered via * check_plain() or filter_xss() before being printed as HTML output. */ function project_issue_state($sid = 0, $restrict = false, $is_author = false, $current_sid = 0, $defaults = false, $account = NULL) { static $options; if (!$options) { $result = db_query('SELECT * FROM {project_issue_state} ORDER BY weight'); while ($state = db_fetch_object($result)) { $options[] = $state; } } foreach($options as $state) { if ($restrict) { // Check if user has access, // or if status is default status and therefore available to all, // or if user is original issue author and author has access, // or if the issue is already in a state, even if the user doesn't have // access to that state themselves. if (user_access('set issue status '. str_replace("'", "", $state->name), $account) || user_access('administer projects', $account) || ($state->sid == variable_get('project_issue_default_state', 1)) || ($state->author_has && $is_author) || ($state->sid == $current_sid) ) { $states[$state->sid] = $state->name; } } else if ($defaults) { if ($state->default_query) { $states[$state->sid] = $state->name; } } else { $states[$state->sid] = $state->name; } } return $sid ? $states[$sid] : $states; } /** * Return an array of state ids that should be used for default queries. */ function project_issue_default_states() { static $defaults; if (empty($defaults)) { $states = project_issue_state(0, false, false, 0, true); $defaults = !empty($states) ? array_keys($states) : array(1, 2, 4); } return $defaults; } function project_issue_priority($priority = 0) { $priorities = array(1 => t('critical'), t('normal'), t('minor')); return $priority ? $priorities[$priority] : $priorities; } function project_issue_category($category = 0, $plural = 1) { if ($plural) { $categories = array('bug' => t('bug reports'), 'task' => t('tasks'), 'feature' => t('feature requests'), 'support' => t('support requests')); } else { $categories = array('bug' => t('bug report'), 'task' => t('task'), 'feature' => t('feature request'), 'support' => t('support request')); } return $category ? $categories[$category] : $categories; } function project_issue_count($pid) { $state = array(); $result = db_query('SELECT p.sid, count(p.sid) AS count FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid WHERE n.status = 1 AND p.pid = %d GROUP BY p.sid', $pid); while ($data = db_fetch_object($result)) { $state[$data->sid] = $data->count; } return $state; } /** * Return the HTML to use for the links at the top of issue query pages. * * @param $links * Array of links, indexed by the action ('create', 'search', etc). * * @see project_issue_query_result() * @see theme_links() */ function theme_project_issue_query_result_links($links) { return theme('links', $links); } /** * Provide an array of project issue summary fields. * @param $context * The context in which the fields will be displayed. * 'web' for project_issue node and comment summary tables. * 'email' for project_issue notification e-mail messages. */ function project_issue_field_labels($context) { if ($context == 'web') { $labels = array('title' => t('Title')); } else { $labels = array(); } $labels += array( 'pid' => t('Project'), 'rid' => t('Version'), 'component' => t('Component'), 'category' => t('Category'), 'priority' => t('Priority'), 'assigned' => t('Assigned to'), 'sid' => t('Status'), ); if ($context == 'email') { $labels += array( 'name' => t('Reported by'), 'updator' => t('Updated by'), ); } return $labels; } /** * Provide the text displayed to a user for a specific metadata field. * * @param $field * Name of the field. * @param $value * Value of the field. * * @return * Text to display to user. NOTE: This is unfiltered text! If this output is * being sent over the web, you must use check_plain(). */ function project_issue_change_summary($field, $value) { switch ($field) { case 'pid': $project = node_load(array('nid' => $value, 'type' => 'project_project')); return $project->title; case 'category': return $value ? project_issue_category($value, 0) : t('<none>'); case 'priority': return $value ? project_issue_priority($value) : t('<none>'); case 'rid': if ($value) { $release->nid = $value; if (module_exists('project_release')) { $release = project_release_load($release); } else { $release->project_release['version'] = t('Unknown'); } return $release->project_release['version']; } return t('<none>'); case 'assigned': $user = user_load(array('uid' => $value)); return (int) $value === 0 ? variable_get('anonymous', t('Anonymous')) : $user->name; case 'sid': return $value ? project_issue_state($value) : t('<none>'); default: return $value; } } function theme_project_issue_create_forbidden($uri = '') { global $user; if ($user->uid) { return ''; } // We cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages. $destination = "destination=". drupal_urlencode("node/add/project-issue/$uri"); if (variable_get('user_register', 1)) { return t('<a href="@login">Login</a> or <a href="@register">register</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination)))); } else { return t('<a href="@login">Login</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)))); } }
Br3nda/drupal-module-project_issue
504a6cfd75726066d3068e5dd87fdcc7c7ca4193
#376377 by dww: Fixed some critical bugs when enabling OG and project* due to the brain-dead code split in project* (#390856) by moving hook_access() and hook_load() implementations into project.module.
diff --git a/issue.inc b/issue.inc index 47a49e1..cd6ef61 100644 --- a/issue.inc +++ b/issue.inc @@ -1,1287 +1,1250 @@ <?php -// $Id: issue.inc,v 1.348 2009/06/08 23:08:29 thehunmonkgroup Exp $ +// $Id: issue.inc,v 1.349 2009/06/15 03:53:04 dww Exp $ /** * JS callback method to return updated elements on the issue form. * This function is called when someone changes the "Project" selector. */ function project_issue_update_project() { $form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); // Rebuild the form and cache it again. $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); // These used to be path arguments. Now they arrive via form element. $issue_nid = $form['nid']['#value']; $pid = $form_state['values']['project_info']['pid']; $rid = isset($form_state['values']['project_info']['rid']) ? $form_state['values']['project_info']['rid'] : 0; $cid = $form_state['values']['cid']; $assigned_uid = $form_state['values']['project_info']['assigned']; $project_info = $form['original_issue']['project_info']; // Only generate release stuff if the project_release module is enabled. if (module_exists('project_release')) { $project->nid = $pid; if ($releases = project_release_get_releases($project, 0)) { $old_version = db_result(db_query("SELECT version FROM {project_release_nodes} WHERE nid = %d", $rid)); $releases = array(t('<none>')) + $releases; // Since the value of releases is by nid, try to match release // based on the label instead. $default = 0; foreach ($releases as $key => $label) { if ($old_version == $label) { $default = $key; } } // Element is tree'd here to match the original form layout. $project_info['#tree'] = TRUE; $project_info['rid']['#options'] = $releases; $project_info['rid']['#disabled'] = FALSE; if (!empty($default)) { $project_info['rid']['#value'] = $default; $project_info['rid']['#default_value'] = $default; } } else { $project_info['rid']['#disabled'] = TRUE; $project_info['rid']['#options'] = array(); } } // Assigned. if (is_numeric($issue_nid)) { $issue = node_load(array('nid' => $issue_nid, 'type' => 'project_issue')); } else { // @TODO: This case should not ever be hit until // http://drupal.org/node/197281 lands. $issue = new stdClass; } $issue->project_issue['pid'] = $pid; $assigned_choices = project_issue_assigned_choices($issue); $project_info['assigned']['#default_value'] = $assigned_uid; $project_info['assigned']['#options'] = $assigned_choices; // Components. $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $pid)); $components = array(); if ($project->components) { $components = array(t('<none>')); foreach (unserialize($project->components) as $component) { $component = check_plain($component); $components[$component] = $component; } } $project_info['component']['#default_value'] = $cid; $project_info['component']['#options'] = $components; // Build the HTML output for the component select. $output = theme('status_messages') . drupal_render($project_info); drupal_json(array('status' => TRUE, 'data' => $output)); exit; } function project_issue_statistics($project = NULL) { $states = project_issue_state(); if ($project->nid) { $filter = sprintf(' AND p.pid = %d ', (int)$project->nid); project_project_set_breadcrumb($project, TRUE); } $output = '<div class="project-issue">'; // Issue lifetime. $header = array(t('Category'), t('Overall'), t('Last month')); $rows = array(); $duration = time() - 30 * 24 * 60 * 60; $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 GROUP BY p.category'), $filter); while ($stat = db_fetch_object($result)) { $rows[$stat->category][0] = project_issue_category($stat->category); $rows[$stat->category][1] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); $rows[$stat->category][2] = array('data' => t('N/A'), 'class' => 'numeric'); } $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 AND n.created > %d GROUP BY p.category'), $filter, $duration); while ($stat = db_fetch_object($result)) { if ($stat->duration > 0) { $rows[$stat->category][2] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); } } $output .= '<h2>'. t('Average lifetime') .'</h2>'; $output .= theme('table', $header, $rows); $header = array( array('data' => t('Status')), array('data' => t('Overall'), 'class' => 'project-issue-numeric'), array('data' => '%', 'class' => 'project-issue-numeric'), array('data' => t('Last month'), 'class' => 'project-issue-numeric'), ); $rows = array(); // Activity overall. $total = db_result(db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s', 'p'), $filter)); $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s GROUP BY p.sid', 'p'), $filter); while ($stat = db_fetch_object($result)) { $rows[$stat->sid][0] = check_plain(project_issue_state($stat->sid)); $rows[$stat->sid][1] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); $rows[$stat->sid][2] = array('data' => number_format($stat->total / $total * 100) .'%', 'class' => 'project-issue-numeric-light'); $rows[$stat->sid][3] = array('data' => '0', 'class' => 'project-issue-numeric'); } // Activity this month. $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND n.changed > %d GROUP BY p.sid', 'p'), $filter, $duration); while ($stat = db_fetch_object($result)) { $rows[$stat->sid][3] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); } $output .= '<h2>'. t('Issue activity') .'</h2>'; $output .= theme('table', $header, $rows); // Project overview. if (!$project->nid) { // Even though we don't use the tablesorting logic in the query itself, // we include it anyways because we're going to leverage the $_GET arguments // to build our own tablesorting mechanism. $header = array(); $header['project'] = array('data' => t('Project'), 'field' => 'title'); foreach ($states as $key => $value) { $header[$key] = array('data' => check_plain($value), 'field' => $key); } $header['total'] = array('data' => t('Total'), 'field' => 'total'); // Force sorting arrow to appear on active first. $header[1]['sort'] = 'desc'; $args = array(); // Since we're pulling the sid to sort by here individually in the first query // below, we can bastardize the tablesorting logic to get tablesorting. $where = ' AND p.sid = %d'; $column = 'total'; if (isset($_GET['order'])) { switch ($_GET['order']) { case 'Project': $where = ''; $column = 'title'; break; case 'Total': $where = ''; break; default: if ($state = array_search($_GET['order'], $states)) { $args[] = $state; } else { $args[] = 1; } break; } } else { $args[] = 1; } $sort = (isset($_GET['sort']) && $_GET['sort'] == 'desc') || !isset($_GET['sort']) ? 'DESC' : 'ASC'; $rows = array(); $projects = pager_query(db_rewrite_sql("SELECT pn.nid, pn.title, COUNT(n.nid) AS total FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid INNER JOIN {node} pn ON p.pid = pn.nid WHERE n.status = 1 AND pn.status = 1$where GROUP BY pn.nid, pn.title ORDER BY $column $sort"), 15, 0, db_rewrite_sql("SELECT COUNT(DISTINCT(n.nid)) FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.pid INNER JOIN {node} pin ON p.nid = pin.nid WHERE n.status = 1 AND pin.status = 1$where"), $args); $orig = array('project' => array('data' => 0)); foreach ($states as $key => $value) { $orig[$key] = array('data' => '', 'class' => 'project-issue-numeric'); } $orig['total'] = array('data' => '', 'class' => 'project-issue-numeric'); while ($project = db_fetch_object($projects)) { $rows[$project->nid] = $orig; $rows[$project->nid]['project']['data'] = l($project->title, "node/$project->nid"); $stats = db_query("SELECT sid, COUNT(nid) as total FROM {project_issues} WHERE pid = %d GROUP BY sid", $project->nid); while ($stat = db_fetch_object($stats)) { $rows[$project->nid]['total']['data'] += $stat->total; $rows[$project->nid][$stat->sid]['data'] = $stat->total; } } $output .= '<h2>'. t('Project overview') .'</h2>'; $output .= '<div class="project-issue-statistics-overview-table">'; $output .= theme('table', $header, $rows); if ($pager = theme('pager', 15, 0)) { $output .= $pager; } $output .= '</div>'; } $output .= '</div>'; return $output; } function project_issue_subscribe_submit($form, &$form_state) { global $user; $all = $form_state['clicked_button']['#value']; $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); // Remove previous subscriptions for user. if (isset($form_state['values']['single'])) { db_query('DELETE FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $form_state['values']['single'], $user->uid); } else { db_query('DELETE FROM {project_subscriptions} WHERE uid = %d', $user->uid); } $_level = array_search($all, $levels); foreach ($form_state['values']['options'] as $nid => $level) { if ($_level !== 0 && $level !== 0) { db_query('INSERT INTO {project_subscriptions} (nid, uid, level) VALUES (%d, %d, %d)', $nid, $user->uid, $_level ? $_level : $level); } } drupal_set_message(t('Subscription settings saved.')); if (isset($form['single'])) { $form_state['redirect'] = 'project/issues/subscribe-mail/'. $form['#project']['#value']->project['uri']; } else { $form_state['redirect'] = 'project/issues/subscribe-mail'; } } function project_issue_subscribe($form_state, $project_nid = 0) { global $user; if (!valid_email_address($user->mail)) { drupal_set_message(t('You need to provide a valid e-mail address to subscribe to issue e-mails. Please edit your user information.'), 'error'); drupal_goto('user/'. $user->uid .'/edit'); } $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); if ($project_nid) { if (!is_numeric($project_nid)) { $project_nid = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $project_nid)); } if (!$project_nid) { return drupal_not_found(); } $project = node_load($project_nid); project_project_set_breadcrumb($project, TRUE); $level = db_result(db_query('SELECT level FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $project->nid, $user->uid)); $form['single'] = array( '#type' => 'value', '#value' => $project->nid, ); $form['#project'] = array( '#type' => 'value', '#value' => $project, ); $form['subscribe'] = array( '#type' => 'markup', '#value' => '<p>'. t('Subscribe to receive e-mail notification when an issue for this project is updated.') .'</p>', ); $form['options']['#tree'] = TRUE; $form['options'][$project->nid] = array( '#type' => 'radios', '#title' => t('Subscribe to @project issues', array('@project' => $project->title)), '#default_value' => isset($level) ? $level : 0, '#options' => $levels, ); } else { $form['buttons']['all'] = array( '#type' => 'markup', '#value' => t('All projects'), ); foreach ($levels as $key => $level) { $form['buttons'][$level] = array( '#type' => 'submit', '#name' => 'all', '#value' => $level, ); } $nids = array(); $result = db_query(db_rewrite_sql("SELECT s.nid, n.title, s.level, p.uri FROM {project_subscriptions} s INNER JOIN {node} n ON n.nid = s.nid INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1 AND s.uid = %d ORDER BY n.title", 's'), $user->uid); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); foreach ($levels as $key => $level) { if ($project->level == $key) { $status[$project->nid] = $key; } } $nids[] = $project->nid; } if (empty($nids)) { $placeholders = ''; } else { $placeholders = " AND n.nid NOT IN (". implode(',', array_fill(0, count($nids), '%d')) .")"; } $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, p.uri FROM {node} n INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1". ($nids ? $placeholders : "") ." ORDER BY n.title"), $nids); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); $nids[] = $project->nid; } foreach ($nids as $nid) { $form['options']['#tree'] = TRUE; $form['options'][$nid] = array( '#type' => 'radios', '#default_value' => isset($status[$nid]) ? $status[$nid] : 0, '#options' => $levels, ); } } $form['submit'] = array( '#type' => 'submit', '#value' => t('Subscribe'), ); return $form; } function theme_project_issue_subscribe($form) { global $user; $output = ''; if (!isset($form['single'])) { $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); $headers = array_merge(array(t('Project')), $levels); $row = array(); foreach (element_children($form['buttons']) as $key) { $row[] = drupal_render($form['buttons'][$key]); } $rows = array($row); foreach (element_children($form['project']) as $key) { $row = array(drupal_render($form['project'][$key]['title'])); foreach ($levels as $level => $name) { $row[] = drupal_render($form['options'][$key][$level]); } $rows[] = $row; } $output = theme('table', $headers, $rows); } $output .= drupal_render($form); return $output; } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); } $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Implementation of hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => filter_xss($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => filter_xss($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if ($releases) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'hidden', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } else { $form['issue_details']['title'] = array( '#type' => 'value', '#value' => $node->title, ); } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Build an array of users to whom an issue may be assigned. * * @param $issue * The fully loaded issue node object. * @return * A keyed array in the form uid => name containing users * to whom an issue may be assigned. */ function project_issue_assigned_choices($issue) { // Setup the array of choices for who the issue is assigned to. $assigned = array(); foreach (module_implements('project_issue_assignees') as $module) { $function = "{$module}_project_issue_assignees"; $function($assigned, $issue); } natcasesort($assigned); $assigned = array(0 => empty($issue->project_issue['assigned']) ? t('Unassigned') : t('Unassign')) + $assigned; return $assigned; } /** * Implmentation of hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } function project_issue_view($node, $teaser = false, $page = false) { $node = node_prepare($node, $teaser); if (!$teaser && ($page || project_issue_is_comment_reply())) { $node->content['#prefix'] = '<div class="project-issue">'; $node->content['#suffix'] = '</div>'; $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); $release->nid = $node->project_issue['rid']; if (module_exists('project_release')) { $release = project_release_load($release); } $assigned = ($node->project_issue['assigned'] && ($account = user_load(array('uid' => $node->project_issue['assigned']))) ? $account->name : t('Unassigned')); $current_data = array(); $current_data['pid'] = array( 'label' => t('Project'), 'current' => $project->title, ); if (!empty($release->project_release['version'])) { $current_data['rid'] = array( 'label' => t('Version'), 'current' => $release->project_release['version'], ); } $current_data['component'] = array( 'label' => t('Component'), 'current' => $node->project_issue['component'], ); $current_data['category'] = array( 'label' => t('Category'), 'current' => project_issue_category($node->project_issue['category'], 0), ); $current_data['priority'] = array( 'label' => t('Priority'), 'current' => project_issue_priority($node->project_issue['priority']), ); $current_data['assigned'] = array( 'label' => t('Assigned'), 'current' => $assigned, ); $current_data['sid'] = array( 'label' => t('Status'), 'current' => project_issue_state($node->project_issue['sid']), ); // Allow modules to alter the metadata displayed in the table on the actual // issue node itself (at the very top of the issue). Modules should accept // the $current_data parameter by reference and add additional // elements for additional lines in the table. // // Modules implementing this hook should take the following parameters: // @param $view // A string representing the metadata view being generated. For the issue // node main table, this will be 'current'. // @param $node // The project_issue node object. // @param $current_data // An associative array of rows in the project issue metadata table that // will be displayed, with the following key/value pairs: // 'label' => The metadata label. // 'current' => The current metadata value. // This parameter should be accepted by reference. foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('current', $node, $current_data); } $node->content['project_issue_summary'] = array( '#value' => theme('project_issue_summary', $current_data, project_issue_internal_links($node)), '#weight' => -5, ); $node->content['project_issue_header'] = array( '#value' => '<div class="header">'. t('Description') .'</div>', '#weight' => -3, ); project_issue_set_breadcrumb($node, $project); } return $node; } /** * Implementation of hook_project_issue_assignees(). * * This hook is used to modify the list of 'Assigned' users when creating or * commenting on an issue. * * @param $assigned * An array of key => value pairs in the format of uid => name that represents * the list of users that the issue may be assigned to. This parameter * is passed by reference so the hook may make changes, such as adding or * removing elements. * @param $node * The node object for the issue. */ function project_issue_project_issue_assignees(&$assigned, $node) { global $user; if ($user->uid) { if (isset($node->project_issue['assigned']) && $user->uid != $node->project_issue['assigned']) { // Assigned to someone else, add the currently assigned user. $account = user_load(array('uid' => $node->project_issue['assigned'])); $assigned[$node->project_issue['assigned']] = $account->name; } // Always let the person replying assign it to themselves. $assigned[$user->uid] = $user->name; } if (user_access('assign and be assigned project issues')) { // All users are included if either anon or auth user has the perm. if (db_result(db_query("SELECT rid FROM {permission} WHERE perm LIKE '%%%s%%' AND rid IN(%d, %d)", 'assign and be assigned project issues', DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $result = db_query("SELECT uid, name FROM {users}"); } else { $result = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {role} r ON ur.rid = r.rid INNER JOIN {permission} p ON p.rid = r.rid WHERE p.perm LIKE '%%%s%%'", 'assign and be assigned project issues'); } while ($assignee = db_fetch_object($result)) { $assigned[$assignee->uid] = $assignee->name; } } } /** * Themes the metadata table and internal page links for issue nodes. * * @param $current_data * An array of current issue data for the metadata table. * @param $summary_links * An array of internal page links. * @return * An HTML string of the summary section. */ function theme_project_issue_summary($current_data, $summary_links) { $allowed_tags = array('a', 'em', 'strong', 'div', 'span'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); $rows = array(); foreach ($current_data as $name => $values) { $row = array(); $row[] = filter_xss($values['label'], $allowed_tags) .':'; if (in_array($name, $plain_fields)) { $row[] = check_plain($values['current']); } else { $row[] = filter_xss($values['current'], $allowed_tags); } $rows[] = $row; } $output = '<div id="project-summary-container" class="clear-block">'; $output .= '<div id="project-issue-summary-table" class="summary">'. theme('table', array(), $rows) .'</div>'; if (!empty($summary_links)) { $output .= '<div id="project-issue-summary-links">'. theme('item_list', $summary_links, t('Jump to:'), 'ul', array('class' => 'internal-links')) .'</div>'; } $output .= '</div>'; return $output; } /** * Generates internal page links for issue pages. * * @param $node * The issue node. * @return * An array of internal page links. */ function project_issue_internal_links($node) { $links = array(); if ($node->comment != COMMENT_NODE_DISABLED) { // Link to the first unread, or most recent comment. if (comment_num_new($node->nid)) { // There are unread replies; link to first unread comment. $links[] = l(t('First unread comment'), "node/$node->nid", array('fragment' => 'new')); } else { // No unread replies; link to most recent comment. $comment_cid = db_result(db_query_range("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {node} n on pic.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY pic.cid DESC", $node->nid, 0, 1)); if ($comment_cid) { $links[] = l(t('Most recent comment'), "node/$node->nid", array('fragment' => "comment-$comment_cid")); } } // Link for most recent patch. $file_cid = db_result(db_query_range("SELECT cu.cid FROM {comment_upload} cu INNER JOIN {node} n on cu.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY cu.fid DESC", $node->nid, 0, 1)); if ($file_cid) { $links[] = l(t('Most recent attachment'), "node/$node->nid", array('fragment' => "comment-$file_cid")); } } // Link straight to comment form. if ($node->comment == COMMENT_NODE_READ_WRITE && (user_access('post comments') || user_access('post comments without approval'))) { // TODO: This conditional needs to be ripped out in D6. $comment_form_location = isset($node->project_issue['comment_form_location']) ? $node->project_issue['comment_form_location'] : variable_get('comment_form_location_' . $node->type, COMMENT_FORM_SEPARATE_PAGE); // Comment form isn't on the page, link to the comment reply page. if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) { $links[] = l(t('Add new comment'), "comment/reply/$node->nid"); } // Comment form is on the page, generate an internal page link for it. else { $links[] = l(t('Add new comment'), "node/$node->nid", array('fragment' => "comment-form")); } } return $links; } -function project_issue_load($node) { - $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); - - // TODO: This need to be ripped out in D6. - $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); - $issue = new stdClass; - $issue->project_issue = $additions; - return $issue; -} - /** * Implementation of hook_insert(). * * @param $node * Object containing form values from the project_issue node form. This is * NOT a fully loaded $node object, so the issue-related values are directly * in $node, not in the $node->project_issue array. */ function project_issue_insert($node) { // Permanently store the original issue states in a serialized array. This // is a bit yucky, but we need them for proper handling of states workflow. // The current states need to be stored in {project_issues} as well for // query efficiency in issue queue searches, and it seems too messy to add a // bunch of new columns to the {project_issues} table for the original // states. $original_issue_data = new stdClass(); $fields = array( 'pid' => 0, 'rid' => 0, 'component' => '', 'category' => '', 'priority' => 0, 'assigned' => 0, 'sid' => 0, 'title' => '', ); foreach ($fields as $field => $default) { // Some of the incoming data may not have the correct default. if (!$node->$field) { $node->$field = $default; } $original_issue_data->$field = $node->$field; } db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); // Invalidate the "Issue cockpit" block cache for this project, since the // new issue will have altered the summary totals. cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); } function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } -function project_issue_access($op, $node, $account) { - - if (user_access('administer projects', $account)) { - return TRUE; - } - switch ($op) { - case 'view': - if (user_access('access own project issues', $account) && $node->uid == $account->uid) { - return TRUE; - } - if (!user_access('access project issues', $account)) { - return FALSE; - } - break; - case 'create': - return user_access('create project issues', $account); - case 'update': - if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { - return TRUE; - } - break; - case 'delete': - // Admin case already handled, no one else should be able to delete. - break; - } -} - // Support stuff /** * Return information about project issue state values. * * @param $sid * Integer state id to return information about, or 0 for all states. * @param $restrict * Boolean to determine if states should be restricted based on the * permissions of the current user or $account if that parameter * is provided. * @param $is_author * Boolean that indicates if the current user is the author of the * issue, which can potentially grant a wider selection of states. * @param $current_sid * The current integer state id for the issue. * @param $defaults * Boolean to request the states used for default issue queries. * @param $account * Account of a user to pass to user_access() for access checking. * This parameter will have no effect unless $restrict is also * set to TRUE. * * @return * An array of states (sid as key, name as value) that match the * given filters, or the name of the requested state. * NOTE: The state name returned is raw text, and should be filtered via * check_plain() or filter_xss() before being printed as HTML output. */ function project_issue_state($sid = 0, $restrict = false, $is_author = false, $current_sid = 0, $defaults = false, $account = NULL) { static $options; if (!$options) { $result = db_query('SELECT * FROM {project_issue_state} ORDER BY weight'); while ($state = db_fetch_object($result)) { $options[] = $state; } } foreach($options as $state) { if ($restrict) { // Check if user has access, // or if status is default status and therefore available to all, // or if user is original issue author and author has access, // or if the issue is already in a state, even if the user doesn't have // access to that state themselves. if (user_access('set issue status '. str_replace("'", "", $state->name), $account) || user_access('administer projects', $account) || ($state->sid == variable_get('project_issue_default_state', 1)) || ($state->author_has && $is_author) || ($state->sid == $current_sid) ) { $states[$state->sid] = $state->name; } } else if ($defaults) { if ($state->default_query) { $states[$state->sid] = $state->name; } } else { $states[$state->sid] = $state->name; } } return $sid ? $states[$sid] : $states; } /** * Return an array of state ids that should be used for default queries. */ function project_issue_default_states() { static $defaults; if (empty($defaults)) { $states = project_issue_state(0, false, false, 0, true); $defaults = !empty($states) ? array_keys($states) : array(1, 2, 4); } return $defaults; } function project_issue_priority($priority = 0) { $priorities = array(1 => t('critical'), t('normal'), t('minor')); return $priority ? $priorities[$priority] : $priorities; } function project_issue_category($category = 0, $plural = 1) { if ($plural) { $categories = array('bug' => t('bug reports'), 'task' => t('tasks'), 'feature' => t('feature requests'), 'support' => t('support requests')); } else { $categories = array('bug' => t('bug report'), 'task' => t('task'), 'feature' => t('feature request'), 'support' => t('support request')); } return $category ? $categories[$category] : $categories; } function project_issue_count($pid) { $state = array(); $result = db_query('SELECT p.sid, count(p.sid) AS count FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid WHERE n.status = 1 AND p.pid = %d GROUP BY p.sid', $pid); while ($data = db_fetch_object($result)) { $state[$data->sid] = $data->count; } return $state; } /** * Return the HTML to use for the links at the top of issue query pages. * * @param $links * Array of links, indexed by the action ('create', 'search', etc). * * @see project_issue_query_result() * @see theme_links() */ function theme_project_issue_query_result_links($links) { return theme('links', $links); } /** * Provide an array of project issue summary fields. * @param $context * The context in which the fields will be displayed. * 'web' for project_issue node and comment summary tables. * 'email' for project_issue notification e-mail messages. */ function project_issue_field_labels($context) { if ($context == 'web') { $labels = array('title' => t('Title')); } else { $labels = array(); } $labels += array( 'pid' => t('Project'), 'rid' => t('Version'), 'component' => t('Component'), 'category' => t('Category'), 'priority' => t('Priority'), 'assigned' => t('Assigned to'), 'sid' => t('Status'), ); if ($context == 'email') { $labels += array( 'name' => t('Reported by'), 'updator' => t('Updated by'), ); } return $labels; } /** * Provide the text displayed to a user for a specific metadata field. * * @param $field * Name of the field. * @param $value * Value of the field. * * @return * Text to display to user. NOTE: This is unfiltered text! If this output is * being sent over the web, you must use check_plain(). */ function project_issue_change_summary($field, $value) { switch ($field) { case 'pid': $project = node_load(array('nid' => $value, 'type' => 'project_project')); return $project->title; case 'category': return $value ? project_issue_category($value, 0) : t('<none>'); case 'priority': return $value ? project_issue_priority($value) : t('<none>'); case 'rid': if ($value) { $release->nid = $value; if (module_exists('project_release')) { $release = project_release_load($release); } else { $release->project_release['version'] = t('Unknown'); } return $release->project_release['version']; } return t('<none>'); case 'assigned': $user = user_load(array('uid' => $value)); return (int) $value === 0 ? variable_get('anonymous', t('Anonymous')) : $user->name; case 'sid': return $value ? project_issue_state($value) : t('<none>'); default: return $value; } } function theme_project_issue_create_forbidden($uri = '') { global $user; if ($user->uid) { return ''; } // We cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages. $destination = "destination=". drupal_urlencode("node/add/project-issue/$uri"); if (variable_get('user_register', 1)) { return t('<a href="@login">Login</a> or <a href="@register">register</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)), '@register' => url('user/register', array('query' => $destination)))); } else { return t('<a href="@login">Login</a> to create an issue', array('@login' => url('user/login', array('query' => $destination)))); } } diff --git a/project_issue.module b/project_issue.module index 5ab9c78..5c6ebc5 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,1259 +1,1299 @@ <?php -// $Id: project_issue.module,v 1.166 2009/05/09 18:16:30 dww Exp $ +// $Id: project_issue.module,v 1.167 2009/06/15 03:53:05 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. foreach (array('issue', 'comment', 'mail') as $file) { module_load_include('inc', 'project_issue', $file); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue'); } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'issue.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } +function project_issue_access($op, $node, $account) { + + if (user_access('administer projects', $account)) { + return TRUE; + } + switch ($op) { + case 'view': + if (user_access('access own project issues', $account) && $node->uid == $account->uid) { + return TRUE; + } + if (!user_access('access project issues', $account)) { + return FALSE; + } + break; + case 'create': + return user_access('create project issues', $account); + case 'update': + if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { + return TRUE; + } + break; + case 'delete': + // Admin case already handled, no one else should be able to delete. + break; + } +} + /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { $item = trim($item); } /** * Implementation of hook_cron(). * * There is a variable (no admin UI, just via settings.php) that controls if * the admin has setup a separate cron job on their system to invoke this code * instead of relying on cron.php and hook_cron(). If this variable, called * 'project_issue_hook_cron', is set to FALSE, then there's nothing to do * in here. Otherwise, we include the cron.inc file and invoke that code * ourselves. */ function project_issue_cron() { if (variable_get('project_issue_hook_cron', TRUE)) { module_load_include('inc', 'project_issue', 'includes/cron'); _project_issue_cron(); } } /** * Comment left when cron auto-closes an issue. * * @param $auto_close_days * The (minimum) number of days without activity before automatically closing * a fixed issue. * @return * Message to be added as a comment to an issue when auto-closing that issue. */ function theme_project_issue_auto_close_message($auto_close_days) { $auto_close_interval = format_interval($auto_close_days * 24 * 60 * 60, 2); return t('Automatically closed -- issue fixed for !interval with no activity.', array('!interval' => $auto_close_interval)); } /** * Add a followup to a project issue using the auto-followup user. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * See project_issue_add_followup() for a full list of possible keys. * * @return * TRUE if the comment was successfully added, FALSE if either there's no * auto-followup user configured or if the requested issue wasn't found. * * @see project_issue_add_followup(). */ function project_issue_add_auto_followup($changes) { // If a user for automatic followups exists, use that uid and proceed. if ($auto_user = _project_issue_followup_get_user()) { $changes['uid'] = $auto_user->uid; return project_issue_add_followup($changes); } else { return FALSE; } } /** * Saves a comment to the database. * * TODO: Ideally this should die as soon as core's comment_save() becomes more * abstracted. * * @param $changes * An associative array specifying what should change in the issue. Every key * corresponds to a database field and the value is what it should be changed * to. Required keys are: * - nid: Specifies the issue being changed. * - comment: Contains the text of the followup changing the issue. * * 'uid' and 'name' are optional keys -- if not specified then the values * from the currently logged in user will be used, though it's generally * safer to specify the uid explicitly. * * You can specify the following fields of the comment table: subject, * hostname, timestamp, score, status, format, thread, mail, homepage. * You can also specify the following fields from project_issues * table: category, priority, assigned, sid, title. There is a special, * optional key called 'project_info', its value is another associative * array with the following fields from project_issues: pid, rid, component. * Example: To change the issue status and set the comment text for the * issue with nid = 100, this array might look like: * array( * 'nid' => 100, * 'sid' => 4, * 'comment' => t('This issue was automatically closed after 2 weeks of no activity.'), * ); * * @return * TRUE if the comment was successfully added to the requested issue, * otherwise FALSE. */ function project_issue_add_followup($changes) { if (isset($changes['uid'])) { $account = user_load(array('uid' => $changes['uid'])); } else { global $user; $account = $user; } $result = db_query('SELECT pi.nid, pi.rid, pi.component, pi.category, pi.priority, pi.assigned, pi.sid, pi.pid, n.title FROM {project_issues} pi INNER JOIN {node} n ON n.nid = pi.nid WHERE n.nid = %d', $changes['nid']); if ($issue = db_fetch_object($result)) { // Build vancode $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $changes['nid'])); // Strip the "/" from the end of the thread. $max = rtrim($max, '/'); // Finally, build the thread field for this new comment. $thread = int2vancode(vancode2int($max) + 1) .'/'; // These two are not allowed to be set in changes. unset($changes['cid'], $changes['pid']); $comment = $changes + array( 'pid' => 0, 'uid' => $account->uid, // The correct subject (#number) is supplied during the save cycle. 'subject' => '--project followup subject--', 'hostname' => ip_address(), 'timestamp' => time(), 'status' => COMMENT_PUBLISHED, 'format' => FILTER_FORMAT_DEFAULT, 'thread' => $thread, 'name' => $account->name, 'mail' => '', 'homepage' => '', 'category' => $issue->category, 'priority' => $issue->priority, 'assigned' => $issue->assigned, 'sid' => $issue->sid, 'title' => $issue->title, ); if (!isset($comment['project_info'])) { $comment['project_info'] = array(); } $comment['project_info'] += array( 'pid' => $issue->pid, 'rid' => $issue->rid, 'component' => $issue->component, 'assigned' => $issue->assigned, ); db_query("INSERT INTO {comments} (pid, nid, uid, subject, comment, hostname, timestamp, status, format, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s')", $comment['pid'], $comment['nid'], $comment['uid'], $comment['subject'], $comment['comment'], $comment['hostname'], $comment['timestamp'], $comment['status'], $comment['format'], $comment['thread'], $comment['name'], $comment['mail'], $comment['homepage']); $comment['cid'] = db_last_insert_id('comments', 'cid'); _comment_update_node_statistics($comment['nid']); // Tell the other modules a new comment has been submitted. comment_invoke_comment($comment, 'insert'); cache_clear_all(); return TRUE; } return FALSE; } /** * Load and verify the followup user. * * @return $account * The account of the followup user (or FALSE if not found). */ function _project_issue_followup_get_user() { $uid = variable_get('project_issue_followup_user', ''); if ($uid === '') { return FALSE; } $account = user_load(array('uid' => $uid)); // Safety check -- we have to have a valid user here. if (!$account) { watchdog('project_issue', 'Auto-change user failed to load.', WATCHDOG_ERROR); return FALSE; } $anon = variable_get('anonymous', t('Anonymous')); $account->name = $uid ? $account->name : $anon; // Safety check -- selected user must still have the correct permissions to follow up on issues. if (!user_access('access project issues', $account)) { watchdog('project_issue', '%name does not have sufficient permissions to follow up on issues.', array('%name' => $account->name), WATCHDOG_ERROR); return FALSE; } return $account; } /** * hook_nodeapi() implementation. This just decides what type of node * is being passed, and calls the appropriate type-specific hook. * * @see project_issue_issue_nodeapi(). * @see project_issue_project_nodeapi(). */ function project_issue_nodeapi(&$node, $op, $arg) { switch ($node->type) { case 'project_project': project_issue_project_nodeapi($node, $op, $arg); break; case 'project_issue': project_issue_issue_nodeapi($node, $op, $arg); break; } } /** * hook_nodeapi implementation specific to "project_issue" nodes. * @see project_issue_nodeapi(). */ function project_issue_issue_nodeapi(&$node, $op, $arg) { global $user; switch ($op) { case 'view': $_GET['mode'] = COMMENT_MODE_FLAT_EXPANDED; $_GET['sort'] = COMMENT_ORDER_OLDEST_FIRST; project_issue_comment_view($node); break; case 'presave': // Only for new nodes with files set. if (empty($node->nid) && isset($node->files)) { project_issue_rewrite_issue_filepath($node->files); } break; case 'insert': // Mark the node for email notification during hook_exit(), so all issue // and file data is in a consistent state before we generate the email. project_issue_set_mail_notify($node->nid); break; } } +/** + * Implement hook_load() for project issue nodes. + */ +function project_issue_load($node) { + $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); + + // TODO: This need to be ripped out in D6. + $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); + $issue = new stdClass; + $issue->project_issue = $additions; + return $issue; +} + /** * Store issue nodes that need mail notifications sent. * * It's possible that mass inserts/updates could occur, and also possible that * a given node/comment could be programatically updated more than once in a * page load -- an associative array is used in order to support these cases. * * @param $nid * The node ID of the issue node to store, or NULL to fetch the stored nids. * @return * If $nid is not passed, an associative array of nids that are marked for * notification emails, with the following structure: key = nid, value = nid. */ function project_issue_set_mail_notify($nid = NULL) { static $nids = array(); if (!isset($nid)) { $return = $nids; $nids = array(); // Reset just in case this function gets called again. return $return; } else { $nids[$nid] = $nid; } } /** * Implementation of hook_exit(). */ function project_issue_exit() { // Check for issue nodes that need mail notifications sent. This is done in // hook_exit() so that all issue and file data is in a consistent state // before we generate the email. $nids = project_issue_set_mail_notify(); // For cached pages, this hook is called, but there aren't any mail functions // loaded. Since the cached pages won't have any new mail notifications, // we can safely test for this case. if (!empty($nids)) { foreach ($nids as $nid) { project_mail_notify($nid); } } } /** * Rewrites the file information to move files to the issues directory. * * @param $files * An array of file objects, keyed by file ID. */ function project_issue_rewrite_issue_filepath($files) { if ($issue_dir = variable_get('project_directory_issues', 'issues') ) { foreach ($files as $key => $file) { $file = (object) $file; $old_path = $file->filepath; $final_dir = file_directory_path() .'/'. $issue_dir; $move_path = $old_path; file_move($move_path, $final_dir .'/'. basename($file->filepath)); $new_basename = basename($move_path); db_query("UPDATE {files} SET filepath = '%s' WHERE fid = %d", $final_dir .'/'. $new_basename, $file->fid); } } } function project_issue_my_projects_table() { $uid = 0; $display = views_get_page_view(); if (!empty($display->view->argument['uid'])) { $uid = $display->view->argument['uid']->get_value(); } if (empty($uid)) { return; } $header = array( array('data' => t('Project'), 'field' => 'n.title', 'sort' => 'asc'), array( 'data' => t('Last issue update'), 'field' => 'max_issue_changed', 'class' => 'project-issue-updated', ), array( 'data' => t('Open issues'), 'field' => 'count', 'class' => 'project-issues', ), array('data' => t('Issue links'), 'class' => 'project-issue-links'), ); $default_states = implode(',', project_issue_default_states()); $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, COUNT(ni.nid) AS count, MAX(ni.changed) AS max_issue_changed FROM {node} n LEFT JOIN {project_issues} pi ON n.nid = pi.pid AND pi.sid IN ($default_states) LEFT JOIN {node} ni ON ni.nid = pi.nid AND ni.status = 1 WHERE n.type = 'project_project' AND n.status = 1 AND n.uid = %d GROUP BY n.nid, n.title") . tablesort_sql($header), $uid); $any_admin = FALSE; $projects = array(); while ($node = db_fetch_object($result)) { $node_obj = node_load($node->nid); $node->is_admin = node_access('update', $node_obj); $node->project['uri'] = $node_obj->project['uri']; $node->project_issue['issues'] = $node_obj->project_issue['issues']; $node->project_release['releases'] = isset($node_obj->project_release['releases']) ? $node_obj->project_release['releases'] : 0; if ($node->is_admin) { $any_admin = TRUE; } $projects[] = $node; } if (empty($projects)) { return ($uid ? t('You have no projects.') : t('This user has no projects.')); } foreach ($projects as $node) { $issue_links = array( array( 'title' => t('View'), 'href' => 'project/issues/'. $node->project['uri'], ), array( 'title' => t('Search'), 'href' => 'project/issues/search/'. $node->project['uri'], ), array( 'title' => t('Create'), 'href' => 'node/add/project-issue/'. $node->project['uri'], ), ); if ($node->is_admin) { $project_links = array( array( 'title' => t('Edit'), 'href' => "node/$node->nid/edit", ), ); if (module_exists('project_release') && $node->project_release['releases']) { $project_links[] = array( 'title' => t('Add release'), 'href' => "node/add/project-release/$node->nid", ); } } if ($node->project_issue['issues']) { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => $node->max_issue_changed ? format_interval(time() - $node->max_issue_changed, 2) : t('n/a'), 'class' => 'project-issue-updated', ), array( 'data' => $node->count, 'class' => 'project-issues', ), array( 'data' => theme('links', $issue_links), 'class' => 'project-issue-links', ), ); } else { $row = array( array( 'data' => l($node->title, "node/$node->nid"), 'class' => 'project-name', ), array( 'data' => t('Issue tracking is disabled.'), 'colspan' => $node->is_admin ? 2 : 3, ), ); if ($node->is_admin) { $row[] = array( 'data' => l(t('Enable'), "node/$node->nid/edit/issues", array('query' => drupal_get_destination())), 'class' => 'project-issue-links', ); } } if ($node->is_admin) { $row[] = array( 'data' => theme('links', $project_links), 'class' => 'project-project-links', ); } elseif ($any_admin) { $row[] = array(); } $rows[] = $row; $query->projects[] = $node->nid; } if ($any_admin) { $header[] = array('data' => t('Project links'), 'class' => 'project-project-links'); } return theme('table', $header, $rows, array('class' => 'projects')); } /** * Page callback function for the "Issues" subtab at the site-wide search page. */ function project_issue_search_page() { $view_info = variable_get('project_issue_search_issues_view', 'project_issue_search_all:default'); $view_parts = explode(':', $view_info); $view = views_get_view($view_parts[0]); $view->override_path = 'search/issues'; $output .= $view->preview($view_parts[1]); return $output; } /** * hook_nodeapi implementation specific to "project_project" nodes * (from the project.module) * @see project_issue_nodeapi(). */ function project_issue_project_nodeapi(&$node, $op, $arg) { switch ($op) { case 'load': project_issue_project_load($node, $arg); break; case 'insert': project_issue_project_insert($node); break; case 'delete': project_issue_project_delete($node); break; } } function project_issue_project_load(&$node, $arg) { $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $node->nid)); // If nothing loaded, bail immediately if (!$project) { return $node; } $node->project_issue = array(); $node->project_issue['components'] = unserialize($project->components); $node->project_issue['default_component'] = $project->default_component; $node->project_issue['mail_copy_filter'] = unserialize($project->mail_copy_filter); $node->project_issue['mail_copy_filter_state'] = unserialize($project->mail_copy_filter_state); foreach (array('issues', 'help', 'mail_digest', 'mail_copy', 'mail_reminder') as $field) { $node->project_issue[$field] = $project->$field; } return $node; } function project_issue_project_insert($node) { // Setup reasonable defaults: enable issue tracker and standard // components. If maintainers want to change these, (or any of the // other issue-related project settings, like the email notifications) // they'd use the "issues" subtab of the project edit tab (since none // of these fields are present on the initial project add form). $node->project_issue['issues'] = 1; // Default components are saved in the variables table as a plain // string instead of as a serialized array since they come out of // a textarea on a system settings form. Convert here to the more // desirable serialized array for storage per-project. $defaults = array(t('Code'), t('Documentation'), t('Miscellaneous'), t('User interface')); $components = variable_get('project_issue_default_components', implode("\n", $defaults)); $default_components = explode("\n", str_replace("\r", '', $components)); $node->project_issue['components'] = serialize($default_components); db_query("INSERT INTO {project_issue_projects} (nid, issues, components) VALUES (%d, %d, '%s')", $node->nid, $node->project_issue['issues'], $node->project_issue['components']); } function project_issue_project_delete($node) { // Delete all associated issues. $issues = db_query('SELECT nid FROM {project_issues} WHERE pid = %d', $node->nid); while ($issue = db_fetch_object($issues)) { node_delete($issue->nid); } db_query('DELETE FROM {project_issue_projects} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_subscriptions} WHERE nid = %d', $node->nid); } /** * Submit handler to adjust project issue metadata when comments are mass edited. */ function project_issue_comment_mass_update($form_id, $form_values) { // This filters non-numeric values, then empty values. $cids = array_filter(array_filter($form_values['comments'], 'is_numeric')); $issue_comments = db_query("SELECT n.nid, c.cid FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE c.cid IN (". implode(', ', $cids) .") AND n.type = 'project_issue'"); while ($issue_comment = db_fetch_object($issue_comments)) { project_issue_update_by_comment($issue_comment, 'update'); } } /** * Set the breadcrumb trail for project issues and issue followups. * * Since the comment form and a full node view of an issue can appear * on both full issue pages and comment reply pages, this function checks * to see which page is being loaded, and sets the breadcrumb appropriately. * * @param $node * The issue node object. * @param $project * The project node object. */ function project_issue_set_breadcrumb($node, $project) { $extra = array(); $extra[] = l($project->title, 'node/'. $project->nid); $extra[] = l(t('Issues'), 'project/issues/'. $project->project['uri']); // Add the issue title if we're on a comment reply page. if (project_issue_is_comment_reply() || project_issue_is_comment_edit()) { $extra[] = l($node->title, 'node/'. $node->nid); } project_project_set_breadcrumb($project, $extra); } /** * Implementation of hook_link_alter(). */ function project_issue_link_alter(&$links, $node) { // Only remove link for full page views. if ($node->type == 'project_issue' && arg(0) == 'node' && is_numeric(arg(1))) { unset($links['comment_add']); } } /** * @defgroup project_issue_filter Project Issue number to link filter. */ /** * Theme automatic Project Issue links. * @ingroup project_issue_filter themeable * * @param $node * The issue node object to be linked. * @param $comment_id * The comment id to be appended to the link, optional. * @param $comment_number * The comment's number, as visible to users, optional. * @param $include_assigned * Optional boolean to include the user the issue is assigned to. */ function theme_project_issue_issue_link($node, $comment_id = NULL, $comment_number = NULL, $include_assigned = FALSE) { $path = "node/$node->nid"; // See if the issue is assigned to anyone. If so, we'll include it either // in the title attribute on hover, or next to the issue link if there was // an '@' appended to the issue nid. if (!empty($node->project_issue['assigned'])) { $username = db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $node->project_issue['assigned'])); } else { $username = ''; } if (!empty($username) && !$include_assigned) { // We have an assigned user, but we're not going to print it next to the // issue link, so include it in title. l() runs $attributes through // drupal_attributes() which escapes the value. $attributes = array('title' => t('Status: !status, Assigned to: !username', array('!status' => project_issue_state($node->project_issue['sid']), '!username' => $username))); } else { // Just the status. $attributes = array('title' => t('Status: !status', array('!status' => project_issue_state($node->project_issue['sid'])))); } if (isset($comment_id)) { $title = "#$node->nid-$comment_number: $node->title"; $link = l($title, $path, array('attributes' => $attributes, 'fragment' => "comment-$comment_id")); } else { $title = "#$node->nid: $node->title"; $link = l($title, $path, array('attributes' => $attributes)); } $output = '<span class="project-issue-status-'. $node->project_issue['sid'] .' project-issue-status-info">'. $link; if ($include_assigned && !empty($username)) { $output .= ' <span class="project-issue-assigned-user">'. t('Assigned to: @username', array('@username' => $username)) .'</span>'; } $output .= '</span>'; return $output; } /** * Implementation of hook_form_filter_tips(). * @ingroup project_issue_filter */ function project_issue_filter_tips($delta, $format, $long = FALSE) { if ($long) { return t("References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically, with the title of the issue appended. The status of the issue is shown on hover. If '@' is appended (e.g. [#1234@]), the user the issue is assigned to will also be printed."); } else { return t('Project issue numbers (ex. [#12345]) turn into links automatically.'); } } /** * Implementation of hook_filter(). * @ingroup project_issue_filter */ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { switch ($op) { case 'list': return array(0 => t('Project Issue to link filter')); case 'description': return t('Converts references to project issues (in the form of [#12345]) into links. Caching should be disabled if node access control modules are used.'); case 'no cache': return FALSE; case 'prepare': return $text; case 'process': $regex = '(?:(?<!\w)\[#\d+(?:-\d+)?(@)?\](?!\w))|<pre>.*?<\/pre>|<code>.*?<\/code>|<a(?:[^>"\']|"[^"]*"|\'[^\']*\')*>.*?<\/a>'; $text = preg_replace_callback("/$regex/", 'project_issue_link_filter_callback', $text); return $text; } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); if (!empty($grants)) { $conflict_grants = TRUE; } $allowed_roles = user_roles(FALSE, 'access project issues'); if (!isset($allowed_roles[DRUPAL_ANONYMOUS_RID])) { $conflict_anonymous = TRUE; } foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if ($conflict_grants && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'.
Br3nda/drupal-module-project_issue
356df4c94e8a1cf1ff06b29dd9c53de6504be3b8
#445204 by hunmonk: Editing an issue clears out the title. Explicitly declare the title as a form value if metadata editing is disabled.
diff --git a/issue.inc b/issue.inc index 4992212..47a49e1 100644 --- a/issue.inc +++ b/issue.inc @@ -1,1200 +1,1206 @@ <?php -// $Id: issue.inc,v 1.347 2009/05/05 19:15:57 dww Exp $ +// $Id: issue.inc,v 1.348 2009/06/08 23:08:29 thehunmonkgroup Exp $ /** * JS callback method to return updated elements on the issue form. * This function is called when someone changes the "Project" selector. */ function project_issue_update_project() { $form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE); $form_build_id = $_POST['form_build_id']; $form = form_get_cache($form_build_id, $form_state); $args = $form['#parameters']; $form_id = array_shift($args); $form_state['post'] = $form['#post'] = $_POST; $form['#programmed'] = $form['#redirect'] = FALSE; drupal_process_form($form_id, $form, $form_state); // Rebuild the form and cache it again. $form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id); // These used to be path arguments. Now they arrive via form element. $issue_nid = $form['nid']['#value']; $pid = $form_state['values']['project_info']['pid']; $rid = isset($form_state['values']['project_info']['rid']) ? $form_state['values']['project_info']['rid'] : 0; $cid = $form_state['values']['cid']; $assigned_uid = $form_state['values']['project_info']['assigned']; $project_info = $form['original_issue']['project_info']; // Only generate release stuff if the project_release module is enabled. if (module_exists('project_release')) { $project->nid = $pid; if ($releases = project_release_get_releases($project, 0)) { $old_version = db_result(db_query("SELECT version FROM {project_release_nodes} WHERE nid = %d", $rid)); $releases = array(t('<none>')) + $releases; // Since the value of releases is by nid, try to match release // based on the label instead. $default = 0; foreach ($releases as $key => $label) { if ($old_version == $label) { $default = $key; } } // Element is tree'd here to match the original form layout. $project_info['#tree'] = TRUE; $project_info['rid']['#options'] = $releases; $project_info['rid']['#disabled'] = FALSE; if (!empty($default)) { $project_info['rid']['#value'] = $default; $project_info['rid']['#default_value'] = $default; } } else { $project_info['rid']['#disabled'] = TRUE; $project_info['rid']['#options'] = array(); } } // Assigned. if (is_numeric($issue_nid)) { $issue = node_load(array('nid' => $issue_nid, 'type' => 'project_issue')); } else { // @TODO: This case should not ever be hit until // http://drupal.org/node/197281 lands. $issue = new stdClass; } $issue->project_issue['pid'] = $pid; $assigned_choices = project_issue_assigned_choices($issue); $project_info['assigned']['#default_value'] = $assigned_uid; $project_info['assigned']['#options'] = $assigned_choices; // Components. $project = db_fetch_object(db_query('SELECT * FROM {project_issue_projects} WHERE nid = %d', $pid)); $components = array(); if ($project->components) { $components = array(t('<none>')); foreach (unserialize($project->components) as $component) { $component = check_plain($component); $components[$component] = $component; } } $project_info['component']['#default_value'] = $cid; $project_info['component']['#options'] = $components; // Build the HTML output for the component select. $output = theme('status_messages') . drupal_render($project_info); drupal_json(array('status' => TRUE, 'data' => $output)); exit; } function project_issue_statistics($project = NULL) { $states = project_issue_state(); if ($project->nid) { $filter = sprintf(' AND p.pid = %d ', (int)$project->nid); project_project_set_breadcrumb($project, TRUE); } $output = '<div class="project-issue">'; // Issue lifetime. $header = array(t('Category'), t('Overall'), t('Last month')); $rows = array(); $duration = time() - 30 * 24 * 60 * 60; $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 GROUP BY p.category'), $filter); while ($stat = db_fetch_object($result)) { $rows[$stat->category][0] = project_issue_category($stat->category); $rows[$stat->category][1] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); $rows[$stat->category][2] = array('data' => t('N/A'), 'class' => 'numeric'); } $result = db_query(db_rewrite_sql('SELECT p.category, SUM(n.changed - n.created) / COUNT(p.category) AS duration FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND p.sid > 1 AND n.created > %d GROUP BY p.category'), $filter, $duration); while ($stat = db_fetch_object($result)) { if ($stat->duration > 0) { $rows[$stat->category][2] = array('data' => format_interval($stat->duration, 2), 'class' => 'numeric'); } } $output .= '<h2>'. t('Average lifetime') .'</h2>'; $output .= theme('table', $header, $rows); $header = array( array('data' => t('Status')), array('data' => t('Overall'), 'class' => 'project-issue-numeric'), array('data' => '%', 'class' => 'project-issue-numeric'), array('data' => t('Last month'), 'class' => 'project-issue-numeric'), ); $rows = array(); // Activity overall. $total = db_result(db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s', 'p'), $filter)); $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s GROUP BY p.sid', 'p'), $filter); while ($stat = db_fetch_object($result)) { $rows[$stat->sid][0] = check_plain(project_issue_state($stat->sid)); $rows[$stat->sid][1] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); $rows[$stat->sid][2] = array('data' => number_format($stat->total / $total * 100) .'%', 'class' => 'project-issue-numeric-light'); $rows[$stat->sid][3] = array('data' => '0', 'class' => 'project-issue-numeric'); } // Activity this month. $result = db_query(db_rewrite_sql('SELECT COUNT(p.nid) AS total, p.sid FROM {project_issues} p INNER JOIN {node} n ON n.nid = p.nid WHERE n.status = 1%s AND n.changed > %d GROUP BY p.sid', 'p'), $filter, $duration); while ($stat = db_fetch_object($result)) { $rows[$stat->sid][3] = array('data' => $stat->total, 'class' => 'project-issue-numeric'); } $output .= '<h2>'. t('Issue activity') .'</h2>'; $output .= theme('table', $header, $rows); // Project overview. if (!$project->nid) { // Even though we don't use the tablesorting logic in the query itself, // we include it anyways because we're going to leverage the $_GET arguments // to build our own tablesorting mechanism. $header = array(); $header['project'] = array('data' => t('Project'), 'field' => 'title'); foreach ($states as $key => $value) { $header[$key] = array('data' => check_plain($value), 'field' => $key); } $header['total'] = array('data' => t('Total'), 'field' => 'total'); // Force sorting arrow to appear on active first. $header[1]['sort'] = 'desc'; $args = array(); // Since we're pulling the sid to sort by here individually in the first query // below, we can bastardize the tablesorting logic to get tablesorting. $where = ' AND p.sid = %d'; $column = 'total'; if (isset($_GET['order'])) { switch ($_GET['order']) { case 'Project': $where = ''; $column = 'title'; break; case 'Total': $where = ''; break; default: if ($state = array_search($_GET['order'], $states)) { $args[] = $state; } else { $args[] = 1; } break; } } else { $args[] = 1; } $sort = (isset($_GET['sort']) && $_GET['sort'] == 'desc') || !isset($_GET['sort']) ? 'DESC' : 'ASC'; $rows = array(); $projects = pager_query(db_rewrite_sql("SELECT pn.nid, pn.title, COUNT(n.nid) AS total FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid INNER JOIN {node} pn ON p.pid = pn.nid WHERE n.status = 1 AND pn.status = 1$where GROUP BY pn.nid, pn.title ORDER BY $column $sort"), 15, 0, db_rewrite_sql("SELECT COUNT(DISTINCT(n.nid)) FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.pid INNER JOIN {node} pin ON p.nid = pin.nid WHERE n.status = 1 AND pin.status = 1$where"), $args); $orig = array('project' => array('data' => 0)); foreach ($states as $key => $value) { $orig[$key] = array('data' => '', 'class' => 'project-issue-numeric'); } $orig['total'] = array('data' => '', 'class' => 'project-issue-numeric'); while ($project = db_fetch_object($projects)) { $rows[$project->nid] = $orig; $rows[$project->nid]['project']['data'] = l($project->title, "node/$project->nid"); $stats = db_query("SELECT sid, COUNT(nid) as total FROM {project_issues} WHERE pid = %d GROUP BY sid", $project->nid); while ($stat = db_fetch_object($stats)) { $rows[$project->nid]['total']['data'] += $stat->total; $rows[$project->nid][$stat->sid]['data'] = $stat->total; } } $output .= '<h2>'. t('Project overview') .'</h2>'; $output .= '<div class="project-issue-statistics-overview-table">'; $output .= theme('table', $header, $rows); if ($pager = theme('pager', 15, 0)) { $output .= $pager; } $output .= '</div>'; } $output .= '</div>'; return $output; } function project_issue_subscribe_submit($form, &$form_state) { global $user; $all = $form_state['clicked_button']['#value']; $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); // Remove previous subscriptions for user. if (isset($form_state['values']['single'])) { db_query('DELETE FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $form_state['values']['single'], $user->uid); } else { db_query('DELETE FROM {project_subscriptions} WHERE uid = %d', $user->uid); } $_level = array_search($all, $levels); foreach ($form_state['values']['options'] as $nid => $level) { if ($_level !== 0 && $level !== 0) { db_query('INSERT INTO {project_subscriptions} (nid, uid, level) VALUES (%d, %d, %d)', $nid, $user->uid, $_level ? $_level : $level); } } drupal_set_message(t('Subscription settings saved.')); if (isset($form['single'])) { $form_state['redirect'] = 'project/issues/subscribe-mail/'. $form['#project']['#value']->project['uri']; } else { $form_state['redirect'] = 'project/issues/subscribe-mail'; } } function project_issue_subscribe($form_state, $project_nid = 0) { global $user; if (!valid_email_address($user->mail)) { drupal_set_message(t('You need to provide a valid e-mail address to subscribe to issue e-mails. Please edit your user information.'), 'error'); drupal_goto('user/'. $user->uid .'/edit'); } $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); if ($project_nid) { if (!is_numeric($project_nid)) { $project_nid = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $project_nid)); } if (!$project_nid) { return drupal_not_found(); } $project = node_load($project_nid); project_project_set_breadcrumb($project, TRUE); $level = db_result(db_query('SELECT level FROM {project_subscriptions} WHERE nid = %d AND uid = %d', $project->nid, $user->uid)); $form['single'] = array( '#type' => 'value', '#value' => $project->nid, ); $form['#project'] = array( '#type' => 'value', '#value' => $project, ); $form['subscribe'] = array( '#type' => 'markup', '#value' => '<p>'. t('Subscribe to receive e-mail notification when an issue for this project is updated.') .'</p>', ); $form['options']['#tree'] = TRUE; $form['options'][$project->nid] = array( '#type' => 'radios', '#title' => t('Subscribe to @project issues', array('@project' => $project->title)), '#default_value' => isset($level) ? $level : 0, '#options' => $levels, ); } else { $form['buttons']['all'] = array( '#type' => 'markup', '#value' => t('All projects'), ); foreach ($levels as $key => $level) { $form['buttons'][$level] = array( '#type' => 'submit', '#name' => 'all', '#value' => $level, ); } $nids = array(); $result = db_query(db_rewrite_sql("SELECT s.nid, n.title, s.level, p.uri FROM {project_subscriptions} s INNER JOIN {node} n ON n.nid = s.nid INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1 AND s.uid = %d ORDER BY n.title", 's'), $user->uid); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); foreach ($levels as $key => $level) { if ($project->level == $key) { $status[$project->nid] = $key; } } $nids[] = $project->nid; } if (empty($nids)) { $placeholders = ''; } else { $placeholders = " AND n.nid NOT IN (". implode(',', array_fill(0, count($nids), '%d')) .")"; } $result = db_query(db_rewrite_sql("SELECT n.nid, n.title, p.uri FROM {node} n INNER JOIN {project_projects} p ON n.nid = p.nid WHERE n.type = 'project_project' AND n.status = 1". ($nids ? $placeholders : "") ." ORDER BY n.title"), $nids); while ($project = db_fetch_object($result)) { $form['project'][$project->nid]['title'] = array( '#value' => l($project->title, "node/$project->nid"), ); $nids[] = $project->nid; } foreach ($nids as $nid) { $form['options']['#tree'] = TRUE; $form['options'][$nid] = array( '#type' => 'radios', '#default_value' => isset($status[$nid]) ? $status[$nid] : 0, '#options' => $levels, ); } } $form['submit'] = array( '#type' => 'submit', '#value' => t('Subscribe'), ); return $form; } function theme_project_issue_subscribe($form) { global $user; $output = ''; if (!isset($form['single'])) { $levels = array(0 => t('None'), 1 => t('Own issues'), 2 => t('All issues')); $headers = array_merge(array(t('Project')), $levels); $row = array(); foreach (element_children($form['buttons']) as $key) { $row[] = drupal_render($form['buttons'][$key]); } $rows = array($row); foreach (element_children($form['project']) as $key) { $row = array(drupal_render($form['project'][$key]['title'])); foreach ($levels as $level => $name) { $row[] = drupal_render($form['options'][$key][$level]); } $rows[] = $row; } $output = theme('table', $headers, $rows); } $output .= drupal_render($form); return $output; } function project_issue_pick_project_page() { drupal_set_title(t('Submit @name', array('@name' => node_get_types('name', 'project_issue')))); return drupal_get_form('project_issue_pick_project_form'); } /** * Form builder for a simple form to select a project when creating a new * issue (as the first "page", but this is not really a multi-page form). */ function project_issue_pick_project_form(&$form_state) { $form = array(); // Fetch a list of all projects. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); } $form['pid'] = array( '#type' => 'select', '#title' => t('Project'), '#options' => $projects, '#required' => TRUE, ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Next'), ); return $form; } function project_issue_pick_project_form_validate($form, &$form_state) { if (empty($form_state['values']['pid'])) { form_set_error('pid', t('You must select a project.')); } $node = node_load($form_state['values']['pid']); if (empty($node) || $node->type != 'project_project') { form_set_error('pid', t('Invalid project selected.')); } } function project_issue_pick_project_form_submit($form, &$form_state) { $project = node_load($form_state['values']['pid']); $form_state['redirect'] = 'node/add/project-issue/'. $project->project['uri']; } /** * Implementation of hook_form(). * * Create the project issue node form. * * @param $node * The project issue node object. * @param $include_metadata_fields * If set, metadata fields (eg. status, assigned, title) will * be included in the form regardless of whether $node->nid is set. * Otherwise, metadata fields will only be included in the form * if $node->nid is empty. */ function project_issue_form($node, $form_state, $include_metadata_fields = FALSE) { global $user; $defaults = array( 'rid', 'component', 'category', 'priority', 'assigned', 'sid', ); // Set some defaults for new forms. if (!isset($node->nid)) { foreach ($defaults as $default) { $node->project_issue[$default] = 0; } } // In the case of an issue preview, get our defaults from the submitted form. // TODO: do we want to #tree our form so we don't need this hack? if (isset($form_state['node'])) { foreach ($defaults as $default) { if (isset($form_state['node'][$default])) { $node->project_issue[$default] = $form_state['node'][$default]; } } } // If this function is being called as a result of CCK building the form // in content_admin_field_overview_form(), just return an empty array, since // CCK only grabs the top level fields and this form has none of those anyway. if (!empty($node->cck_dummy_node_form)) { return array(); } if (arg(0) == 'node' && arg(1) == 'add') { $breadcrumb = array(); $breadcrumb[] = l(t('Home'), NULL); $breadcrumb[] = l(t('Create content'), 'node/add'); drupal_set_breadcrumb($breadcrumb); } $default_state = variable_get('project_issue_default_state', 1); // Fetch a list of all projects to test for access. $uris = NULL; $projects = array(t('<none>')) + project_projects_select_options($uris); if (count($projects) == 1) { drupal_set_message(t('You do not have access to any projects.'), 'error'); drupal_goto('node/add/project-issue'); return; } // Figure out what project we should use for the issue metadata. if (!empty($form_state['values']['project_info']['pid'])) { // The project has been selected in the form itself (e.g. it's been // changed and we're previewing, etc.) $pid = $form_state['values']['project_info']['pid']; } elseif (!empty($node->project_issue['pid'])) { // The issue node already knows what project it belongs to. $pid = $node->project_issue['pid']; } else { // Fallback and try to learn the project from the URL -- evil. $pid = arg(3); if (!empty($pid)) { if (is_numeric($pid)) { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql('SELECT p.nid FROM {project_projects} p WHERE p.nid = %d', 'p'), $pid)); } else { $node->project_issue['pid'] = db_result(db_query(db_rewrite_sql("SELECT p.nid FROM {project_projects} p WHERE p.uri = '%s'", 'p'), $pid)); } } $pid = $node->project_issue['pid']; } if (empty($pid)) { drupal_set_message(t('Invalid project selected.'), 'error'); drupal_goto('node/add/project-issue'); } // If this issue has already been created and is just being // edited, we want to prevent any metadata changes. However, allow // the $include_metadata_fields parameter to override this check. if ($include_metadata_fields) { $allow_metadata_changes = TRUE; } else { $allow_metadata_changes = empty($node->nid); } // Load the project and initialize some support arrays. $project = node_load($pid); if ($project->type != 'project_project') { drupal_set_message(t('Invalid project selected.'), 'error'); // Not sure the best place to go here... drupal_goto('node/add/project-issue'); } if ($allow_metadata_changes) { if (module_exists('project_release') && isset($node->project_issue['rid']) && $releases = project_release_get_releases($project, 0, 'version', 'all', array($node->project_issue['rid']))) { $releases = array(t('<none>')) + $releases; } // Remove releases marked as invalid release nodes for user selection. foreach (variable_get('project_issue_invalid_releases', array()) as $rid) { unset($releases[$rid]); } // Setup components and default component. if (!empty($node->project_issue['component'])) { $default_component = $node->project_issue['component']; } else { $default_component = $project->project_issue['default_component']; } $components = empty($default_component) ? array(t('<none>')) : array(); if ($project->project_issue['components']) { foreach ($project->project_issue['components'] as $component) { $component = check_plain($component); $components[$component] = $component; } } $categories = array_merge(array(t('<none>')), project_issue_category(0, 0)); $priorities = project_issue_priority(); $states = project_issue_state(0, TRUE, !empty($node->nid) && ($node->uid == $user->uid), $node->project_issue['sid']); $assigned = project_issue_assigned_choices($node); } // Display the site-wide and/or per-project help text. $site_help = trim(variable_get('project_issue_site_help', '')); if (!empty($site_help)) { $form['project_help']['site'] = array( '#prefix' => '<div class="messages status site">', '#value' => filter_xss($site_help), '#suffix' => '</div>', ); } $project_help = trim($project->project_issue['help']); if (!empty($project_help)) { $form['project_help']['project'] = array( '#prefix' => '<div class="messages status project">', '#value' => filter_xss($project_help), '#suffix' => '</div>', ); } if ($allow_metadata_changes) { $form['project_info'] = array( '#type' => 'fieldset', '#title' => t('Project information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['project_info']['project_display'] = array( '#type' => 'item', '#title' => t('Project'), '#value' => check_plain($project->title), ); $form['project_info']['pid'] = array( '#type' => 'value', '#value' => $node->project_issue['pid'], ); if ($releases) { $form['project_info']['rid'] = array( '#type' => 'select', '#title' => t('Version'), '#default_value' => $node->project_issue['rid'], '#options' => $releases, '#required' => TRUE, ); } $form['project_info']['component'] = array( '#type' => 'select', '#title' => t('Component'), '#default_value' => $default_component, '#options' => $components, '#required' => TRUE, ); $form['issue_info'] = array( '#type' => 'fieldset', '#title' => t('Issue information'), '#prefix' => '<div class="inline-options">', '#suffix' => '</div>', ); $form['issue_info']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#default_value' => $node->project_issue['category'] ? $node->project_issue['category'] : arg(4), '#options' => $categories, '#required' => TRUE, ); $form['issue_info']['priority'] = array( '#type' => 'select', '#title' => t('Priority'), '#default_value' => $node->project_issue['priority'] ? $node->project_issue['priority'] : 2, '#options' => $priorities, ); $form['issue_info']['assigned'] = array( '#type' => 'select', '#title' => t('Assigned'), '#default_value' => $node->project_issue['assigned'], '#options' => $assigned, ); if (count($states) > 1) { $form['issue_info']['sid'] = array( '#type' => 'select', '#title' => t('Status'), '#default_value' => $node->project_issue['sid'] ? $node->project_issue['sid'] : $default_state, '#options' => $states, ); } else { $form['issue_info']['sid'] = array( '#type' => 'hidden', '#value' => $default_state, ); $form['issue_info']['status'] = array( '#type' => 'item', '#title' => t('Status'), '#value' => check_plain(project_issue_state($default_state)), ); } } $form['issue_details'] = array( '#type' => 'fieldset', '#title' => t('Issue details'), '#prefix' => '</div><div class="standard">', ); if ($allow_metadata_changes) { $form['issue_details']['title'] = array( '#type' => 'textfield', '#title' => t('Title'), '#default_value' => $node->title, '#size' => 60, '#maxlength' => 128, '#required' => TRUE, ); } + else { + $form['issue_details']['title'] = array( + '#type' => 'value', + '#value' => $node->title, + ); + } $form['issue_details']['body'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => $node->body, '#rows' => 10, '#required' => TRUE, ); $form['issue_details']['format'] = filter_form($node->format); $directory = file_create_path(variable_get('project_directory_issues', 'issues')); if (!file_check_directory($directory, 0)) { $msg = t('File attachments are disabled. The issue directory has not been properly configured.'); if (user_access('administer site configuration')) { $msg .= ' '. t('Please visit the !admin-project-issue-settings page.', array('!admin-project-issue-settings' => l(t('Project issue settings'), 'admin/project/project-issue-settings'))); } else { $msg .= ' '. t('Please contact the site administrator.'); } drupal_set_message($msg, 'error'); } return $form; } /** * Build an array of users to whom an issue may be assigned. * * @param $issue * The fully loaded issue node object. * @return * A keyed array in the form uid => name containing users * to whom an issue may be assigned. */ function project_issue_assigned_choices($issue) { // Setup the array of choices for who the issue is assigned to. $assigned = array(); foreach (module_implements('project_issue_assignees') as $module) { $function = "{$module}_project_issue_assignees"; $function($assigned, $issue); } natcasesort($assigned); $assigned = array(0 => empty($issue->project_issue['assigned']) ? t('Unassigned') : t('Unassign')) + $assigned; return $assigned; } /** * Implmentation of hook_validate(). * * Ensures that the issue node form has valid values for all required fields. * We use hook_validate() here instead of a #validate handler or even defining * project_issue_node_form_validate() since if we did, node_form_validate() * itself would not be invoked, which would lead to all kinds of problems, * including hook_nodeapi('validate') never being invoked. * * @param $node * An object of form values from the project_issue node form, not a fully * loaded issue node object. Therefore, the fields are not in the usual * $node->project_issue array. */ function project_issue_validate($node) { // If $node->nid is set, that means that the node was being // edited and not created. If that's the case, the user was // not presented with any of the metadata fields, so there's no // need to validate them here. if (empty($node->nid)) { if (empty($node->pid)) { form_set_error('pid', t('You have to specify a valid project.')); } elseif ($project = node_load($node->pid)) { if (module_exists('project_release') && $releases = project_release_get_releases($project, 0)) { if (empty($node->rid)) { form_set_error('rid', t('You have to specify a valid version.')); } } if (isset($node->component) && !in_array($node->component, $project->project_issue['components'])) { $node->component = 0; } if (empty($node->component)) { form_set_error('component', t('You have to specify a valid component.')); } if (empty($node->category)) { form_set_error('category', t('You have to specify a valid category.')); } } } } function project_issue_view($node, $teaser = false, $page = false) { $node = node_prepare($node, $teaser); if (!$teaser && ($page || project_issue_is_comment_reply())) { $node->content['#prefix'] = '<div class="project-issue">'; $node->content['#suffix'] = '</div>'; $project = node_load(array('nid' => $node->project_issue['pid'], 'type' => 'project_project')); $release->nid = $node->project_issue['rid']; if (module_exists('project_release')) { $release = project_release_load($release); } $assigned = ($node->project_issue['assigned'] && ($account = user_load(array('uid' => $node->project_issue['assigned']))) ? $account->name : t('Unassigned')); $current_data = array(); $current_data['pid'] = array( 'label' => t('Project'), 'current' => $project->title, ); if (!empty($release->project_release['version'])) { $current_data['rid'] = array( 'label' => t('Version'), 'current' => $release->project_release['version'], ); } $current_data['component'] = array( 'label' => t('Component'), 'current' => $node->project_issue['component'], ); $current_data['category'] = array( 'label' => t('Category'), 'current' => project_issue_category($node->project_issue['category'], 0), ); $current_data['priority'] = array( 'label' => t('Priority'), 'current' => project_issue_priority($node->project_issue['priority']), ); $current_data['assigned'] = array( 'label' => t('Assigned'), 'current' => $assigned, ); $current_data['sid'] = array( 'label' => t('Status'), 'current' => project_issue_state($node->project_issue['sid']), ); // Allow modules to alter the metadata displayed in the table on the actual // issue node itself (at the very top of the issue). Modules should accept // the $current_data parameter by reference and add additional // elements for additional lines in the table. // // Modules implementing this hook should take the following parameters: // @param $view // A string representing the metadata view being generated. For the issue // node main table, this will be 'current'. // @param $node // The project_issue node object. // @param $current_data // An associative array of rows in the project issue metadata table that // will be displayed, with the following key/value pairs: // 'label' => The metadata label. // 'current' => The current metadata value. // This parameter should be accepted by reference. foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('current', $node, $current_data); } $node->content['project_issue_summary'] = array( '#value' => theme('project_issue_summary', $current_data, project_issue_internal_links($node)), '#weight' => -5, ); $node->content['project_issue_header'] = array( '#value' => '<div class="header">'. t('Description') .'</div>', '#weight' => -3, ); project_issue_set_breadcrumb($node, $project); } return $node; } /** * Implementation of hook_project_issue_assignees(). * * This hook is used to modify the list of 'Assigned' users when creating or * commenting on an issue. * * @param $assigned * An array of key => value pairs in the format of uid => name that represents * the list of users that the issue may be assigned to. This parameter * is passed by reference so the hook may make changes, such as adding or * removing elements. * @param $node * The node object for the issue. */ function project_issue_project_issue_assignees(&$assigned, $node) { global $user; if ($user->uid) { if (isset($node->project_issue['assigned']) && $user->uid != $node->project_issue['assigned']) { // Assigned to someone else, add the currently assigned user. $account = user_load(array('uid' => $node->project_issue['assigned'])); $assigned[$node->project_issue['assigned']] = $account->name; } // Always let the person replying assign it to themselves. $assigned[$user->uid] = $user->name; } if (user_access('assign and be assigned project issues')) { // All users are included if either anon or auth user has the perm. if (db_result(db_query("SELECT rid FROM {permission} WHERE perm LIKE '%%%s%%' AND rid IN(%d, %d)", 'assign and be assigned project issues', DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) { $result = db_query("SELECT uid, name FROM {users}"); } else { $result = db_query("SELECT u.uid, u.name FROM {users} u INNER JOIN {users_roles} ur ON u.uid = ur.uid INNER JOIN {role} r ON ur.rid = r.rid INNER JOIN {permission} p ON p.rid = r.rid WHERE p.perm LIKE '%%%s%%'", 'assign and be assigned project issues'); } while ($assignee = db_fetch_object($result)) { $assigned[$assignee->uid] = $assignee->name; } } } /** * Themes the metadata table and internal page links for issue nodes. * * @param $current_data * An array of current issue data for the metadata table. * @param $summary_links * An array of internal page links. * @return * An HTML string of the summary section. */ function theme_project_issue_summary($current_data, $summary_links) { $allowed_tags = array('a', 'em', 'strong', 'div', 'span'); // Fields that should be rendered as plain text, not filtered HTML. $plain_fields = array('title', 'pid', 'rid'); $rows = array(); foreach ($current_data as $name => $values) { $row = array(); $row[] = filter_xss($values['label'], $allowed_tags) .':'; if (in_array($name, $plain_fields)) { $row[] = check_plain($values['current']); } else { $row[] = filter_xss($values['current'], $allowed_tags); } $rows[] = $row; } $output = '<div id="project-summary-container" class="clear-block">'; $output .= '<div id="project-issue-summary-table" class="summary">'. theme('table', array(), $rows) .'</div>'; if (!empty($summary_links)) { $output .= '<div id="project-issue-summary-links">'. theme('item_list', $summary_links, t('Jump to:'), 'ul', array('class' => 'internal-links')) .'</div>'; } $output .= '</div>'; return $output; } /** * Generates internal page links for issue pages. * * @param $node * The issue node. * @return * An array of internal page links. */ function project_issue_internal_links($node) { $links = array(); if ($node->comment != COMMENT_NODE_DISABLED) { // Link to the first unread, or most recent comment. if (comment_num_new($node->nid)) { // There are unread replies; link to first unread comment. $links[] = l(t('First unread comment'), "node/$node->nid", array('fragment' => 'new')); } else { // No unread replies; link to most recent comment. $comment_cid = db_result(db_query_range("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {node} n on pic.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY pic.cid DESC", $node->nid, 0, 1)); if ($comment_cid) { $links[] = l(t('Most recent comment'), "node/$node->nid", array('fragment' => "comment-$comment_cid")); } } // Link for most recent patch. $file_cid = db_result(db_query_range("SELECT cu.cid FROM {comment_upload} cu INNER JOIN {node} n on cu.nid = n.nid WHERE n.status = 1 AND n.nid = %d ORDER BY cu.fid DESC", $node->nid, 0, 1)); if ($file_cid) { $links[] = l(t('Most recent attachment'), "node/$node->nid", array('fragment' => "comment-$file_cid")); } } // Link straight to comment form. if ($node->comment == COMMENT_NODE_READ_WRITE && (user_access('post comments') || user_access('post comments without approval'))) { // TODO: This conditional needs to be ripped out in D6. $comment_form_location = isset($node->project_issue['comment_form_location']) ? $node->project_issue['comment_form_location'] : variable_get('comment_form_location_' . $node->type, COMMENT_FORM_SEPARATE_PAGE); // Comment form isn't on the page, link to the comment reply page. if ($comment_form_location == COMMENT_FORM_SEPARATE_PAGE) { $links[] = l(t('Add new comment'), "comment/reply/$node->nid"); } // Comment form is on the page, generate an internal page link for it. else { $links[] = l(t('Add new comment'), "node/$node->nid", array('fragment' => "comment-form")); } } return $links; } function project_issue_load($node) { $additions = db_fetch_array(db_query(db_rewrite_sql('SELECT pi.* FROM {project_issues} pi WHERE pi.nid = %d', 'pi'), $node->nid)); // TODO: This need to be ripped out in D6. $additions['comment_form_location'] = variable_get('project_issue_comment_form_location', NULL); $issue = new stdClass; $issue->project_issue = $additions; return $issue; } /** * Implementation of hook_insert(). * * @param $node * Object containing form values from the project_issue node form. This is * NOT a fully loaded $node object, so the issue-related values are directly * in $node, not in the $node->project_issue array. */ function project_issue_insert($node) { // Permanently store the original issue states in a serialized array. This // is a bit yucky, but we need them for proper handling of states workflow. // The current states need to be stored in {project_issues} as well for // query efficiency in issue queue searches, and it seems too messy to add a // bunch of new columns to the {project_issues} table for the original // states. $original_issue_data = new stdClass(); $fields = array( 'pid' => 0, 'rid' => 0, 'component' => '', 'category' => '', 'priority' => 0, 'assigned' => 0, 'sid' => 0, 'title' => '', ); foreach ($fields as $field => $default) { // Some of the incoming data may not have the correct default. if (!$node->$field) { $node->$field = $default; } $original_issue_data->$field = $node->$field; } db_query("INSERT INTO {project_issues} (nid, pid, category, component, priority, rid, assigned, sid, original_issue_data, last_comment_id, db_lock) VALUES (%d, %d, '%s', '%s', %d, %d, %d, %d, '%s', %d, %d)", $node->nid, $node->pid, $node->category, $node->component, $node->priority, $node->rid, $node->assigned, $node->sid, serialize($original_issue_data), 0, 0); // Invalidate the "Issue cockpit" block cache for this project, since the // new issue will have altered the summary totals. cache_clear_all('project_issue_cockpit_block:'. $node->pid, 'cache'); } function project_issue_delete($node) { db_query('DELETE FROM {project_issues} WHERE nid = %d', $node->nid); db_query('DELETE FROM {project_issue_comments} WHERE nid = %d', $node->nid); } function project_issue_access($op, $node, $account) { if (user_access('administer projects', $account)) { return TRUE; } switch ($op) { case 'view': if (user_access('access own project issues', $account) && $node->uid == $account->uid) { return TRUE; } if (!user_access('access project issues', $account)) { return FALSE; } break; case 'create': return user_access('create project issues', $account); case 'update': if (user_access('edit own project issues', $account) && $node->uid == $account->uid) { return TRUE; } break; case 'delete': // Admin case already handled, no one else should be able to delete. break; } } // Support stuff /** * Return information about project issue state values. * * @param $sid * Integer state id to return information about, or 0 for all states. * @param $restrict * Boolean to determine if states should be restricted based on the * permissions of the current user or $account if that parameter * is provided. * @param $is_author * Boolean that indicates if the current user is the author of the * issue, which can potentially grant a wider selection of states. * @param $current_sid * The current integer state id for the issue. * @param $defaults * Boolean to request the states used for default issue queries. * @param $account * Account of a user to pass to user_access() for access checking. * This parameter will have no effect unless $restrict is also * set to TRUE. * * @return * An array of states (sid as key, name as value) that match the * given filters, or the name of the requested state. * NOTE: The state name returned is raw text, and should be filtered via * check_plain() or filter_xss() before being printed as HTML output. */ function project_issue_state($sid = 0, $restrict = false, $is_author = false, $current_sid = 0, $defaults = false, $account = NULL) { static $options; if (!$options) { $result = db_query('SELECT * FROM {project_issue_state} ORDER BY weight'); while ($state = db_fetch_object($result)) { $options[] = $state; } } foreach($options as $state) { if ($restrict) { // Check if user has access, // or if status is default status and therefore available to all, // or if user is original issue author and author has access, // or if the issue is already in a state, even if the user doesn't have // access to that state themselves. if (user_access('set issue status '. str_replace("'", "", $state->name), $account) || user_access('administer projects', $account) || ($state->sid == variable_get('project_issue_default_state', 1)) || ($state->author_has && $is_author) || ($state->sid == $current_sid) ) { $states[$state->sid] = $state->name; } } else if ($defaults) { if ($state->default_query) { $states[$state->sid] = $state->name; } } else { $states[$state->sid] = $state->name; } } return $sid ? $states[$sid] : $states; } /** * Return an array of state ids that should be used for default queries. */ function project_issue_default_states() { static $defaults; if (empty($defaults)) { $states = project_issue_state(0, false, false, 0, true); $defaults = !empty($states) ? array_keys($states) : array(1, 2, 4); } return $defaults; } function project_issue_priority($priority = 0) { $priorities = array(1 => t('critical'), t('normal'), t('minor')); return $priority ? $priorities[$priority] : $priorities; } function project_issue_category($category = 0, $plural = 1) { if ($plural) { $categories = array('bug' => t('bug reports'), 'task' => t('tasks'), 'feature' => t('feature requests'), 'support' => t('support requests')); } else { $categories = array('bug' => t('bug report'), 'task' => t('task'), 'feature' => t('feature request'), 'support' => t('support request')); } return $category ? $categories[$category] : $categories; } function project_issue_count($pid) { $state = array(); $result = db_query('SELECT p.sid, count(p.sid) AS count FROM {node} n INNER JOIN {project_issues} p ON n.nid = p.nid WHERE n.status = 1 AND p.pid = %d GROUP BY p.sid', $pid); while ($data = db_fetch_object($result)) { $state[$data->sid] = $data->count; } return $state; } /** * Return the HTML to use for the links at the top of issue query pages. * * @param $links * Array of links, indexed by the action ('create', 'search', etc). * * @see project_issue_query_result() * @see theme_links() */ function theme_project_issue_query_result_links($links) { return theme('links', $links); } /** * Provide an array of project issue summary fields. * @param $context * The context in which the fields will be displayed. * 'web' for project_issue node and comment summary tables. * 'email' for project_issue notification e-mail messages. */ function project_issue_field_labels($context) { if ($context == 'web') { $labels = array('title' => t('Title')); } else {
Br3nda/drupal-module-project_issue
cf5d9ce40ef8d719d8758b4ba7369b9e519df23b
#425728 by dww: Added the project title to the issue cockpit block title.
diff --git a/project_issue.module b/project_issue.module index b8c8ddc..5ab9c78 100644 --- a/project_issue.module +++ b/project_issue.module @@ -1,514 +1,514 @@ <?php -// $Id: project_issue.module,v 1.165 2009/05/05 19:15:57 dww Exp $ +// $Id: project_issue.module,v 1.166 2009/05/09 18:16:30 dww Exp $ // issue nodes -> project_issues // issue comments -> project_issue_comments /// Default age in days of issues to auto close. define('PROJECT_ISSUE_AUTO_CLOSE_DAYS', 14); /// Project issue state = fixed. define('PROJECT_ISSUE_STATE_FIXED', 2); /// Project issue state = closed. define('PROJECT_ISSUE_STATE_CLOSED', 7); /** * Implementation of hook_init(). */ function project_issue_init() { /// @TODO: we need a real page split instead of this. foreach (array('issue', 'comment', 'mail') as $file) { module_load_include('inc', 'project_issue', $file); } /// @TODO: this should only be done on pages that need it. $path = drupal_get_path('module', 'project_issue'); drupal_add_css($path .'/project_issue.css'); } function project_issue_menu() { $items = array(); $includes = drupal_get_path('module', 'project_issue') .'/includes'; // Issues $items['project/issues/update_project'] = array( 'page callback' => 'project_issue_update_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_CALLBACK, ); $items['project/issues/statistics'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); $items['project/issues/statistics/%project_node'] = array( 'title' => 'Statistics', 'page callback' => 'project_issue_statistics', 'page arguments' => array(3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); $path = 'project/issues/subscribe-mail'; if (!variable_get('project_issue_global_subscribe_page', TRUE)) { // If we don't want the global subscribe page, require an argument. $path .= '/%'; } $items[$path] = array( 'title' => 'Subscribe', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_subscribe', 3), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'file' => 'issue.inc', ); if (module_exists('search')) { $items['search/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_search_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'type' => MENU_LOCAL_TASK, 'weight' => 4, ); } // "My projects" page (which shows all issues for all your projects) $items['project/user'] = array( 'title' => 'My projects', 'page callback' => 'project_issue_user_page', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('auth'), 'type' => MENU_NORMAL_ITEM, 'weight' => -49, ); // Administrative pages $items['admin/project/project-issue-settings'] = array( 'title' => 'Project issue settings', 'description' => 'Specify where attachments to issues should be stored on your site, and what filename extensions should be allowed.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_settings_form'), 'access arguments' => array('administer projects'), 'weight' => 1, 'type' => MENU_NORMAL_ITEM, 'file' => 'includes/admin.settings.inc', ); // Administer issue status settings $items['admin/project/project-issue-status'] = array( 'title' => 'Project issue status options', 'description' => 'Configure what issue status values should be used on your site.', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_admin_states_form'), 'access arguments' => array('administer projects'), 'type' => MENU_NORMAL_ITEM, 'weight' => 1, 'file' => 'includes/admin.issue_status.inc' ); $items['admin/project/project-issue-status/delete'] = array( 'title' => 'Delete', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_delete_state_confirm', 4), 'access arguments' => array('administer projects'), 'type' => MENU_CALLBACK, 'file' => 'includes/admin.issue_status.inc' ); // Issues subtab on project node edit tab. $items['node/%project_node/edit/issues'] = array( 'title' => 'Issues', 'page callback' => 'project_issue_project_edit_issues', 'page arguments' => array(1), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_LOCAL_TASK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/%project_node/edit/component/delete/%'] = array( 'title' => 'Delete component', 'description' => 'Delete component', 'page callback' => 'drupal_get_form', 'page arguments' => array('project_issue_component_delete_form', 1, 5), 'access callback' => 'node_access', 'access arguments' => array('update', 1), 'type' => MENU_CALLBACK, 'file' => 'includes/project_edit_issues.inc', ); $items['node/add/project-issue/%'] = array( 'page callback' => 'node_add', 'page arguments' => array('project-issue'), 'title' => drupal_ucfirst(node_get_types('name', 'project_issue')), 'title callback' => 'check_plain', 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'page callback' => 'node_add', 'page arguments' => array(2), 'file' => 'node.pages.inc', 'file path' => drupal_get_path('module', 'node'), 'type' => MENU_CALLBACK, ); // Redirect node/add/project_issue/* to node/add/project-issue. $items['node/add/project_issue'] = array( 'page callback' => 'project_issue_add_redirect_page', 'page arguments' => array(3, 4), 'access callback' => 'node_access', 'access arguments' => array('create', 'project_issue'), 'type' => MENU_CALLBACK, ); // Autocomplete paths. // Autocomplete a comma-separated list of projects that have issues enabled. $items['project/autocomplete/issue/project'] = array( 'page callback' => 'project_issue_autocomplete_issue_project', 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); // Autocomplete a comma-separated list of projects from all issues a user // has either submitted or commented on. $items['project/autocomplete/issue/user/%'] = array( 'page callback' => 'project_issue_autocomplete_user_issue_project', 'page arguments' => array(4, 5), 'access callback' => 'project_issue_menu_access', 'access arguments' => array('any'), 'file' => 'autocomplete.inc', 'file path' => $includes, 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_menu_alter(). */ function project_issue_menu_alter(&$callbacks) { // Special menu item for the "first page" of submitting a new issue. // Instead of the treachery of a true multipage form, we just have // a simple form at node/add/project-issue that provides a project // selector which redirects to node/add/project-issue/[project-name]. $callbacks['node/add/project-issue']['page callback'] = 'project_issue_pick_project_page'; $callbacks['node/add/project-issue']['file'] = 'issue.inc'; $callbacks['node/add/project-issue']['file path'] = drupal_get_path('module', 'project_issue'); } /** * Determine access to a given type of menu item. * * @param $type * Type of menu item to check access for, can be 'any' if the current user * can access any issues, or 'auth' if the current user is authenticated and * can accses any issues. */ function project_issue_menu_access($type) { global $user; if ($type == 'auth' && empty($user->uid)) { return FALSE; } return user_access('access project issues') || user_access('access own project issues'); } /** * Redirect node/add/project_issue/* to node/add/project-issue/*. */ function project_issue_add_redirect_page($project = NULL, $category = NULL) { $path = 'node/add/project-issue'; if (!empty($project)) { $path .= "/$project"; } if (!empty($category)) { $path .= "/$category"; } drupal_goto($path); } function project_issue_help($path, $arg) { switch ($path) { case 'admin/help#project_issue': return '<h3>'. t('Mailhandler support') .'</h3>'. '<p>'. t('Basic mail format:') .'</p>'. '<pre>'. t("Type: project\nProject: chatbox\nCategory: bug report\nVersion: cvs\nPriority: normal\nStatus: active\nComponent: code\n\nWhatever I type here will be the body of the node.\n") .'</pre>'. '<p>'. t('See the mailhandler help for more information on using the mailhandler module.') .'</p>'; case 'node/add#project_issue': return t('Add a new issue (bug report, feature request, etc) to an existing project.'); case 'admin/project/project-issue-status': return '<p>'. t('Use this page to add new status options for project issues or to change or delete existing options.') .'</p>'. '<dl>'. '<dt>'. t('Adding') .'</dt>'. '<dd>'. t('To add a new status option, put its name in one of the blank places at the bottom of the form and assign it a weight.') .'</dd>'. '<dt>'. t('Updating') .'</dt>'. '<dd>'. t('When renaming existing issues, keep in mind that issues with the existing name will receive the new one.') .'</dd>'. '<dt>'. t('Deleting') .'</dt>'. '<dd>'. t('If you delete an existing issue status, you will be prompted for a new status to assign to existing issues with the deleted status.') .'</dd>'. '<dt>'. t('Weight') .'</dt>'. '<dd>'. t('The weight of an issue determines the order it appears in lists, like in the select box where users designate a status for their issue.') .'</dd>'. '<dt>'. t('Author may set') .'</dt>'. '<dd>'. t("Check this option to give the original poster of an issue the right to set a status option, even if she or he isn't part of a role with this permission. You may wish, for example, to allow issue authors to close their own issues.") .'</dd>'. '<dt>'. t('In default queries') .'</dt>'. '<dd>'. t('There are a number of pages that display a list of issues based on a certain query. For all of these views of the issue queues, if no status options are explicitly selected, a certain set of defaults will be used to construct the query.') .'</dd>'. '<dt>'. t('Default status') .'</dt>'. '<dd>'. t('The default status option will be used for new issues, and all users with the permission to create issues will automatically have permission to set this status. The default issue status cannot be deleted. If you wish to delete this status, first set a different status to default.') .'</dd>'. '</dl>'; } // NOTE: This totally sucks, and is a dirty, ugly hack. Since we don't // want to rely on PHP filtered headers for our views, and defining our // own display plugin breaks other nice things like RSS, we just cheat // and render these links in here. We'd like to remove this once a // better solution is available that doesn't hard-code the paths. if ($arg[0] == 'project' && $arg[1] == 'user') { return project_issue_my_projects_table(); } if ($arg[0] == 'project' && $arg[1] == 'issues') { // If there's no other arg, we're done. if (empty($arg[2])) { return project_issue_query_result_links(); } // project/issues/user is a special case, since if there's an argument, // it's a username, not a project. Furthermore, we don't want any links // for anonymous. if ($arg[2] == 'user') { global $user; if (empty($user->uid) && empty($arg[3])) { return; } return project_issue_query_result_links(); } switch ($arg[2]) { case 'search': case 'statistics': case 'subscribe-mail': return project_issue_query_result_links($arg[3]); default: return project_issue_query_result_links($arg[2]); } } } /** * Implementation of hook_theme(). */ function project_issue_theme() { return array( 'project_issue_comment_table' => array( 'file' => 'comment.inc', 'arguments' => array( 'comment_changes' => NULL, ), ), 'project_issue_comment_table_row' => array( 'file' => 'comment.inc', 'arguments' => array( 'field' => NULL, 'change' => NULL, ), ), 'project_issue_subscribe' => array( 'file' => 'issue.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_summary' => array( 'file' => 'issue.inc', 'arguments' => array( 'current_data' => NULL, 'summary_links' => NULL, ), ), 'project_issue_admin_states_form' => array( 'file' => 'includes/admin.issue_status.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_project_edit_form' => array( 'file' => 'includes/project_edit_issues.inc', 'arguments' => array( 'form' => NULL, ), ), 'project_issue_query_result_links' => array( 'file' => 'issue.inc', 'arguments' => array( 'links' => NULL, ), ), 'project_issue_create_forbidden' => array( 'file' => 'issue.inc', 'arguments' => array( 'uri' => NULL, ), ), 'project_issue_mail_summary' => array( 'file' => 'mail.inc', 'arguments' => array( 'entry' => NULL, 'node' => NULL, 'changes' => NULL, 'display_files' => NULL, ), ), 'project_issue_mail_summary_field' => array( 'file' => 'mail.inc', 'arguments' => array( 'node' => NULL, 'field_name' => NULL, 'change' => NULL, ), ), 'project_issue_auto_close_message' => array( 'file' => 'project_issue.module', 'arguments' => array( 'auto_close_days' => NULL, ), ), 'project_issue_issue_link' => array( 'file' => 'project_issue.module', 'arguments' => array( 'node' => NULL, 'comment_id' => NULL, 'comment_number' => NULL, 'include_assigned' => FALSE, ), ), 'project_issue_issue_cockpit' => array( 'arguments' => array( 'node' => NULL, ), 'file' => 'includes/issue_cockpit.inc', 'template' => 'theme/project-issue-issue-cockpit', ), ); } /** * Implementation of hook_views_api(). */ function project_issue_views_api() { return array( 'api' => 2.0, 'path' => drupal_get_path('module', 'project_issue') .'/views', ); } /** * Implementation of hook_form_alter. */ function project_issue_form_alter(&$form, &$form_state, $form_id) { switch ($form_id) { // Issues must be updated if any project issue comments are edited/deleted. case 'comment_admin_overview': $form['#submit'][] = 'project_issue_comment_mass_update'; break; case 'project_issue_node_form': // For our theming, wrap everything in a 'project-issue' class. $form['#prefix'] = isset($form['#prefix'])? $form['#prefix'] : ''; $form['#prefix'] .= '<div class="project-issue">'; $form['#suffix'] = isset($form['#suffix'])? $form['#suffix'] : ''; $form['#suffix'] = '</div>'. $form['#suffix']; if (isset($form['attachments'])) { if (isset($form['project_info'])) { // We already know what project it is, so make sure the 'File // attachments' fieldset is expanded. $form['attachments']['#collapsed'] = FALSE; } else { // On the first page of the multi-page form, don't have a project // selected yet, so unset the file attachments fieldset entirely. unset($form['attachments']); } } break; // see also: project_issue_form_comment_form_alter case 'comment_form': $nid = $form['nid']['#value']; $node = node_load($nid); // Allows only project_issue if ($node->type != 'project_issue') { return; } // Make sure the 'File attachments' fieldset is expanded and before the // original issue fieldset. if (isset($form['attachments'])) { $form['attachments']['#collapsed'] = FALSE; $form['attachments']['#weight'] = 2; // TODO: temporary hack until we decide how to deal with // editing attachments on issues overall. if (!empty($form['cid']['#value'])) { unset($form['attachments']); } } // Add our own custom validation to the comment form for issue nodes. $form['#validate'][] = 'project_issue_form_comment_validate'; break; case 'comment_confirm_delete': $type = db_result(db_query("SELECT type FROM {node} WHERE nid = %d", $form['#comment']->nid)); if (!empty($type) && $type == 'project_issue') { $form['description']['#value'] = t('This action cannot be undone.'); } break; case 'views_exposed_form': project_issue_alter_views_exposed_form($form, $form_state); break; case 'project_issue_issue_cockpit_searchbox': // Since we're using a GET #action for this searchbox, unset the FAPI // cruft we don't want to see in the URL. unset($form['form_build_id']); unset($form['form_id']); unset($form['form_token']); break; } } function project_issue_node_info() { return array( 'project_issue' => array( 'name' => t('Issue'), 'module' => 'project_issue', 'description' => t('An issue that can be tracked, such as a bug report, feature request, or task.'), ), ); } function project_issue_perm() { $perms = array( 'create project issues', 'access project issues', 'edit own project issues', 'access own project issues', 'assign and be assigned project issues', ); $states = project_issue_state(); foreach($states as $key => $value) { $perms[] = "set issue status ". str_replace("'", "", $value); } return $perms; } /** * Helper to trim all elements in an array. */ function project_issue_trim(&$item, $key) { @@ -1159,535 +1159,535 @@ function project_issue_filter($op, $delta = 0, $format = -1, $text = '') { } } function project_issue_link_filter_callback($matches) { $parts = array(); if (preg_match('/^\[#(\d+)(?:-(\d+))?(@)?\]$/', $matches[0], $parts)) { $nid = $parts[1]; $node = node_load($nid); $include_assigned = isset($parts[3]); if (is_object($node) && node_access('view', $node) && $node->type == 'project_issue') { if (isset($parts[2])) { // Pull comment id based on the comment number if we have one. $comment_number = $parts[2]; if ($comment_id = db_result(db_query("SELECT pic.cid FROM {project_issue_comments} pic INNER JOIN {comments} c ON pic.cid = c.cid WHERE pic.nid = %d AND pic.comment_number = %d AND c.status = %d", $nid, $comment_number, COMMENT_PUBLISHED))) { return theme('project_issue_issue_link', $node, $comment_id, $comment_number, $include_assigned); } } // If we got this far there wasn't a valid comment number, so just link // to the node instead. return theme('project_issue_issue_link', $node, NULL, NULL, $include_assigned); } } // If we haven't already returned a replacement, return the original text. return $matches[0]; } /** * Implementation of hook_requirements(). * @ingroup project_issue_filter * * Check for conflicts with: * installed node access control modules, * 'access project issues' restrictions, * filters escaping code with higher weight. */ function project_issue_requirements($phase) { $requirements = array(); $input_formats = array(); if ($phase == 'runtime') { $grants = module_implements('node_grants'); if (!empty($grants)) { $conflict_grants = TRUE; } $allowed_roles = user_roles(FALSE, 'access project issues'); if (!isset($allowed_roles[DRUPAL_ANONYMOUS_RID])) { $conflict_anonymous = TRUE; } foreach (filter_formats() as $format => $input_format) { $filters = filter_list_format($format); if (isset($filters['project_issue/0'])) { if ($conflict_grants && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some module conflicts were detected.'), 'description' => t('%issuefilter should not be enabled when a node access control is also in use. Users may be able to see cached titles of project issues they would otherwise not have access to. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } if ($conflict_anonymous && filter_format_allowcache($format)) { $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some security conflicts were detected.'), 'description' => t('%issuefilter conflicts with project issue access settings. Users who do not have access to all project issues may be able to see titles of project issues. You should disable this filter in !inputformat input format.', array('%issuefilter' => t('Project Issue to link filter'), '!inputformat' => l($input_format->name, "admin/settings/filters/$format"))), 'severity' => REQUIREMENT_ERROR, ); } // Put up an error when some code escaping filter's weight is higher. $low_filters = array('filter/0', 'filter/1', 'bbcode/0', 'codefilter/0', 'geshifilter/0'); foreach ($low_filters as $lfilter) { if (isset($filters[$lfilter]) && $filters['project_issue/0']->weight <= $filters[$lfilter]->weight) { $description_names['%issuefilter'] = $filters['project_issue/0']->name; $description_names['%lowfilter'] = $filters[$lfilter]->name; $requirements[] = array( 'title' => t('Project Issue to link filter'), 'value' => t('Some filter conflicts were detected.'), 'description' => t('%issuefilter should come after %lowfilter to prevent loss of layout and highlighting.', $description_names) .' '. l(t('Please rearrange the filters.'), "admin/settings/filters/$format/order"), 'severity' => REQUIREMENT_ERROR, ); } } } } } return $requirements; } /** * Calculate the differences in project_issue comment metadata * between the original issue and a comment or between two * comments. * * @param $view * A string representing the metadata view being generated. For the comment * metadata table, this will be 'diff'. * @param $node * The issue node. * @param $old_data * Object containing old metadata. * @param $new_data * Object containing new metadata. * @param $field_labels * An associative array of field_name=>display_name pairs. * In most cases, this will be the array returned by project_issue_change_summary(). * * @return * An associative array containing information about changes between * the two objects. * For example: * array( * 'component' => array( * 'label' => t('Component'), * 'old' => 'Code', * 'new' => 'User interface', * ), * 'sid' => array( * 'label' => t('Status'), * 'old' => 8, * 'new' => 13, * ), * ) */ function project_issue_metadata_changes($node, $old_data, $new_data, $field_labels = array()) { $changes = array(); foreach ($field_labels as $property => $name) { if ($property == 'rid' && empty($old_data->rid) && empty($new_data->rid)) { // Special case for version -- if both are empty, leave it out entirely, // since maybe this project doesn't have (and/or disabled) releases. continue; } if (isset($old_data->$property) || isset($new_data->$property)) { $changes[$property] = array('label' => $name); } if (isset($old_data->$property) && isset($new_data->$property)) { if ($old_data->$property != $new_data->$property) { $changes[$property]['old'] = $old_data->$property; $changes[$property]['new'] = $new_data->$property; } } elseif (isset($old_data->$property)) { $changes[$property]['old'] = $old_data->$property; } elseif (isset($new_data->$property)) { $changes[$property]['new'] = $new_data->$property; } } // Allow other modules to implement hook_project_issue_metadata() so that they // can find changes in additional metadata. In most cases other modules will // be responsible for storing this metadata in their own tables. Developers // of modules that implement this hook should keep in mind the following: // 1. Implementations of hook_project_issue_metadata() must take the // $changes array by reference. // 2. Differences in properties will only be processed later on for // elements of the array which have the 'label', 'old', and 'new' properties // defined. // In other words, for each line in the differences table (or field in the email) // that is displayed, your hook should add something like the following as a // new element of the $changes array: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => 'MySQL, pgSQL, javascript', // 'new' => 'pgSQL, newbie', // ), // // There are two methods you can use to indicate multiple changes of a field. // The first is that for 'old' and 'new' you pass strings separated by some // character, customarily a comma. This method is used in // the example above. When using this method, the default display of the changes // will be to show all old values followed by all new values. In the example // above, this would be displayed like: // Vocabulary 10: MySQL, pgSQL, javascript >> pgSQL, newbie // // The other method you can use when constructing 'old' and 'new' is to make // both of these arrays, with each element of the array one change. If you // use this method, all elements in the 'old' array are typically interpreted // as being removed, and all elements in the 'new' array are typically interpreted // as being added. An example of this type of structure is as follows: // 'taxonomy_vid_10' => array( // 'label' => 'Vocabulary 10', // 'old' => array('MySQL', 'javascript'), // 'new' => array('newbie'), // ), // In this situation, the default display of these changes in a project issue // metadata table would be as follows: // Vocabulary 10: -MySQL, -javascript +newbie foreach (module_implements('project_issue_metadata') as $module) { $function = $module .'_project_issue_metadata'; $function('diff', $node, $changes, $old_data, $new_data); } return $changes; } function project_issue_form_project_quick_navigate_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#submit' => array('project_issue_quick_navigate_issues_submit'), '#validate' => array('project_issue_quick_navigate_issues_validate'), ); } function project_issue_quick_navigate_issues_validate($form, &$form_state) { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {project_projects} pp INNER JOIN {project_issue_projects} pip ON pp.nid = pip.nid WHERE pp.nid = %d", $form_state['values']['project_goto'])); if (empty($project)) { form_set_error('project_goto', t('You must select a project to view issues for.')); } if (empty($project->issues)) { form_set_error('project_goto', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } function project_issue_quick_navigate_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_form_project_quick_navigate_title_form_alter(&$form, $form_state) { $form['issues'] = array( '#type' => 'submit', '#value' => t('View issues'), '#validate' => array('project_issue_quick_navigate_title_issues_validate'), '#submit' => array('project_issue_quick_navigate_title_issues_submit'), ); } function project_issue_quick_navigate_title_issues_validate($form, &$form_state) { if (empty($form_state['values']['project_title'])) { form_set_error('project_title', t('You must enter a project to view issues for.')); } else { $project = db_fetch_object(db_query("SELECT pp.uri, pip.issues FROM {node} n INNER JOIN {project_projects} pp ON n.nid = pp.nid INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.title = '%s'", $form_state['values']['project_title'])); if (empty($project)) { form_set_error('project_title', t('The name you entered (%title) is not a valid project.', array('%title' => $form_state['values']['project_title']))); } if (empty($project->issues)) { form_set_error('project_title', t('The selected project does not have an issue queue.')); } else { $form_state['project_uri'] = $project->uri; } } } function project_issue_quick_navigate_title_issues_submit($form, &$form_state) { $form_state['redirect'] = 'project/issues/'. $form_state['project_uri']; } function project_issue_alter_views_exposed_form(&$form, &$form_state) { switch ($form_state['view']->name) { case 'project_issue_search_all': case 'project_issue_search_project': case 'project_issue_user_projects': $user_filters = array('assigned', 'submitted', 'participant'); foreach (element_children($form) as $element) { if ($form[$element]['#type'] == 'textfield') { if ($form_state['view']->name == 'project_issue_user_projects') { $form[$element]['#size'] = 16; } else { $form[$element]['#size'] = 32; } } elseif ($form[$element]['#type'] == 'select' && $form[$element]['#multiple']) { $form[$element]['#size'] = 5; } if (in_array($element, $user_filters)) { $form[$element]['#description'] = t('Enter a comma separated list of users.'); } } break; } // Rename the "Apply" button to "Search" on all project_issue_* views. if (substr($form_state['view']->name, 0, 14) == 'project_issue_') { $form['submit']['#value'] = t('Search'); } } function project_issue_preprocess_views_view_table($variables) { $view = $variables['view']; if ($view->plugin_name == 'project_issue_table') { foreach ($view->result as $num => $result) { $variables['row_classes'][$num][] = "state-$result->project_issues_sid"; $variables['row_classes'][$num][] = "priority-$result->project_issues_priority"; } } $variables['class'] .= " project-issue"; } /** * Generate the links used at the top of query result pages. * * @param $project_arg * The node ID or project short name (uri) of the project to generate links * for, or NULL if it's a page of site-wide issues. * * @return * Themed HTML output for the list of links. * * @see theme_project_issue_query_result_links() */ function project_issue_query_result_links($project_arg = NULL) { global $user; $links = array(); if (empty($project_arg)) { // These are site-wide links, not per-project if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue", 'attributes' => array('title' => t('Create a new issue.')), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden'), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search", 'attributes' => array('title' => t('Use the advanced search page for finding issues.')), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics", 'attributes' => array('title' => t('See statistics about issues.')), ); if (!empty($user->uid) && variable_get('project_issue_global_subscribe_page', TRUE)) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail", 'attributes' => array('title' => t('Receive e-mail updates about issues.')), ); } } else { // We know the project, make project-specific links. if (is_numeric($project_arg)) { $uri = project_get_uri_from_nid($project_arg); } else { $uri = $project_arg; } if (node_access('create', 'project_issue')) { $links['create'] = array( 'title' => t('Create a new issue'), 'href' => "node/add/project-issue/$uri", 'attributes' => array('title' => t('Create a new issue for @project.', array('@project' => $uri))), ); } else { $links['create'] = array( 'title' => theme('project_issue_create_forbidden', $uri), 'html' => TRUE, ); } $links['search'] = array( 'title' => t('Advanced search'), 'href' => "project/issues/search/$uri", 'attributes' => array('title' => t('Use the advanced search page to find @project issues.', array('@project' => $uri))), ); $links['statistics'] = array( 'title' => t('Statistics'), 'href' => "project/issues/statistics/$uri", 'attributes' => array('title' => t('See statistics about @project issues.', array('@project' => $uri))), ); if ($user->uid) { $links['subscribe'] = array( 'title' => t('Subscribe'), 'href' => "project/issues/subscribe-mail/$uri", 'attributes' => array('title' => t('Receive e-mail updates about @project issues.', array('@project' => $uri))), ); } } return theme('project_issue_query_result_links', $links); } /** * Helper function to return an array of projects that meet a given constraint. * * @param $constraint * Restrict the list of projects. Valid options are 'all' (all projects * with issue tracking enabled), 'owner' (all projects owned by a given * user) and 'participant' (all projects from issues that a given user * submitted or commented on. * @param $uid * User ID to use for $constraint == 'owner' or 'participant'. * * @return * Array of project titles, keyed by node ID (nid) that match the given * constraint. */ function project_issue_get_projects($constraint = 'all', $uid = NULL) { $options = array(); $join = ''; // Only published projects. $where[] = 'n.status = %d'; $args[] = 1; // That have issue tracking enabled. $where[] = 'pip.issues = %d'; $args[] = 1; // Add extra JOIN and WHERE depending on the requested project source. switch ($constraint) { case 'owner': // The given uid must own each project. $where[] = 'n.uid = %d'; $args[] = $uid; break; case 'participant': $join = 'INNER JOIN {project_issues} pi ON n.nid = pi.pid INNER JOIN {node} pin ON pi.nid = pin.nid LEFT JOIN {comments} c ON pi.nid = c.nid'; // Restrict to published issues... $where[] = 'pin.status = %d'; $args[] = 1; // ...that this user submitted or commented on. $where[] = '(pin.uid = %d OR c.uid = %d)'; $args[] = $uid; $args[] = $uid; break; } // Build the actual query. $sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {project_issue_projects} pip ON n.nid = pip.nid $join WHERE " . implode(' AND ', $where) . " ORDER BY n.title ASC"; $query = db_query(db_rewrite_sql($sql), $args); while ($project = db_fetch_object($query)) { $options[$project->nid] = $project->title; } return $options; } /** * Menu access callback for the project_issue_plugin_access_user_list plugin. */ function project_issue_views_user_access($view_name, $display_id, $argument_name) { $view = views_get_view($view_name); $view->set_display($display_id); $view->init_handlers(); // Find the values for any arguments embedded in the path via '%'. $i = 0; foreach (explode('/', $view->display_handler->get_option('path')) as $element) { if ($element == '%') { $view->args[] = arg($i); } $i++; } // Now handle any implicit arguments from the end of the path. $num_arguments = count($view->argument); while (count($view->args) < $num_arguments) { $view->args[] = arg($i); $i++; } $arg_uid = $view->argument[$argument_name]->get_value(); return !empty($arg_uid); } /** * Return the views filter identifier for a given project issue vocabulary. */ function project_issue_views_filter_identifier($name) { return drupal_strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', check_plain($name))); } /** * Implementation of hook_block(). */ function project_issue_block($op = 'list', $delta = 0, $edit = array()) { if ($op == 'list') { $blocks['issue_cockpit'] = array( 'info' => t('Issue cockpit'), 'cache' => BLOCK_CACHE_PER_ROLE | BLOCK_CACHE_PER_PAGE, ); return $blocks; } elseif ($op == 'configure' && $delta == 'issue_cockpit') { $options = array('All' => t('All issues')) + project_issue_category(); $form['project_issue_cockpit_categories'] = array( '#type' => 'checkboxes', '#title' => t('Issue categories to display'), '#description' => t('Select which categories the block should display a summary of total vs. open issues.'), '#default_value' => variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')), '#options' => $options, ); return $form; } elseif ($op == 'save' && $delta == 'issue_cockpit') { variable_set('project_issue_cockpit_categories', $edit['project_issue_cockpit_categories']); // Invalidate the cache for this block since the categories might change. cache_clear_all('project_issue_cockpit_block:', 'cache', TRUE); } elseif ($op == 'view' && ($node = project_get_project_from_menu()) && !empty($node->project_issue['issues']) && node_access('view', $node)) { $cid = 'project_issue_cockpit_block:'. $node->nid; if (($cache = cache_get($cid))) { $block = $cache->data; } else { module_load_include('inc', 'project_issue', 'includes/issue_cockpit'); $block = array( - 'subject' => t('Issues'), + 'subject' => t('Issues for @project', array('@project' => $node->title)), 'content' => theme('project_issue_issue_cockpit', $node), ); cache_set($cid, $block); } return $block; } } /** * Implemenation of hook_project_page_link_alter(). * * Add project_issue-specific links to the array of project links. */ function project_issue_project_page_link_alter(&$links, $node) { // TODO: Assumes "patch" issue status values (http://drupal.org/node/27865). // Prepend a link to the development section to view pending patches. if (!empty($node->project['uri'])) { $patches['pending_patches'] = l(t('View pending patches'), 'project/issues/search/'. $node->project['uri'], array('query' => 'status[]=8&status[]=13&status[]=14')); $links['development']['links'] = $patches + $links['development']['links']; } }
Br3nda/drupal-module-project_issue
25722155ce7d63ee109c504928992eb841826c05
#425728 by dww: Due to the caching for the issue cockpit block, don't conditionally test for permission to create issues just to display the hint about searching existing issues before submitting a new one.
diff --git a/theme/project-issue-issue-cockpit.tpl.php b/theme/project-issue-issue-cockpit.tpl.php index c0dcc9a..bd1bf59 100644 --- a/theme/project-issue-issue-cockpit.tpl.php +++ b/theme/project-issue-issue-cockpit.tpl.php @@ -1,36 +1,34 @@ <?php -// $Id: project-issue-issue-cockpit.tpl.php,v 1.5 2009/05/06 23:43:34 dww Exp $ +// $Id: project-issue-issue-cockpit.tpl.php,v 1.6 2009/05/09 18:07:30 dww Exp $ ?> -<?php if ($make_issues): ?> - <?php print t('To avoid duplicates, please search before submitting a new issue.'); ?> -<?php endif; ?> +<?php print t('To avoid duplicates, please search before submitting a new issue.'); ?> <?php if ($view_issues): ?> <?php print $form; ?> <div class="issue-cockpit-categories"> <?php foreach($categories as $key => $category): ?> <div class="issue-cockpit-<?php print $key; ?>"> <span class="category-header"><?php print ucfirst($categories[$key]['name']); ?></span> <div class="issue-cockpit-totals"> <?php print l(t('!open open', array('!open' => $categories[$key]['open'])), $path, array('query' => 'categories='. $key)); ?>, <?php print l(t('!total total', array('!total' => $categories[$key]['total'])), $path, array('query' => 'status=All&categories='. $key)); ?> </div> </div> <?php endforeach; ?> </div> <div class="issue-cockpit-subscribe"> <?php print $issue_subscribe; ?> </div> <div class="issue-cockpit-statistics"> <?php print $issue_statistics; ?> </div> <?php if ($oldest): ?> <div class="issue-cockpit-oldest"> <?php print t('Oldest open issue: @date', array('@date' => format_date($oldest, 'custom', 'j M y'))); ?> </div> <?php endif; ?> <?php endif; ?>
Br3nda/drupal-module-project_issue
f694c3d5a4849ed71921f77f0be7ed26918957b9
#456468 by dww: Fixed type of the new default_component column in the {project_issue_projects} table to be a varchar(255) to prevent SQL errors about trying to give a "text" field a default value. We don't need a whole text field for this, anyway -- a varchar will be faster.
diff --git a/project_issue.install b/project_issue.install index 3804ffc..a6f2720 100644 --- a/project_issue.install +++ b/project_issue.install @@ -1,433 +1,435 @@ <?php -// $Id: project_issue.install,v 1.61 2009/05/05 19:15:57 dww Exp $ +// $Id: project_issue.install,v 1.62 2009/05/08 18:54:09 dww Exp $ /** * Implementation of hook_schema(). */ function project_issue_schema() { $schema['project_issue_projects'] = array( 'description' => t('Table containing per-project issue-related settings.'), 'fields' => array( 'nid' => array( 'description' => t('Primary Key: The {project_projects}.nid of the project.'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'issues' => array( 'description' => t('Boolean value indicating whether or not issue-tracking is enabled for this project.'), 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'components' => array( 'description' => t('A serialized array defining the components for this project.'), 'type' => 'text', 'not null' => FALSE, ), 'default_component' => array( 'description' => t('The default component for new issues of this project, or an empty string if the user needs to select a component.'), - 'type' => 'text', + 'type' => 'varchar', + 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'help' => array( 'description' => t('Submission guidelines for issues added to this project.'), 'type' => 'text', 'not null' => FALSE, ), 'mail_digest' => array( 'description' => t('E-mail address for the weekly critical issues report.'), 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy' => array( 'description' => t('E-mail address to send a copy of all issues to.'), 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter' => array( 'description' => t('A serialized array containing the types of issues to include in the e-mail sent to {project_projects}.mail_copy.'), 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_copy_filter_state' => array( 'description' => t('A serialized array containing the statuses to include in the e-mail sent to {project_projects}.mail_copy.'), 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'mail_reminder' => array( 'description' => t('Boolean indicating whether or not users with open issues should receive a monthly reminder.'), 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('nid'), ); $schema['project_issues'] = array( 'description' => t('The base table for issues.'), 'fields' => array( 'nid' => array( 'description' => t('Primary Key: The {node}.nid of this project_issue node.'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => t('The {project_projects}.nid of the project to which this issue belongs.'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'category' => array( 'description' => t('Category of the issue.'), 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'component' => array( 'description' => t('Component of the issue as defined per-project in {project_issue_projects}.components.'), 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => t('The priority for this issue.'), 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'rid' => array( 'description' => t('The {project_release_nodes}.rid (version identifier) for this issue (only used in conjunction with the project_release module).'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => t('The {users}.uid of the user to which this issue is currently assigned.'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => t('Current {project_issue_state}.sid of this issue.'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'original_issue_data' => array( 'description' => t('A serialized object containing the original metadata values that were used when this issue was created.'), 'type' => 'text', 'not null' => TRUE, ), 'last_comment_id' => array( 'description' => t('{comments}.cid of the most recent comment added to the issue. 0 if no comment has been added yet.'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'db_lock' => array( 'description' => t('Row-lock indicator to prevent race conditions when determining sequential comment number (http://drupal.org/node/180866).'), 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_issues_pid' => array('pid'), 'project_issues_sid' => array('sid'), 'project_issues_nid_assigned' => array('nid', 'assigned'), ), 'primary key' => array('nid'), ); $schema['project_issue_comments'] = array( 'description' => t('The base table for comments added to issues.'), 'fields' => array( 'nid' => array( 'description' => t('References {project_issues}.nid, the issue to which this comment was added.'), 'type' => 'int', 'not null' => FALSE, ), 'cid' => array( 'description' => t('The {comments}.cid for this comment.'), 'type' => 'int', 'not null' => FALSE, ), 'rid' => array( 'description' => t('The {project_release_nodes}.rid (version identifier) after this comment was made (only used in conjunction with the project_release module).'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'component' => array( 'description' => t('Component of the issue after this comment was made. Components are defined per-project in {project_issue_projects}.components.'), 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'category' => array( 'description' => t('Category of this issue after this comment was made.'), 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'priority' => array( 'description' => t('The priority for this issue after this comment was made.'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'assigned' => array( 'description' => t('The {users}.uid of the user to which this issue was assigned after this comment was made.'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'sid' => array( 'description' => t('The {project_issue_state}.sid of this issue after this comment was made.'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'pid' => array( 'description' => t('The {project_projects}.nid of the project to which this issue belongs after this comment was made.'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'title' => array( 'description' => t('The title of the issue after this comment was made.'), 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, ), 'timestamp' => array( 'description' => t('Timestamp for this comment.'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, ), 'comment_number' => array( 'description' => t('The sequential number for this comment in the issue.'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'nid_timestamp' => array('nid', 'timestamp'), 'comment_number' => array('comment_number'), ), ); $schema['project_subscriptions'] = array( 'description' => t('Table keeping track of per-user project_issue subscriptions.'), 'fields' => array( 'nid' => array( 'description' => t('{project_projects}.nid of the project to which the user is subscribed.'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'uid' => array( 'description' => t('The {users}.uid for this subscriber.'), 'type' => 'int', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), 'level' => array( 'description' => t('The type of subscription for the project. Possible values are: 0 = not subscribed, 1 = subscribed to own issues or 2 = subscribed to all issues.'), 'type' => 'int', 'size' => 'tiny', 'unsigned' => 1, 'not null' => TRUE, 'default' => 0, ), ), 'indexes' => array( 'project_subscriptions_nid_uid_level' => array('nid', 'uid', 'level'), ), ); $schema['project_issue_state'] = array( 'description' => t('Table that holds all possible values for issue statuses.'), 'fields' => array( 'sid' => array( 'description' => t('Primary Key: Unique id for this status.'), 'type' => 'serial', 'unsigned' => 1, 'not null' => TRUE, ), 'name' => array( 'description' => t('Display-friendly name for this status.'), 'type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => '', ), 'weight' => array( 'description' => t('Weight for this status, used when ordering statuses'), 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'author_has' => array( 'description' => t('Boolean indicating whether or not the author of an issue may use this issue status in that issue, regardless of the permissions controlling site-wide use of this status.'), 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), 'default_query' => array( 'description' => t('Boolean indicating whether or not issues with this status are included in default queries.'), 'type' => 'int', 'size' => 'tiny', 'not null' => TRUE, 'default' => 0, ), ), 'primary key' => array('sid'), ); return $schema; } function project_issue_install() { // We need to check this before we try to create the table, so that // if it already exists, we don't attempt to insert our own values. $project_issue_state_existed = db_table_exists('project_issue_state'); // Create tables. drupal_install_schema('project_issue'); if (!$project_issue_state_existed) { // sid, name, weight, author-can-set, in-default-queries project_issue_init_state(1, 'active', -13, 0, 1); project_issue_init_state(2, 'fixed', 1, 0, 1); project_issue_init_state(3, 'duplicate', 4, 0, 0); project_issue_init_state(4, 'postponed', 6, 0, 1); project_issue_init_state(5, "won't fix", 9, 0, 0); project_issue_init_state(6, 'by design', 11, 0, 0); project_issue_init_state(7, 'closed', 13, 1, 0); project_issue_init_state(8, 'needs review', -8, 0, 0); project_issue_init_state(13, 'needs work', -6, 0, 0); project_issue_init_state(14, 'ready to commit', -2, 0, 0); // Since we're hacking in auto-increment values here, // update the sequence value for Postgres -- ugly but necessary for now. if ($GLOBALS['db_type'] == 'pgsql') { db_query("SELECT setval('project_issue_state_sid_seq', 14)"); } } project_issue_add_missing_projects(); db_query("UPDATE {system} SET weight = 2 WHERE name = 'project_issue'"); // Set up future followups to be read/write. if (module_exists('comment')) { variable_set('comment_project_issue', COMMENT_NODE_READ_WRITE); } // Enable file attachments for followups. variable_set('comment_upload_project_issue', 1); // Enable file attachments for issues. variable_set('upload_project_issue', 1); } /** * Implementation of hook_uninstall(). */ function project_issue_uninstall() { // Remove tables. drupal_uninstall_schema('project_issue'); $variables = array( 'project_issue_default_state', 'project_directory_issues', 'project_reply_to', 'project_issue_digest_last', 'project_issue_cockpit_categories', 'project_issue_digest_interval', 'project_issue_reminder_last', 'project_issue_reminder_interval', 'project_issue_show_comment_signatures', 'project_issue_site_help', 'project_issue_invalid_releases', 'project_issue_followup_user', 'project_issue_hook_cron', ); foreach ($variables as $variable) { variable_del($variable); } } function project_issue_enable() { project_issue_add_missing_projects(); } /** * Initialize a given issue state in the database. */ function project_issue_init_state($sid, $name, $weight, $author, $query) { db_query("INSERT INTO {project_issue_state} (sid, name, weight, author_has, default_query) VALUES (%d, '%s', %d, %d, %d)", $sid, $name, $weight, $author, $query); } /** * Check for existing project nodes that do not have an entry in the * {project_issue_projects} table, and add them. * */ function project_issue_add_missing_projects() { $projects = db_query("SELECT n.nid, pip.nid AS pip_nid FROM {node} n LEFT JOIN {project_issue_projects} pip ON n.nid = pip.nid WHERE n.type = 'project_project' AND pip.nid IS NULL"); while ($project = db_fetch_object($projects)) { db_query('INSERT INTO {project_issue_projects} (nid) VALUES (%d)', $project->nid); } } /** * Remove stale setting that's now provided by views. */ function project_issue_update_6000() { variable_del('project_issues_per_page'); return array(); } /** * Add the 'default_component' field to {project_issue_projects}. */ function project_issue_update_6001() { $ret = array(); - db_add_field($ret, 'project_issue_projects', 'default_component', array('type' => 'text', 'not null' => TRUE, 'default' => '')); + db_add_field($ret, 'project_issue_projects', 'default_component', + array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '')); return $ret; }
Br3nda/drupal-module-project_issue
416bd6ea55c194e2df7ceb2435c3c0d56104b55e
#425728 by longwave: Fixed two minor bugs with the new "Issue cockpit": - Don't try to print the date of the oldest open issue if there isn't one. - Corrected typo (s/subcribe/subscribe/).
diff --git a/includes/issue_cockpit.inc b/includes/issue_cockpit.inc index cc8d24f..7c618c4 100644 --- a/includes/issue_cockpit.inc +++ b/includes/issue_cockpit.inc @@ -1,81 +1,81 @@ <?php -// $Id: issue_cockpit.inc,v 1.5 2009/04/20 19:11:34 dww Exp $ +// $Id: issue_cockpit.inc,v 1.6 2009/05/06 23:43:34 dww Exp $ /** * Form builder for the search box in the issue cockpit block. */ function project_issue_issue_cockpit_searchbox(&$form_state, $node) { $search_path = 'project/issues/' . $node->project['uri']; $adv_search_path = 'project/issues/search/' . $node->project['uri']; return array( '#action' => url($search_path), '#method' => 'get', 'text' => array( '#type' => 'textfield', '#size' => 20, ), 'status' => array( '#type' => 'hidden', '#value' => 'All', ), 'submit' => array( '#type' => 'submit', '#value' => t('Search'), '#name' => '', ), 'advanced' => array( '#value' => l(t('Advanced search'), $adv_search_path), ), ); } /** * Theme template preprocess to declare variables for the issue cockpit. */ function template_preprocess_project_issue_issue_cockpit(&$vars) { $node = $vars['node']; // Flags that indicate what kind of access to project issues to allow. $has_issues = !empty($node->project_issue['issues']); $vars['view_issues'] = $has_issues && (user_access('access project issues') || user_access('access own project issues') || user_access('administer projects')); $vars['make_issues'] = $has_issues && node_access('create', 'project_issue'); if ($vars['view_issues']) { $open_states = '('. implode(',', array_keys(project_issue_state(0, FALSE, FALSE, 0, TRUE))) .')'; $vars['path'] = 'project/issues/'. $node->project['uri']; $vars['form'] = drupal_get_form('project_issue_issue_cockpit_searchbox', $node); $vars['categories'] = array(); $categories = array('All' => t('All issues')) + project_issue_category(); $setting = variable_get('project_issue_cockpit_categories', array('All' => 'All', 'bug' => 'bug')); $active_categories = array_intersect_key($categories, array_filter($setting)); foreach ($active_categories as $category => $name) { $vars['categories'][$category] = array('name' => $name, 'open' => 0, 'total' => 0); } if (isset($vars['categories']['All'])) { $vars['categories']['All']['open'] = db_result(db_query(db_rewrite_sql('SELECT count(*) FROM {node} n INNER JOIN {project_issues} i ON n.nid = i.nid WHERE n.status = 1 AND i.pid = %d AND i.sid IN '. $open_states), $node->nid)); $vars['categories']['All']['total'] = db_result(db_query(db_rewrite_sql('SELECT count(*) FROM {node} n INNER JOIN {project_issues} i ON n.nid = i.nid WHERE n.status = 1 AND i.pid = %d'), $node->nid)); } $result = db_query(db_rewrite_sql('SELECT count(*) AS open, i.category FROM {node} n INNER JOIN {project_issues} i ON n.nid = i.nid WHERE n.status = 1 AND i.pid = %d AND i.sid IN '. $open_states .' GROUP BY i.category'), $node->nid); while ($category = db_fetch_object($result)) { if (isset($vars['categories'][$category->category])) { $vars['categories'][$category->category]['open'] = $category->open; } } $result = db_query(db_rewrite_sql('SELECT count(*) AS total, i.category FROM {node} n INNER JOIN {project_issues} i ON n.nid = i.nid WHERE n.status = 1 AND i.pid = %d GROUP BY i.category'), $node->nid); while ($category = db_fetch_object($result)) { if (isset($vars['categories'][$category->category])) { $vars['categories'][$category->category]['total'] = $category->total; } } - $vars['issue_subscribe'] = l(t('Subcribe via e-mail'), 'project/issues/subscribe-mail/'. $node->project['uri'], array('query' => drupal_get_destination())); + $vars['issue_subscribe'] = l(t('Subscribe via e-mail'), 'project/issues/subscribe-mail/'. $node->project['uri'], array('query' => drupal_get_destination())); $vars['issue_statistics'] = l(t('Issue statistics'), 'project/issues/statistics/'. $node->project['uri']); $vars['oldest'] = db_result(db_query(db_rewrite_sql('SELECT min(n.created) FROM {node} n INNER JOIN {project_issues} i ON n.nid = i.nid WHERE n.status = 1 AND i.pid = %d AND i.sid IN '. $open_states), $node->nid)); } } diff --git a/theme/project-issue-issue-cockpit.tpl.php b/theme/project-issue-issue-cockpit.tpl.php index f30d8b7..c0dcc9a 100644 --- a/theme/project-issue-issue-cockpit.tpl.php +++ b/theme/project-issue-issue-cockpit.tpl.php @@ -1,34 +1,36 @@ <?php -// $Id: project-issue-issue-cockpit.tpl.php,v 1.4 2009/04/20 19:11:35 dww Exp $ +// $Id: project-issue-issue-cockpit.tpl.php,v 1.5 2009/05/06 23:43:34 dww Exp $ ?> <?php if ($make_issues): ?> <?php print t('To avoid duplicates, please search before submitting a new issue.'); ?> <?php endif; ?> <?php if ($view_issues): ?> <?php print $form; ?> <div class="issue-cockpit-categories"> <?php foreach($categories as $key => $category): ?> <div class="issue-cockpit-<?php print $key; ?>"> <span class="category-header"><?php print ucfirst($categories[$key]['name']); ?></span> <div class="issue-cockpit-totals"> <?php print l(t('!open open', array('!open' => $categories[$key]['open'])), $path, array('query' => 'categories='. $key)); ?>, <?php print l(t('!total total', array('!total' => $categories[$key]['total'])), $path, array('query' => 'status=All&categories='. $key)); ?> </div> </div> <?php endforeach; ?> </div> <div class="issue-cockpit-subscribe"> <?php print $issue_subscribe; ?> </div> <div class="issue-cockpit-statistics"> <?php print $issue_statistics; ?> </div> - <div class="issue-cockpit-oldest"> - <?php print t('Oldest open issue: @date', array('@date' => format_date($oldest, 'custom', 'j M y'))); ?> - </div> + <?php if ($oldest): ?> + <div class="issue-cockpit-oldest"> + <?php print t('Oldest open issue: @date', array('@date' => format_date($oldest, 'custom', 'j M y'))); ?> + </div> + <?php endif; ?> <?php endif; ?>
coleifer/django-generic-aggregation
7dc1557ac0a791ccc56278b57ba25d6651d868e0
readthedocs required updates.
diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..850d79c --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,4 @@ +version: 2 +python: + install: + - requirements: docs/requirements.txt diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..93120e6 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1 @@ +docutils<0.18
coleifer/django-generic-aggregation
b30c1ee475dedd50bcb893145f363303a71db710
fix readme formatting
diff --git a/README.rst b/README.rst index c3f181b..841b7cb 100644 --- a/README.rst +++ b/README.rst @@ -1,71 +1,73 @@ ========================== django-generic-aggregation ========================== annotate() and aggregate() for generically-related data. also a handy function for filtering GFK-model querysets. Use django's `GenericRelation <https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations>`_ where possible, as this can make the queries generated more efficient by using a JOIN rather than a subquery. installation ------------ :: # install from pypi pip install django-generic-aggregation # or install via git pip install -e git+git://github.com/coleifer/django-generic-aggregation.git#egg=generic_aggregation examples -------- The examples below assume the following simple models: :: class Rating(models.Model): rating = models.IntegerField() object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') class Food(models.Model): name = models.CharField(max_length=50) ratings = generic.GenericRelation(Rating) # reverse generic relation You want to figure out which items are highest rated (generic_annotate) :: from django.db.models import Avg food_qs = Food.objects.filter(name__startswith='a') generic_annotate(food_qs, Rating, Avg('ratings__rating')) # you can mix and match queryset / model generic_annotate(food_qs, Rating.objects.all(), Avg('ratings__rating')) You want the average rating for all foods that start with 'a' (generic_aggregate) :: food_qs = Food.objects.filter(name__startswith='a') generic_aggregate(food_qs, Rating, Avg('ratings__rating')) You want to only display ratings for foods that start with 'a' (generic_filter) +:: + food_qs = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), food_qs) documentation ------------- https://django-generic-aggregation.readthedocs.io/
coleifer/django-generic-aggregation
e5e11255e6ab70dc74854945a59f4c74b918c934
Convert readthedocs links for their .org -> .io migration for hosted projects
diff --git a/README.rst b/README.rst index d11c57d..c3f181b 100644 --- a/README.rst +++ b/README.rst @@ -1,71 +1,71 @@ ========================== django-generic-aggregation ========================== annotate() and aggregate() for generically-related data. also a handy function for filtering GFK-model querysets. Use django's `GenericRelation <https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations>`_ where possible, as this can make the queries generated more efficient by using a JOIN rather than a subquery. installation ------------ :: # install from pypi pip install django-generic-aggregation # or install via git pip install -e git+git://github.com/coleifer/django-generic-aggregation.git#egg=generic_aggregation examples -------- The examples below assume the following simple models: :: class Rating(models.Model): rating = models.IntegerField() object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') class Food(models.Model): name = models.CharField(max_length=50) ratings = generic.GenericRelation(Rating) # reverse generic relation You want to figure out which items are highest rated (generic_annotate) :: from django.db.models import Avg food_qs = Food.objects.filter(name__startswith='a') generic_annotate(food_qs, Rating, Avg('ratings__rating')) # you can mix and match queryset / model generic_annotate(food_qs, Rating.objects.all(), Avg('ratings__rating')) You want the average rating for all foods that start with 'a' (generic_aggregate) :: food_qs = Food.objects.filter(name__startswith='a') generic_aggregate(food_qs, Rating, Avg('ratings__rating')) You want to only display ratings for foods that start with 'a' (generic_filter) food_qs = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), food_qs) documentation ------------- -http://django-generic-aggregation.readthedocs.org/ +https://django-generic-aggregation.readthedocs.io/
coleifer/django-generic-aggregation
cbdb2caa21d3a6728f6475a68952fd6dd7e8f094
Remove unused function.
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index a16ca36..6083b58 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,352 +1,306 @@ """ Django does not properly set up casts """ import django from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection -from django.db.models import Q from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type -def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): - qs = normalize_qs_model(qs_model) - generic_qs = normalize_qs_model(generic_qs_model) - - model = qs.model - generic_model = generic_qs.model - - if gfk_field is None: - gfk_field = get_gfk_field(generic_model) - - content_type = ContentType.objects.get_for_model(model) - - if django.VERSION < (1, 8): - rel_name = aggregator.lookup.split('__', 1)[0] - else: - rel_name = aggregator.default_alias.split('__', 1)[0] - - try: - generic_rel_descriptor = getattr(model, rel_name) - except AttributeError: - # missing the generic relation, so do fallback query - return False - - rel_model = generic_rel_descriptor.field.rel.to - if rel_model != generic_model: - raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( - generic_model, rel_name, rel_model, - )) - - pk_field_type = get_field_type(model._meta.pk) - gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) - if pk_field_type != gfk_field_type: - return False - - qs = qs.filter( - Q(**{ - '%s__%s' % (rel_name, gfk_field.ct_field): content_type, - '%s__pk__in' % (rel_name): generic_qs.values('pk'), - }) - | Q(**{ - '%s__%s__isnull' % (rel_name, gfk_field.ct_field): True, - }) - ) - return qs - def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if 'mysql' in connection.settings_dict['ENGINE'] and pk_field_type == 'integer': pk_field_type = 'unsigned' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name if django.VERSION < (1, 8): aggregate_field = aggregator.lookup else: aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name if django.VERSION < (1, 8): aggregate_field = aggregator.lookup else: aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params )
coleifer/django-generic-aggregation
50079259353b7c186f9befb6c3282ab4521af68d
Add failing test for ORM-based annotation and fix.
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 640807d..a16ca36 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,362 +1,352 @@ """ Django does not properly set up casts """ import django from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection from django.db.models import Q from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) if django.VERSION < (1, 8): rel_name = aggregator.lookup.split('__', 1)[0] else: rel_name = aggregator.default_alias.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter( Q(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) | Q(**{ '%s__%s__isnull' % (rel_name, gfk_field.ct_field): True, }) ) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ - prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) - if prepared_query is not False: - return prepared_query.annotate(**{alias: aggregator}) - else: - # need to fall back since CAST will be missing - return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) + return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ - prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) - if prepared_query is not False: - return prepared_query.aggregate(aggregate=aggregator)['aggregate'] - else: - # need to fall back since CAST will be missing - return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) + return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if 'mysql' in connection.settings_dict['ENGINE'] and pk_field_type == 'integer': pk_field_type = 'unsigned' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name if django.VERSION < (1, 8): aggregate_field = aggregator.lookup else: aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name if django.VERSION < (1, 8): aggregate_field = aggregator.lookup else: aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params ) diff --git a/generic_aggregation_tests/tests.py b/generic_aggregation_tests/tests.py index 766428f..b857494 100644 --- a/generic_aggregation_tests/tests.py +++ b/generic_aggregation_tests/tests.py @@ -1,202 +1,215 @@ import datetime from django.conf import settings from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate as _generic_annotate, generic_aggregate as _generic_aggregate, generic_filter as _generic_filter from generic_aggregation.utils import fallback_generic_annotate, fallback_generic_aggregate, fallback_generic_filter from generic_aggregation_tests.models import ( Food, Rating, CharFieldGFK ) class SimpleTest(TestCase): + PAST_DATE = datetime.datetime(2010, 1, 1) + def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') self.peach = Food.objects.create(name='peach') - dt = datetime.datetime(2010, 1, 1) - Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) - Rating.objects.create(content_object=self.apple, rating=1, created=dt) - Rating.objects.create(content_object=self.apple, rating=3, created=dt) + Rating.objects.create(content_object=self.apple, rating=1, + created=self.PAST_DATE) + Rating.objects.create(content_object=self.apple, rating=3, + created=self.PAST_DATE) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) - Rating.objects.create(content_object=self.orange, rating=8, created=dt) + Rating.objects.create(content_object=self.orange, rating=8, + created=self.PAST_DATE) def generic_annotate(self, *args, **kwargs): return _generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return _generic_aggregate(*args, **kwargs) def generic_filter(self, *args, **kwargs): return _generic_filter(*args, **kwargs) def test_annotation(self): annotated_qs = self.generic_annotate( Food.objects.all(), Rating.objects.all(), models.Count('ratings__rating')).order_by('-score') self.assertEqual(annotated_qs.count(), 3) food_a, food_b, food_c = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_c.score, 0) self.assertEqual(food_c.name, 'peach') annotated_qs = self.generic_annotate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 3) if settings.NULLS_ASC_SORT_FIRST: food_b, food_a, food_c = annotated_qs.order_by('-score') else: food_c, food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_c.score, None) self.assertEqual(food_c.name, 'peach') annotated_qs = self.generic_annotate(Food, Rating, models.Avg('ratings__rating')) self.assertEqual(annotated_qs.count(), 3) if settings.NULLS_ASC_SORT_FIRST: food_b, food_a, food_c = annotated_qs.order_by('-score') else: food_c, food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_c.score, None) self.assertEqual(food_c.name, 'peach') def test_aggregation(self): # number of ratings on any food aggregated = self.generic_aggregate(Food, Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = self.generic_aggregate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 3) # avg for apple aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 3) # avg for orange aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) annotated_qs = self.generic_annotate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 3) if settings.NULLS_ASC_SORT_FIRST: food_a, food_b, food_c = annotated_qs.order_by('-score') else: food_c, food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_c.score, None) self.assertEqual(food_c.name, 'peach') + persimmon = Food.objects.create(name='persimmon') + + Rating.objects.create(content_object=persimmon, rating=1, + created=self.PAST_DATE) + + self.assertEqual(annotated_qs.count(), 4) + self.assertEqual( + {'apple': 8, 'orange': 7, 'peach': None, 'persimmon': None}, + {food.name: food.score for food in annotated_qs}) + def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(aggregated, 15) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) annotated_qs = self.generic_annotate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(annotated_qs.count(), 3) food_a, food_b, food_c = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_c.score, 0) self.assertEqual(food_c.name, 'peach') aggregated = self.generic_aggregate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): annotated_qs = self.generic_annotate(Food, Rating, models.Count('ratings__rating'), alias='count') food_a, food_b, food_c = annotated_qs.order_by('-count') self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.count, 3) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_c.count, 0) self.assertEqual(food_c.name, 'peach') def test_filter(self): ratings = self.generic_filter(Rating.objects.all(), Food.objects.filter(name='orange')) self.assertEqual(len(ratings), 3) for obj in ratings: self.assertEqual(obj.content_object.name, 'orange') def test_filter_cast(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) qs = self.generic_filter(CharFieldGFK.objects.all(), Food.objects.filter(name='apple')) self.assertEqual(len(qs), 2) for obj in qs: self.assertEqual(obj.content_object.name, 'apple') class FallbackTestCase(SimpleTest): def generic_annotate(self, *args, **kwargs): return fallback_generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return fallback_generic_aggregate(*args, **kwargs) def generic_filter(self, *args, **kwargs): return fallback_generic_filter(*args, **kwargs)
coleifer/django-generic-aggregation
5f7618a72c5dc307254b1b71556ad90903fc963e
Add comment.
diff --git a/settings_migrations.py b/settings_migrations.py index 2498517..16b43d8 100644 --- a/settings_migrations.py +++ b/settings_migrations.py @@ -1,20 +1,22 @@ +# Use this settings file to update migrations if the test app models change. + DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '', } } INSTALLED_APPS = [ 'django.contrib.contenttypes', 'generic_aggregation_tests', ] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ) SECRET_KEY = 'secret'
coleifer/django-generic-aggregation
bbb073e27630a0e5dec7b8b9c54730dfa5b956de
Add history and bump version.
diff --git a/History.md b/History.md new file mode 100644 index 0000000..f598432 --- /dev/null +++ b/History.md @@ -0,0 +1,7 @@ +0.4.0 / 2016-01-21 +================== + + * Drop support for Django 1.4, 1.5, and 1.6. + * Add support for Django 1.8 and 1.9. + * Fix mising row bug in ORM-based annotate. + * Fix default (no matching row) values in annotate. diff --git a/docs/conf.py b/docs/conf.py index 9d268dc..b4c9a61 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,242 +1,242 @@ # -*- coding: utf-8 -*- # # django-generic-aggregation documentation build configuration file, created by # sphinx-quickstart on Wed May 2 16:49:11 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'django-generic-aggregation' copyright = u'2012, charles leifer' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '0.3.2' +version = '0.4.0' # The full version, including alpha/beta/rc tags. -release = '0.3.2' +release = '0.4.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'django-generic-aggregationdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'django-generic-aggregation.tex', u'django-generic-aggregation Documentation', u'charles leifer', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'django-generic-aggregation', u'django-generic-aggregation Documentation', [u'charles leifer'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'django-generic-aggregation', u'django-generic-aggregation Documentation', u'charles leifer', 'django-generic-aggregation', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' diff --git a/setup.py b/setup.py index f177b8b..3c6005c 100644 --- a/setup.py +++ b/setup.py @@ -1,33 +1,33 @@ import os from setuptools import setup, find_packages f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() -VERSION = (0, 3, 2) +VERSION = (0, 4, 0) setup( name='django-generic-aggregation', version=".".join(map(str, VERSION)), description='annotate() and aggregate() for generically related data', long_description=readme, author='Charles Leifer', author_email='[email protected]', url='http://github.com/coleifer/django-generic-aggregation/', packages=find_packages(), package_data = { 'generic_aggregation': [ ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], test_suite='runtests.runtests', )
coleifer/django-generic-aggregation
757eee96cae5f5e5485ecca7dceba7ada459a6be
Add space.
diff --git a/docs/index.rst b/docs/index.rst index d3a584c..bd0816e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,195 +1,195 @@ .. django-generic-aggregation documentation master file, created by sphinx-quickstart on Wed May 2 16:49:11 2012. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. ========================== django-generic-aggregation ========================== annotate() and aggregate() for generically-related data. also a handy function for filtering GFK-model querysets. .. note:: Use django's `GenericRelation <https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations>`_ where possible, as this can make the queries generated more efficient by using a JOIN rather than a subquery. installation ------------ :: # install from pypi pip install django-generic-aggregation # or install via git pip install -e git+git://github.com/coleifer/django-generic-aggregation.git#egg=generic_aggregation examples -------- The examples below assume the following simple models: .. code-block:: python class Rating(models.Model): rating = models.IntegerField() object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') class Food(models.Model): name = models.CharField(max_length=50) - ratings =GenericRelation(Rating) # reverse generic relation + ratings = GenericRelation(Rating) # reverse generic relation You want to figure out which items are highest rated (:py:func:`~generic_aggregation.generic_annotate`) .. code-block:: python from django.db.models import Avg food_qs = Food.objects.filter(name__startswith='a') generic_annotate(food_qs, Rating, Avg('ratings__rating')) # you can mix and match queryset / model generic_annotate(food_qs, Rating.objects.all(), Avg('ratings__rating')) You want the average rating for all foods that start with 'a' (:py:func:`~generic_aggregation.generic_aggregate`) .. code-block:: python food_qs = Food.objects.filter(name__startswith='a') generic_aggregate(food_qs, Rating, Avg('ratings__rating')) You want to only display ratings for foods that start with 'a' (:py:func:`~generic_aggregation.generic_filter`) food_qs = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), food_qs) important detail ---------------- As you may have noted in the above examples (at least those using annotate and aggregate), the aggregate we pass in is prefixed with ``ratings__``. The double-underscore prefix refers to the ``ratings`` attribute of the Food model, which is a ``django.contrib.contenttypes.fields.GenericRelation`` instance. We are querying *across* that relation to the field on the Ratings model that we are interested in. When possible, use a GenericRelation and construct your queries in this manner. If you do not have a GenericRelation on the model being queried, it will use a "fallback" method that will return the correct results, though queried in a slightly different manner (a subquery will be used as opposed to a left outer join). If for some reason the Generic Foreign Key's "object_id" field is of a different type than the Primary Key of the related model -- which is probably the case if you're using django.contrib.comments, as it uses a TextField -- a ``CAST`` expression is required by some RDBMS'. Django will not put it there for you, so again, the code will use the "fallback" methods in this case, which add the necessary ``CAST``. `View the code <https://github.com/coleifer/django-generic-aggregation/>`_ for the nitty-gritty details. api --- .. py:module:: generic_aggregation .. py:function:: generic_annotate(qs_model, generic_qs_model, aggregator[, gfk_field=None[, alias='score']]) Find blog entries with the most comments: .. code-block:: python qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: .. code-block:: python generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation :rtype: a queryset containing annotate rows .. py:function:: generic_aggregate(qs_model, generic_qs_model, aggregator[, gfk_field=None]) Find total number of comments on blog entries: .. code-block:: python generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': .. code-block:: python a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :rtype: a scalar value indicating the result of the aggregation .. py:function:: generic_filter(generic_qs_model, filter_qs_model[, gfk_field=None]) Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk :rtype: a filtered queryset Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
coleifer/django-generic-aggregation
e6f2288079661c0f89e2abbdb224efbccd108e0a
Move test app outside of package for Django 1.9.
diff --git a/generic_aggregation/generic_aggregation_tests/__init__.py b/generic_aggregation_tests/__init__.py similarity index 100% rename from generic_aggregation/generic_aggregation_tests/__init__.py rename to generic_aggregation_tests/__init__.py diff --git a/generic_aggregation/generic_aggregation_tests/migrations/0001_initial.py b/generic_aggregation_tests/migrations/0001_initial.py similarity index 100% rename from generic_aggregation/generic_aggregation_tests/migrations/0001_initial.py rename to generic_aggregation_tests/migrations/0001_initial.py diff --git a/generic_aggregation/generic_aggregation_tests/migrations/__init__.py b/generic_aggregation_tests/migrations/__init__.py similarity index 100% rename from generic_aggregation/generic_aggregation_tests/migrations/__init__.py rename to generic_aggregation_tests/migrations/__init__.py diff --git a/generic_aggregation/generic_aggregation_tests/models.py b/generic_aggregation_tests/models.py similarity index 100% rename from generic_aggregation/generic_aggregation_tests/models.py rename to generic_aggregation_tests/models.py diff --git a/generic_aggregation/generic_aggregation_tests/tests.py b/generic_aggregation_tests/tests.py similarity index 99% rename from generic_aggregation/generic_aggregation_tests/tests.py rename to generic_aggregation_tests/tests.py index 927a59c..766428f 100644 --- a/generic_aggregation/generic_aggregation_tests/tests.py +++ b/generic_aggregation_tests/tests.py @@ -1,202 +1,202 @@ import datetime from django.conf import settings from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate as _generic_annotate, generic_aggregate as _generic_aggregate, generic_filter as _generic_filter from generic_aggregation.utils import fallback_generic_annotate, fallback_generic_aggregate, fallback_generic_filter -from generic_aggregation.generic_aggregation_tests.models import ( +from generic_aggregation_tests.models import ( Food, Rating, CharFieldGFK ) class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') self.peach = Food.objects.create(name='peach') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def generic_annotate(self, *args, **kwargs): return _generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return _generic_aggregate(*args, **kwargs) def generic_filter(self, *args, **kwargs): return _generic_filter(*args, **kwargs) def test_annotation(self): annotated_qs = self.generic_annotate( Food.objects.all(), Rating.objects.all(), models.Count('ratings__rating')).order_by('-score') self.assertEqual(annotated_qs.count(), 3) food_a, food_b, food_c = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_c.score, 0) self.assertEqual(food_c.name, 'peach') annotated_qs = self.generic_annotate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 3) if settings.NULLS_ASC_SORT_FIRST: food_b, food_a, food_c = annotated_qs.order_by('-score') else: food_c, food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_c.score, None) self.assertEqual(food_c.name, 'peach') annotated_qs = self.generic_annotate(Food, Rating, models.Avg('ratings__rating')) self.assertEqual(annotated_qs.count(), 3) if settings.NULLS_ASC_SORT_FIRST: food_b, food_a, food_c = annotated_qs.order_by('-score') else: food_c, food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_c.score, None) self.assertEqual(food_c.name, 'peach') def test_aggregation(self): # number of ratings on any food aggregated = self.generic_aggregate(Food, Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = self.generic_aggregate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 3) # avg for apple aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 3) # avg for orange aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) annotated_qs = self.generic_annotate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 3) if settings.NULLS_ASC_SORT_FIRST: food_a, food_b, food_c = annotated_qs.order_by('-score') else: food_c, food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_c.score, None) self.assertEqual(food_c.name, 'peach') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(aggregated, 15) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) annotated_qs = self.generic_annotate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(annotated_qs.count(), 3) food_a, food_b, food_c = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_c.score, 0) self.assertEqual(food_c.name, 'peach') aggregated = self.generic_aggregate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): annotated_qs = self.generic_annotate(Food, Rating, models.Count('ratings__rating'), alias='count') food_a, food_b, food_c = annotated_qs.order_by('-count') self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.count, 3) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_c.count, 0) self.assertEqual(food_c.name, 'peach') def test_filter(self): ratings = self.generic_filter(Rating.objects.all(), Food.objects.filter(name='orange')) self.assertEqual(len(ratings), 3) for obj in ratings: self.assertEqual(obj.content_object.name, 'orange') def test_filter_cast(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) qs = self.generic_filter(CharFieldGFK.objects.all(), Food.objects.filter(name='apple')) self.assertEqual(len(qs), 2) for obj in qs: self.assertEqual(obj.content_object.name, 'apple') class FallbackTestCase(SimpleTest): def generic_annotate(self, *args, **kwargs): return fallback_generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return fallback_generic_aggregate(*args, **kwargs) def generic_filter(self, *args, **kwargs): return fallback_generic_filter(*args, **kwargs) diff --git a/runtests.py b/runtests.py index 0b0f162..95b6cf2 100755 --- a/runtests.py +++ b/runtests.py @@ -1,65 +1,65 @@ #!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if len(sys.argv) > 1: if 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'django.db.backends.postgresql_psycopg2' nulls_asc_sort_first = False elif 'mysql' in sys.argv: sys.argv.remove('mysql') db_engine = 'django.db.backends.mysql' nulls_asc_sort_first = False db_name = 'test_main' else: db_engine = 'django.db.backends.sqlite3' db_name = '' nulls_asc_sort_first = True if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': db_engine, 'NAME': db_name, } }, INSTALLED_APPS=[ 'django.contrib.contenttypes', - 'generic_aggregation.generic_aggregation_tests', + 'generic_aggregation_tests', ], MIDDLEWARE_CLASSES=( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ), NULLS_ASC_SORT_FIRST=nulls_asc_sort_first, ) -app_to_test = 'generic_aggregation.generic_aggregation_tests' +app_to_test = 'generic_aggregation_tests' from django.test.utils import get_runner def runtests(*test_args): if not test_args: test_args = [app_to_test] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) try: from django import setup setup() except ImportError: pass failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:]) diff --git a/settings_migrations.py b/settings_migrations.py index 37f0200..2498517 100644 --- a/settings_migrations.py +++ b/settings_migrations.py @@ -1,20 +1,20 @@ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '', } } INSTALLED_APPS = [ 'django.contrib.contenttypes', - 'generic_aggregation.generic_aggregation_tests', + 'generic_aggregation_tests', ] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ) SECRET_KEY = 'secret'
coleifer/django-generic-aggregation
31a39f17c52ca453c36d00e4905005affe131980
Use newer import path for generic fields.
diff --git a/docs/index.rst b/docs/index.rst index 17ad217..d3a584c 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,195 +1,195 @@ .. django-generic-aggregation documentation master file, created by sphinx-quickstart on Wed May 2 16:49:11 2012. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. ========================== django-generic-aggregation ========================== annotate() and aggregate() for generically-related data. also a handy function for filtering GFK-model querysets. .. note:: Use django's `GenericRelation <https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations>`_ where possible, as this can make the queries generated more efficient by using a JOIN rather than a subquery. installation ------------ :: # install from pypi pip install django-generic-aggregation # or install via git pip install -e git+git://github.com/coleifer/django-generic-aggregation.git#egg=generic_aggregation examples -------- The examples below assume the following simple models: .. code-block:: python class Rating(models.Model): rating = models.IntegerField() object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') class Food(models.Model): name = models.CharField(max_length=50) - ratings = generic.GenericRelation(Rating) # reverse generic relation + ratings =GenericRelation(Rating) # reverse generic relation You want to figure out which items are highest rated (:py:func:`~generic_aggregation.generic_annotate`) .. code-block:: python from django.db.models import Avg food_qs = Food.objects.filter(name__startswith='a') generic_annotate(food_qs, Rating, Avg('ratings__rating')) # you can mix and match queryset / model generic_annotate(food_qs, Rating.objects.all(), Avg('ratings__rating')) You want the average rating for all foods that start with 'a' (:py:func:`~generic_aggregation.generic_aggregate`) .. code-block:: python food_qs = Food.objects.filter(name__startswith='a') generic_aggregate(food_qs, Rating, Avg('ratings__rating')) You want to only display ratings for foods that start with 'a' (:py:func:`~generic_aggregation.generic_filter`) food_qs = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), food_qs) important detail ---------------- As you may have noted in the above examples (at least those using annotate and aggregate), the aggregate we pass in is prefixed with ``ratings__``. The double-underscore prefix refers to the ``ratings`` attribute of the Food model, which is a -``django.contrib.contenttypes.generic.GenericRelation`` instance. We are querying +``django.contrib.contenttypes.fields.GenericRelation`` instance. We are querying *across* that relation to the field on the Ratings model that we are interested in. When possible, use a GenericRelation and construct your queries in this manner. If you do not have a GenericRelation on the model being queried, it will use a "fallback" method that will return the correct results, though queried in a slightly different manner (a subquery will be used as opposed to a left outer join). If for some reason the Generic Foreign Key's "object_id" field is of a different type than the Primary Key of the related model -- which is probably the case if you're using django.contrib.comments, as it uses a TextField -- a ``CAST`` expression is required by some RDBMS'. Django will not put it there for you, so again, the code will use the "fallback" methods in this case, which add the necessary ``CAST``. `View the code <https://github.com/coleifer/django-generic-aggregation/>`_ for the nitty-gritty details. api --- .. py:module:: generic_aggregation .. py:function:: generic_annotate(qs_model, generic_qs_model, aggregator[, gfk_field=None[, alias='score']]) Find blog entries with the most comments: .. code-block:: python qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: .. code-block:: python generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation :rtype: a queryset containing annotate rows .. py:function:: generic_aggregate(qs_model, generic_qs_model, aggregator[, gfk_field=None]) Find total number of comments on blog entries: .. code-block:: python generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': .. code-block:: python a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :rtype: a scalar value indicating the result of the aggregation .. py:function:: generic_filter(generic_qs_model, filter_qs_model[, gfk_field=None]) Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk :rtype: a filtered queryset Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` diff --git a/generic_aggregation/generic_aggregation_tests/models.py b/generic_aggregation/generic_aggregation_tests/models.py index 35c0d81..6a25943 100644 --- a/generic_aggregation/generic_aggregation_tests/models.py +++ b/generic_aggregation/generic_aggregation_tests/models.py @@ -1,33 +1,33 @@ import datetime -from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation +from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Rating(models.Model): rating = models.IntegerField() created = models.DateTimeField(default=datetime.datetime.now) object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') def __unicode__(self): return '%s rated %s' % (self.content_object, self.rating) class CharFieldGFK(models.Model): name = models.CharField(max_length=255) object_id = models.TextField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') class Food(models.Model): name = models.CharField(max_length=100) ratings = GenericRelation(Rating) char_gfk = GenericRelation(CharFieldGFK) def __unicode__(self): return self.name diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 553bee5..640807d 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,362 +1,362 @@ """ Django does not properly set up casts """ import django -from django.contrib.contenttypes.generic import GenericForeignKey +from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection from django.db.models import Q from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) if django.VERSION < (1, 8): rel_name = aggregator.lookup.split('__', 1)[0] else: rel_name = aggregator.default_alias.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter( Q(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) | Q(**{ '%s__%s__isnull' % (rel_name, gfk_field.ct_field): True, }) ) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if 'mysql' in connection.settings_dict['ENGINE'] and pk_field_type == 'integer': pk_field_type = 'unsigned' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name if django.VERSION < (1, 8): aggregate_field = aggregator.lookup else: aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name if django.VERSION < (1, 8): aggregate_field = aggregator.lookup else: aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params )
coleifer/django-generic-aggregation
b757c368f6f67d32ba759a7953829240a3974b2e
Fix postgres test for Django 1.8 by giving test app migrations.
diff --git a/generic_aggregation/generic_aggregation_tests/migrations/0001_initial.py b/generic_aggregation/generic_aggregation_tests/migrations/0001_initial.py new file mode 100644 index 0000000..1747311 --- /dev/null +++ b/generic_aggregation/generic_aggregation_tests/migrations/0001_initial.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('contenttypes', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='CharFieldGFK', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('name', models.CharField(max_length=255)), + ('object_id', models.TextField()), + ('content_type', models.ForeignKey(to='contenttypes.ContentType')), + ], + options={ + }, + bases=(models.Model,), + ), + migrations.CreateModel( + name='Food', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('name', models.CharField(max_length=100)), + ], + options={ + }, + bases=(models.Model,), + ), + migrations.CreateModel( + name='Rating', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('rating', models.IntegerField()), + ('created', models.DateTimeField(default=datetime.datetime.now)), + ('object_id', models.IntegerField()), + ('content_type', models.ForeignKey(to='contenttypes.ContentType')), + ], + options={ + }, + bases=(models.Model,), + ), + ] diff --git a/generic_aggregation/generic_aggregation_tests/migrations/__init__.py b/generic_aggregation/generic_aggregation_tests/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/settings_migrations.py b/settings_migrations.py new file mode 100644 index 0000000..37f0200 --- /dev/null +++ b/settings_migrations.py @@ -0,0 +1,20 @@ +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': '', + } +} + +INSTALLED_APPS = [ + 'django.contrib.contenttypes', + 'generic_aggregation.generic_aggregation_tests', +] + +MIDDLEWARE_CLASSES = ( + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.middleware.locale.LocaleMiddleware', + 'django.middleware.common.CommonMiddleware', +) + +SECRET_KEY = 'secret'
coleifer/django-generic-aggregation
f05dd93d894c369680eafef58ff50ffa58265432
Fix annotation bugs from issue 4.
diff --git a/generic_aggregation/generic_aggregation_tests/tests.py b/generic_aggregation/generic_aggregation_tests/tests.py index 8f46321..927a59c 100644 --- a/generic_aggregation/generic_aggregation_tests/tests.py +++ b/generic_aggregation/generic_aggregation_tests/tests.py @@ -1,177 +1,202 @@ import datetime -from django.contrib.contenttypes.models import ContentType +from django.conf import settings from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate as _generic_annotate, generic_aggregate as _generic_aggregate, generic_filter as _generic_filter from generic_aggregation.utils import fallback_generic_annotate, fallback_generic_aggregate, fallback_generic_filter from generic_aggregation.generic_aggregation_tests.models import ( Food, Rating, CharFieldGFK ) class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') self.peach = Food.objects.create(name='peach') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def generic_annotate(self, *args, **kwargs): return _generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return _generic_aggregate(*args, **kwargs) def generic_filter(self, *args, **kwargs): return _generic_filter(*args, **kwargs) def test_annotation(self): annotated_qs = self.generic_annotate( Food.objects.all(), Rating.objects.all(), models.Count('ratings__rating')).order_by('-score') - self.assertEqual(annotated_qs.count(), 2) + self.assertEqual(annotated_qs.count(), 3) - food_a, food_b = annotated_qs + food_a, food_b, food_c = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') + self.assertEqual(food_c.score, 0) + self.assertEqual(food_c.name, 'peach') + annotated_qs = self.generic_annotate(Food.objects.all(), Rating, models.Sum('ratings__rating')) - self.assertEqual(annotated_qs.count(), 2) + self.assertEqual(annotated_qs.count(), 3) - food_b, food_a = annotated_qs.order_by('-score') + if settings.NULLS_ASC_SORT_FIRST: + food_b, food_a, food_c = annotated_qs.order_by('-score') + else: + food_c, food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') + self.assertEqual(food_c.score, None) + self.assertEqual(food_c.name, 'peach') + annotated_qs = self.generic_annotate(Food, Rating, models.Avg('ratings__rating')) - self.assertEqual(annotated_qs.count(), 2) + self.assertEqual(annotated_qs.count(), 3) - food_b, food_a = annotated_qs.order_by('-score') + if settings.NULLS_ASC_SORT_FIRST: + food_b, food_a, food_c = annotated_qs.order_by('-score') + else: + food_c, food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') + self.assertEqual(food_c.score, None) + self.assertEqual(food_c.name, 'peach') + def test_aggregation(self): # number of ratings on any food aggregated = self.generic_aggregate(Food, Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = self.generic_aggregate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 3) # avg for apple aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 3) # avg for orange aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) annotated_qs = self.generic_annotate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) - self.assertEqual(annotated_qs.count(), 2) + self.assertEqual(annotated_qs.count(), 3) - food_a, food_b = annotated_qs.order_by('-score') + if settings.NULLS_ASC_SORT_FIRST: + food_a, food_b, food_c = annotated_qs.order_by('-score') + else: + food_c, food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') + self.assertEqual(food_c.score, None) + self.assertEqual(food_c.name, 'peach') + def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(aggregated, 15) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) annotated_qs = self.generic_annotate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(annotated_qs.count(), 3) food_a, food_b, food_c = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_c.score, 0) self.assertEqual(food_c.name, 'peach') aggregated = self.generic_aggregate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): annotated_qs = self.generic_annotate(Food, Rating, models.Count('ratings__rating'), alias='count') - food_a, food_b = annotated_qs.order_by('-count') + food_a, food_b, food_c = annotated_qs.order_by('-count') self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') + self.assertEqual(food_b.count, 3) + self.assertEqual(food_b.name, 'orange') + self.assertEqual(food_c.count, 0) + self.assertEqual(food_c.name, 'peach') def test_filter(self): ratings = self.generic_filter(Rating.objects.all(), Food.objects.filter(name='orange')) self.assertEqual(len(ratings), 3) for obj in ratings: self.assertEqual(obj.content_object.name, 'orange') def test_filter_cast(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) qs = self.generic_filter(CharFieldGFK.objects.all(), Food.objects.filter(name='apple')) self.assertEqual(len(qs), 2) for obj in qs: self.assertEqual(obj.content_object.name, 'apple') class FallbackTestCase(SimpleTest): - def generic_aggregate(self, *args, **kwargs): + def generic_annotate(self, *args, **kwargs): return fallback_generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return fallback_generic_aggregate(*args, **kwargs) def generic_filter(self, *args, **kwargs): return fallback_generic_filter(*args, **kwargs) diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 8b355b7..553bee5 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,356 +1,362 @@ """ Django does not properly set up casts """ import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection +from django.db.models import Q from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) if django.VERSION < (1, 8): rel_name = aggregator.lookup.split('__', 1)[0] else: rel_name = aggregator.default_alias.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False - qs = qs.filter(**{ - '%s__%s' % (rel_name, gfk_field.ct_field): content_type, - '%s__pk__in' % (rel_name): generic_qs.values('pk'), - }) + qs = qs.filter( + Q(**{ + '%s__%s' % (rel_name, gfk_field.ct_field): content_type, + '%s__pk__in' % (rel_name): generic_qs.values('pk'), + }) + | Q(**{ + '%s__%s__isnull' % (rel_name, gfk_field.ct_field): True, + }) + ) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if 'mysql' in connection.settings_dict['ENGINE'] and pk_field_type == 'integer': pk_field_type = 'unsigned' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name if django.VERSION < (1, 8): aggregate_field = aggregator.lookup else: aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ - SELECT COALESCE(%s(%s), 0) AS aggregate_score + SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name if django.VERSION < (1, 8): aggregate_field = aggregator.lookup else: aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params ) diff --git a/runtests.py b/runtests.py index ce0f1c9..0b0f162 100755 --- a/runtests.py +++ b/runtests.py @@ -1,61 +1,65 @@ #!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if len(sys.argv) > 1: if 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'django.db.backends.postgresql_psycopg2' + nulls_asc_sort_first = False elif 'mysql' in sys.argv: sys.argv.remove('mysql') db_engine = 'django.db.backends.mysql' + nulls_asc_sort_first = False db_name = 'test_main' else: db_engine = 'django.db.backends.sqlite3' db_name = '' + nulls_asc_sort_first = True if not settings.configured: settings.configure( - DATABASES = { + DATABASES={ 'default': { 'ENGINE': db_engine, 'NAME': db_name, } }, - INSTALLED_APPS = [ + INSTALLED_APPS=[ 'django.contrib.contenttypes', 'generic_aggregation.generic_aggregation_tests', ], - MIDDLEWARE_CLASSES = ( + MIDDLEWARE_CLASSES=( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ), + NULLS_ASC_SORT_FIRST=nulls_asc_sort_first, ) app_to_test = 'generic_aggregation.generic_aggregation_tests' from django.test.utils import get_runner def runtests(*test_args): if not test_args: test_args = [app_to_test] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) try: from django import setup setup() except ImportError: pass failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
coleifer/django-generic-aggregation
50a3c9c09a67735f66b471ba0e0ba8b53552efe8
Fix utils for Django 1.8.
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 6e4e574..8b355b7 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,343 +1,356 @@ """ Django does not properly set up casts """ +import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) - rel_name = aggregator.lookup.split('__', 1)[0] - + + if django.VERSION < (1, 8): + rel_name = aggregator.lookup.split('__', 1)[0] + else: + rel_name = aggregator.default_alias.split('__', 1)[0] + try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if 'mysql' in connection.settings_dict['ENGINE'] and pk_field_type == 'integer': pk_field_type = 'unsigned' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name - aggregate_field = aggregator.lookup - + + if django.VERSION < (1, 8): + aggregate_field = aggregator.lookup + else: + aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] + # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT COALESCE(%s(%s), 0) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name - aggregate_field = aggregator.lookup + + if django.VERSION < (1, 8): + aggregate_field = aggregator.lookup + else: + aggregate_field = aggregator.default_alias.rsplit('__', 1)[0] # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params )
coleifer/django-generic-aggregation
1dc7916253769fe9ba7eddb86de3064eefe7eb57
Remove pre-1.7 code.
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 2fadc13..6e4e574 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,353 +1,343 @@ """ Django does not properly set up casts """ -import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType -from django.db import connection, models +from django.db import connection from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): - if django.VERSION < (1, 4): - raw_type = f.db_type() - else: - raw_type = f.db_type(connection) + raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) rel_name = aggregator.lookup.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): - if django.VERSION < (1, 2): - return query.as_sql() - else: - return query.get_compiler(connection=connection).as_sql() + return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): - if django.VERSION < (1, 2): - return query.as_nested_sql() - else: - return query.get_compiler(connection=connection).as_nested_sql() + return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if 'mysql' in connection.settings_dict['ENGINE'] and pk_field_type == 'integer': pk_field_type = 'unsigned' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT COALESCE(%s(%s), 0) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params ) diff --git a/runtests.py b/runtests.py index b821dcc..ce0f1c9 100755 --- a/runtests.py +++ b/runtests.py @@ -1,65 +1,61 @@ #!/usr/bin/env python import sys -import django from os.path import dirname, abspath from django.conf import settings if len(sys.argv) > 1: if 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'django.db.backends.postgresql_psycopg2' elif 'mysql' in sys.argv: sys.argv.remove('mysql') db_engine = 'django.db.backends.mysql' db_name = 'test_main' else: db_engine = 'django.db.backends.sqlite3' db_name = '' if not settings.configured: settings.configure( DATABASES = { 'default': { 'ENGINE': db_engine, 'NAME': db_name, } }, INSTALLED_APPS = [ 'django.contrib.contenttypes', 'generic_aggregation.generic_aggregation_tests', ], MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ), ) -if django.VERSION < (1, 6): - app_to_test = 'generic_aggregation_tests' -else: - app_to_test = 'generic_aggregation.generic_aggregation_tests' +app_to_test = 'generic_aggregation.generic_aggregation_tests' from django.test.utils import get_runner def runtests(*test_args): if not test_args: test_args = [app_to_test] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) try: from django import setup setup() except ImportError: pass failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
coleifer/django-generic-aggregation
d338c376d338dbc14ff443cb38a00f10f612b63e
Add tox and coverage integration
diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..94b9b53 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,6 @@ +[run] +source = generic_aggregation +branck = True + +[report] +omit = *tests* \ No newline at end of file diff --git a/.gitignore b/.gitignore index 394e930..1399fbd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,11 @@ *.pyc build/ src/ pip-log.txt *DS_Store *~ dist/ *.egg-info/ +htmlcov +.coverage +.tox \ No newline at end of file diff --git a/runtests.py b/runtests.py index 6992d2b..b821dcc 100755 --- a/runtests.py +++ b/runtests.py @@ -1,48 +1,65 @@ #!/usr/bin/env python import sys +import django from os.path import dirname, abspath from django.conf import settings -if len(sys.argv) > 1: +if len(sys.argv) > 1: if 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'django.db.backends.postgresql_psycopg2' elif 'mysql' in sys.argv: sys.argv.remove('mysql') db_engine = 'django.db.backends.mysql' db_name = 'test_main' else: db_engine = 'django.db.backends.sqlite3' db_name = '' if not settings.configured: settings.configure( DATABASES = { 'default': { 'ENGINE': db_engine, 'NAME': db_name, } }, INSTALLED_APPS = [ 'django.contrib.contenttypes', 'generic_aggregation.generic_aggregation_tests', ], + MIDDLEWARE_CLASSES = ( + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.middleware.locale.LocaleMiddleware', + 'django.middleware.common.CommonMiddleware', + ), ) +if django.VERSION < (1, 6): + app_to_test = 'generic_aggregation_tests' +else: + app_to_test = 'generic_aggregation.generic_aggregation_tests' + from django.test.utils import get_runner def runtests(*test_args): if not test_args: - test_args = ['generic_aggregation_tests'] + test_args = [app_to_test] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) + try: + from django import setup + setup() + except ImportError: + pass failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:]) diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..f4a9b6e --- /dev/null +++ b/tox.ini @@ -0,0 +1,26 @@ +[tox] +skipsdist = false +usedevelop = true +envlist = + py27-dj{14,15,16,17}-{sqlite,postgres}, + py34-dj{15,16,17}-{sqlite,postgres} + +[testenv] +downloadcache = {toxworkdir}/_download/ +basepython = + py27: python2.7 + py34: python3.4 +deps = + coverage==3.7.1 + psycopg2 + dj14: Django==1.4.20 + dj15: Django==1.5.12 + dj16: Django==1.6.11 + dj17: Django==1.7.7 +commands = + postgres: coverage run runtests.py postgres + sqlite: coverage run runtests.py + coverage report + coverage html -d htmlcov/{envname} +setenv = + PYTHONPATH = {toxinidir}
coleifer/django-generic-aggregation
8cba5855161e5a88c27b492124803494ec311463
Version bump
diff --git a/setup.py b/setup.py index 1edcf2d..f177b8b 100644 --- a/setup.py +++ b/setup.py @@ -1,33 +1,33 @@ import os from setuptools import setup, find_packages f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() -VERSION = (0, 3, 1) +VERSION = (0, 3, 2) setup( name='django-generic-aggregation', version=".".join(map(str, VERSION)), description='annotate() and aggregate() for generically related data', long_description=readme, author='Charles Leifer', author_email='[email protected]', url='http://github.com/coleifer/django-generic-aggregation/', packages=find_packages(), package_data = { 'generic_aggregation': [ ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], test_suite='runtests.runtests', )
coleifer/django-generic-aggregation
e6fcddc0a32e5700ee23749691e74ece1a19a0d8
Fix for MySQL cast expression
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index f8889ee..2fadc13 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,351 +1,353 @@ """ Django does not properly set up casts """ import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection, models from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): if django.VERSION < (1, 4): raw_type = f.db_type() else: raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) rel_name = aggregator.lookup.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) + if 'mysql' in connection.settings_dict['ENGINE'] and pk_field_type == 'integer': + pk_field_type = 'unsigned' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT COALESCE(%s(%s), 0) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params )
coleifer/django-generic-aggregation
d8b3d38f1aa5cecfb98fc5f5db5ef7a28cedac78
Removing normalize hook
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 71ce397..f8889ee 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,352 +1,351 @@ """ Django does not properly set up casts """ import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection, models from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() -def get_field_type(f, normalize=True): +def get_field_type(f): if django.VERSION < (1, 4): raw_type = f.db_type() else: raw_type = f.db_type(connection) - if normalize and raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): + if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) rel_name = aggregator.lookup.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) - pk_field_type_raw = get_field_type(qs_model._meta.pk, False) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: # cast the gfk to the pk type - gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type_raw) + gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT COALESCE(%s(%s), 0) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params ) diff --git a/runtests.py b/runtests.py index fbbfc10..6992d2b 100755 --- a/runtests.py +++ b/runtests.py @@ -1,44 +1,48 @@ #!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings -if len(sys.argv) > 1 and 'postgres' in sys.argv: - sys.argv.remove('postgres') - db_engine = 'django.db.backends.postgresql_psycopg2' +if len(sys.argv) > 1: + if 'postgres' in sys.argv: + sys.argv.remove('postgres') + db_engine = 'django.db.backends.postgresql_psycopg2' + elif 'mysql' in sys.argv: + sys.argv.remove('mysql') + db_engine = 'django.db.backends.mysql' db_name = 'test_main' else: db_engine = 'django.db.backends.sqlite3' db_name = '' if not settings.configured: settings.configure( DATABASES = { 'default': { 'ENGINE': db_engine, 'NAME': db_name, } }, INSTALLED_APPS = [ 'django.contrib.contenttypes', 'generic_aggregation.generic_aggregation_tests', ], ) from django.test.utils import get_runner def runtests(*test_args): if not test_args: test_args = ['generic_aggregation_tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
coleifer/django-generic-aggregation
d746e765c16bfd98669fd5d40edb72806475f5fa
Django 1.4 compat runtests
diff --git a/runtests.py b/runtests.py index 2cfa802..fbbfc10 100755 --- a/runtests.py +++ b/runtests.py @@ -1,38 +1,44 @@ #!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if len(sys.argv) > 1 and 'postgres' in sys.argv: sys.argv.remove('postgres') - db_engine = 'postgresql_psycopg2' + db_engine = 'django.db.backends.postgresql_psycopg2' db_name = 'test_main' else: - db_engine = 'sqlite3' + db_engine = 'django.db.backends.sqlite3' db_name = '' if not settings.configured: settings.configure( - DATABASE_ENGINE = db_engine, - DATABASE_NAME = db_name, + DATABASES = { + 'default': { + 'ENGINE': db_engine, + 'NAME': db_name, + } + }, INSTALLED_APPS = [ 'django.contrib.contenttypes', 'generic_aggregation.generic_aggregation_tests', ], ) -from django.test.simple import run_tests +from django.test.utils import get_runner def runtests(*test_args): if not test_args: test_args = ['generic_aggregation_tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) - failures = run_tests(test_args, verbosity=1, interactive=True) + TestRunner = get_runner(settings) + test_runner = TestRunner(verbosity=1, interactive=True) + failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
coleifer/django-generic-aggregation
d3d52f031782732ab3e043990e0460cf6cd34b9a
Adding way to get field db type w/o normalizing
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index f8889ee..71ce397 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,351 +1,352 @@ """ Django does not properly set up casts """ import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection, models from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() -def get_field_type(f): +def get_field_type(f, normalize=True): if django.VERSION < (1, 4): raw_type = f.db_type() else: raw_type = f.db_type(connection) - if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): + if normalize and raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) rel_name = aggregator.lookup.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) + pk_field_type_raw = get_field_type(qs_model._meta.pk, False) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: # cast the gfk to the pk type - gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) + gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type_raw) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT COALESCE(%s(%s), 0) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params )
coleifer/django-generic-aggregation
c76408c2c002dcab6bfc3148760ee58a19cbe05e
Cleaning up for docs
diff --git a/README.rst b/README.rst index 7bd1721..d11c57d 100644 --- a/README.rst +++ b/README.rst @@ -1,58 +1,71 @@ ========================== django-generic-aggregation ========================== annotate() and aggregate() for generically-related data. also a handy function for filtering GFK-model querysets. -the use of annotate() and aggregate() require a ``GenericRelation``. +Use django's `GenericRelation <https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations>`_ where possible, +as this can make the queries generated more efficient by using a JOIN rather +than a subquery. -Examples --------- -You want the most commented on blog entries:: +installation +------------ + +:: + + # install from pypi + pip install django-generic-aggregation + + # or install via git + pip install -e git+git://github.com/coleifer/django-generic-aggregation.git#egg=generic_aggregation - >>> from django.contrib.comments.models import Comment - >>> from django.db.models import Count - >>> from blog.models import BlogEntry - >>> from generic_aggregation import generic_annotate - >>> annotated = generic_annotate(BlogEntry.objects.all(), Comment, Count('comments__id')) +examples +-------- - >>> for entry in annotated: - ... print entry.title, entry.score +The examples below assume the following simple models: - The most popular 5 - The second best 4 - Nobody commented 0 +:: + class Rating(models.Model): + rating = models.IntegerField() + object_id = models.IntegerField() + content_type = models.ForeignKey(ContentType) + content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') + + class Food(models.Model): + name = models.CharField(max_length=50) + ratings = generic.GenericRelation(Rating) # reverse generic relation -You want to figure out which items are highest rated:: - from django.db.models import Sum, Avg +You want to figure out which items are highest rated (generic_annotate) - # assume a Food model and a generic Rating model - apple = Food.objects.create(name='apple') +:: + + from django.db.models import Avg + + food_qs = Food.objects.filter(name__startswith='a') + generic_annotate(food_qs, Rating, Avg('ratings__rating')) - # create some ratings on the food - Rating.objects.create(content_object=apple, rating=3) - Rating.objects.create(content_object=apple, rating=5) - Rating.objects.create(content_object=apple, rating=7) + # you can mix and match queryset / model + generic_annotate(food_qs, Rating.objects.all(), Avg('ratings__rating')) + +You want the average rating for all foods that start with 'a' (generic_aggregate) + +:: + + food_qs = Food.objects.filter(name__startswith='a') + generic_aggregate(food_qs, Rating, Avg('ratings__rating')) - >>> aggregate = generic_aggregate(Food, Rating, Sum('ratings__rating')) - >>> print aggregate - 15 +You want to only display ratings for foods that start with 'a' (generic_filter) - >>> aggregate = generic_aggregate(Food, Rating.objects.all(), Avg('ratings__rating')) - >>> print aggregate - 5 + food_qs = Food.objects.filter(name__startswith='a') + generic_filter(Rating.objects.all(), food_qs) -You want to only display ratings for comments made on a given site: - >>> from django.contrib.comments.models import Comment - >>> from generic_aggregation import generic_filter - >>> ratings = Rating.objects.all() # <--- grab all the ratings - >>> comments = Comment.objects.filter(site=Site.objects.get_current()) - >>> siteified_ratings = generic_filter(ratings, comments) +documentation +------------- -Check the tests - there are more examples there. Tested with postgres & sqlite +http://django-generic-aggregation.readthedocs.org/ diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..3c360c6 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make <target>' where <target> is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-generic-aggregation.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-generic-aggregation.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/django-generic-aggregation" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-generic-aggregation" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..9d268dc --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,242 @@ +# -*- coding: utf-8 -*- +# +# django-generic-aggregation documentation build configuration file, created by +# sphinx-quickstart on Wed May 2 16:49:11 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'django-generic-aggregation' +copyright = u'2012, charles leifer' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.3.2' +# The full version, including alpha/beta/rc tags. +release = '0.3.2' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'nature' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# "<project> v<release> documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a <link> tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'django-generic-aggregationdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'django-generic-aggregation.tex', u'django-generic-aggregation Documentation', + u'charles leifer', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'django-generic-aggregation', u'django-generic-aggregation Documentation', + [u'charles leifer'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'django-generic-aggregation', u'django-generic-aggregation Documentation', + u'charles leifer', 'django-generic-aggregation', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..17ad217 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,195 @@ +.. django-generic-aggregation documentation master file, created by + sphinx-quickstart on Wed May 2 16:49:11 2012. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +========================== +django-generic-aggregation +========================== + +annotate() and aggregate() for generically-related data. also a handy function +for filtering GFK-model querysets. + +.. note:: + Use django's `GenericRelation <https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations>`_ where possible, + as this can make the queries generated more efficient by using a JOIN rather + than a subquery. + + +installation +------------ + +:: + + # install from pypi + pip install django-generic-aggregation + + # or install via git + pip install -e git+git://github.com/coleifer/django-generic-aggregation.git#egg=generic_aggregation + + +examples +-------- + +The examples below assume the following simple models: + +.. code-block:: python + + class Rating(models.Model): + rating = models.IntegerField() + object_id = models.IntegerField() + content_type = models.ForeignKey(ContentType) + content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') + + class Food(models.Model): + name = models.CharField(max_length=50) + ratings = generic.GenericRelation(Rating) # reverse generic relation + + +You want to figure out which items are highest rated (:py:func:`~generic_aggregation.generic_annotate`) + +.. code-block:: python + + from django.db.models import Avg + + food_qs = Food.objects.filter(name__startswith='a') + generic_annotate(food_qs, Rating, Avg('ratings__rating')) + + # you can mix and match queryset / model + generic_annotate(food_qs, Rating.objects.all(), Avg('ratings__rating')) + +You want the average rating for all foods that start with 'a' (:py:func:`~generic_aggregation.generic_aggregate`) + +.. code-block:: python + + food_qs = Food.objects.filter(name__startswith='a') + generic_aggregate(food_qs, Rating, Avg('ratings__rating')) + +You want to only display ratings for foods that start with 'a' (:py:func:`~generic_aggregation.generic_filter`) + + food_qs = Food.objects.filter(name__startswith='a') + generic_filter(Rating.objects.all(), food_qs) + + +important detail +---------------- + +As you may have noted in the above examples (at least those using annotate and +aggregate), the aggregate we pass in is prefixed with ``ratings__``. The double-underscore +prefix refers to the ``ratings`` attribute of the Food model, which is a +``django.contrib.contenttypes.generic.GenericRelation`` instance. We are querying +*across* that relation to the field on the Ratings model that we are interested in. +When possible, use a GenericRelation and construct your queries in this manner. + +If you do not have a GenericRelation on the model being queried, it will use +a "fallback" method that will return the correct results, though queried in a slightly +different manner (a subquery will be used as opposed to a left outer join). + +If for some reason the Generic Foreign Key's "object_id" field is of a different +type than the Primary Key of the related model -- which is probably the case if you're +using django.contrib.comments, as it uses a TextField -- a ``CAST`` expression is +required by some RDBMS'. Django will not put it there for you, so again, the +code will use the "fallback" methods in this case, which add the necessary ``CAST``. + +`View the code <https://github.com/coleifer/django-generic-aggregation/>`_ for the nitty-gritty details. + + +api +--- + +.. py:module:: generic_aggregation + +.. py:function:: generic_annotate(qs_model, generic_qs_model, aggregator[, gfk_field=None[, alias='score']]) + + Find blog entries with the most comments: + + .. code-block:: python + + qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) + for entry in qs: + print entry.title, entry.score + + Find the highest rated foods: + + .. code-block:: python + + generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') + for food in qs: + print food.name, '- average rating:', food.avg + + .. note:: + In both of the above examples it is assumed that a GenericRelation exists + on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). + If a GenericRelation does *not* exist, the query will still return correct + results but the code path will be different as it will use the fallback method. + + .. warning:: + If the underlying column type differs between the qs_model's primary + key and the generic_qs_model's foreign key column, it will use the fallback + method, which can correctly CASTself. + + :param qs_model: A model or a queryset of objects you want to perform + annotation on, e.g. blog entries + :param generic_qs_model: A model or queryset containing a GFK, e.g. comments + :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') + :param gfk_field: explicitly specify the field w/the gfk + :param alias: attribute name to use for annotation + :rtype: a queryset containing annotate rows + +.. py:function:: generic_aggregate(qs_model, generic_qs_model, aggregator[, gfk_field=None]) + + Find total number of comments on blog entries: + + .. code-block:: python + + generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) + + Find the average rating for foods starting with 'a': + + .. code-block:: python + + a_foods = Food.objects.filter(name__startswith='a') + generic_aggregate(a_foods, Rating, Avg('ratings__rating')) + + .. note:: + In both of the above examples it is assumed that a GenericRelation exists + on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). + If a GenericRelation does *not* exist, the query will still return correct + results but the code path will be different as it will use the fallback method. + + .. warning:: + If the underlying column type differs between the qs_model's primary + key and the generic_qs_model's foreign key column, it will use the fallback + method, which can correctly CASTself. + + :param qs_model: A model or a queryset of objects you want to perform + annotation on, e.g. blog entries + :param generic_qs_model: A model or queryset containing a GFK, e.g. comments + :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') + :param gfk_field: explicitly specify the field w/the gfk + :rtype: a scalar value indicating the result of the aggregation + +.. py:function:: generic_filter(generic_qs_model, filter_qs_model[, gfk_field=None]) + + Only show me ratings made on foods that start with "a": + + a_foods = Food.objects.filter(name__startswith='a') + generic_filter(Rating.objects.all(), a_foods) + + Only show me comments from entries that are marked as public: + + generic_filter(Comment.objects.public(), Entry.objects.public()) + + :param generic_qs_model: A model or queryset containing a GFK, e.g. comments + :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to + :param gfk_field: explicitly specify the field w/the gfk + :rtype: a filtered queryset + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..b366f7a --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,190 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^<target^>` where ^<target^> is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-generic-aggregation.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-generic-aggregation.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +:end diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 02d0743..f8889ee 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,322 +1,351 @@ """ Django does not properly set up casts """ import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection, models from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): if django.VERSION < (1, 4): raw_type = f.db_type() else: raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) rel_name = aggregator.lookup.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ + Find blog entries with the most comments: + + qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) + for entry in qs: + print entry.title, entry.score + + Find the highest rated foods: + + generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') + for food in qs: + print food.name, '- average rating:', food.avg + + .. note:: + In both of the above examples it is assumed that a GenericRelation exists + on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). + If a GenericRelation does *not* exist, the query will still return correct + results but the code path will be different as it will use the fallback method. + + .. warning:: + If the underlying column type differs between the qs_model's primary + key and the generic_qs_model's foreign key column, it will use the fallback + method, which can correctly CASTself. + :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation - - Note: - requires presence of a GenericRelation() on the qs_model, which should - be referenced in the aggregator function - - Warning: - if the primary key field differs in type from the GFK's fk_field a CAST - is not expressed on the JOIN, so the code will fallback gracefully - - Example: - - generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ + Find total number of comments on blog entries: + + generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) + + Find the average rating for foods starting with 'a': + + a_foods = Food.objects.filter(name__startswith='a') + generic_aggregate(a_foods, Rating, Avg('ratings__rating')) + + .. note:: + In both of the above examples it is assumed that a GenericRelation exists + on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). + If a GenericRelation does *not* exist, the query will still return correct + results but the code path will be different as it will use the fallback method. + + .. warning:: + If the underlying column type differs between the qs_model's primary + key and the generic_qs_model's foreign key column, it will use the fallback + method, which can correctly CASTself. + :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk - - Note: - requires presence of a GenericRelation() on the qs_model, which should - be referenced in the aggregator function - - Warning: - if the primary key field differs in type from the GFK's fk_field a CAST - is not expressed on the JOIN, so the code will fallback gracefully - - Example: - - generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ - Filter a queryset of objects containing GFKs so that they are restricted to - only those objects that relate to items in the filter queryset + Only show me ratings made on foods that start with "a": + + a_foods = Food.objects.filter(name__startswith='a') + generic_filter(Rating.objects.all(), a_foods) + + Only show me comments from entries that are marked as public: + + generic_filter(Comment.objects.public(), Entry.objects.public()) + + :param generic_qs_model: A model or queryset containing a GFK, e.g. comments + :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to + :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT COALESCE(%s(%s), 0) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # get the contenttype of our filtered queryset, e.g. Business filter_model = filter_qs.model content_type = ContentType.objects.get_for_model(filter_model) # filter the generic queryset to only include items of the given ctype generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) # just select the primary keys in the sub-select filtered_query = filter_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(filtered_query) where = '%s IN (%s)' % ( gfk_expression(filter_model, gfk_field), inner_query, ) return generic_qs.extra( where=(where,), params=inner_query_params )
coleifer/django-generic-aggregation
2585d1b9fed7750945c80db786fd600c9b1a80bf
Adding test for fallback w/cast
diff --git a/generic_aggregation/generic_aggregation_tests/tests.py b/generic_aggregation/generic_aggregation_tests/tests.py index 073645b..89aee97 100644 --- a/generic_aggregation/generic_aggregation_tests/tests.py +++ b/generic_aggregation/generic_aggregation_tests/tests.py @@ -1,156 +1,170 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate as _generic_annotate, generic_aggregate as _generic_aggregate, generic_filter as _generic_filter from generic_aggregation.utils import fallback_generic_annotate, fallback_generic_aggregate, fallback_generic_filter from generic_aggregation.generic_aggregation_tests.models import ( Food, Rating, CharFieldGFK ) class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def generic_annotate(self, *args, **kwargs): return _generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return _generic_aggregate(*args, **kwargs) def generic_filter(self, *args, **kwargs): return _generic_filter(*args, **kwargs) def test_annotation(self): annotated_qs = self.generic_annotate(Food.objects.all(), Rating.objects.all(), models.Count('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') annotated_qs = self.generic_annotate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') annotated_qs = self.generic_annotate(Food, Rating, models.Avg('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food aggregated = self.generic_aggregate(Food, Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = self.generic_aggregate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 3) # avg for apple aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 3) # avg for orange aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) annotated_qs = self.generic_annotate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(aggregated, 15) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) annotated_qs = self.generic_annotate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') aggregated = self.generic_aggregate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): annotated_qs = self.generic_annotate(Food, Rating, models.Count('ratings__rating'), alias='count') food_a, food_b = annotated_qs.order_by('-count') self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') def test_filter(self): ratings = self.generic_filter(Rating.objects.all(), Food.objects.filter(name='orange')) self.assertEqual(len(ratings), 3) + + for obj in ratings: + self.assertEqual(obj.content_object.name, 'orange') + + def test_filter_cast(self): + a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) + a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) + o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) + + qs = self.generic_filter(CharFieldGFK.objects.all(), Food.objects.filter(name='apple')) + self.assertEqual(len(qs), 2) + + for obj in qs: + self.assertEqual(obj.content_object.name, 'apple') class FallbackTestCase(SimpleTest): def generic_aggregate(self, *args, **kwargs): return fallback_generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return fallback_generic_aggregate(*args, **kwargs) def generic_filter(self, *args, **kwargs): return fallback_generic_filter(*args, **kwargs)
coleifer/django-generic-aggregation
6ce59ed7c23a6df1d7c40e8206d31d9565ec9601
Bugfix
diff --git a/setup.py b/setup.py index 4f4ec29..1edcf2d 100644 --- a/setup.py +++ b/setup.py @@ -1,33 +1,33 @@ import os from setuptools import setup, find_packages f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() -VERSION = (0, 3, 0) +VERSION = (0, 3, 1) setup( name='django-generic-aggregation', version=".".join(map(str, VERSION)), description='annotate() and aggregate() for generically related data', long_description=readme, author='Charles Leifer', author_email='[email protected]', url='http://github.com/coleifer/django-generic-aggregation/', packages=find_packages(), package_data = { 'generic_aggregation': [ ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], test_suite='runtests.runtests', )
coleifer/django-generic-aggregation
4864b2abe7e51fddf6c0810866d6290cb1e50bec
Adding a fallback filter method because django doesn't handle casting properly on IN lookups either
diff --git a/generic_aggregation/generic_aggregation_tests/tests.py b/generic_aggregation/generic_aggregation_tests/tests.py index 37cb5d9..073645b 100644 --- a/generic_aggregation/generic_aggregation_tests/tests.py +++ b/generic_aggregation/generic_aggregation_tests/tests.py @@ -1,150 +1,156 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase -from generic_aggregation import generic_annotate as _generic_annotate, generic_aggregate as _generic_aggregate, generic_filter -from generic_aggregation.utils import fallback_generic_annotate, fallback_generic_aggregate +from generic_aggregation import generic_annotate as _generic_annotate, generic_aggregate as _generic_aggregate, generic_filter as _generic_filter +from generic_aggregation.utils import fallback_generic_annotate, fallback_generic_aggregate, fallback_generic_filter from generic_aggregation.generic_aggregation_tests.models import ( Food, Rating, CharFieldGFK ) class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def generic_annotate(self, *args, **kwargs): return _generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return _generic_aggregate(*args, **kwargs) + + def generic_filter(self, *args, **kwargs): + return _generic_filter(*args, **kwargs) def test_annotation(self): annotated_qs = self.generic_annotate(Food.objects.all(), Rating.objects.all(), models.Count('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') annotated_qs = self.generic_annotate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') annotated_qs = self.generic_annotate(Food, Rating, models.Avg('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food aggregated = self.generic_aggregate(Food, Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = self.generic_aggregate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 3) # avg for apple aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 3) # avg for orange aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) annotated_qs = self.generic_annotate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(aggregated, 15) aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) annotated_qs = self.generic_annotate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') aggregated = self.generic_aggregate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): annotated_qs = self.generic_annotate(Food, Rating, models.Count('ratings__rating'), alias='count') food_a, food_b = annotated_qs.order_by('-count') self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') def test_filter(self): - ratings = generic_filter(Rating.objects.all(), Food.objects.filter(name='orange')) + ratings = self.generic_filter(Rating.objects.all(), Food.objects.filter(name='orange')) self.assertEqual(len(ratings), 3) class FallbackTestCase(SimpleTest): def generic_aggregate(self, *args, **kwargs): return fallback_generic_annotate(*args, **kwargs) def generic_aggregate(self, *args, **kwargs): return fallback_generic_aggregate(*args, **kwargs) + + def generic_filter(self, *args, **kwargs): + return fallback_generic_filter(*args, **kwargs) diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 3e277e1..02d0743 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,289 +1,322 @@ """ Django does not properly set up casts """ import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection, models from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): if django.VERSION < (1, 4): raw_type = f.db_type() else: raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) rel_name = aggregator.lookup.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation Note: requires presence of a GenericRelation() on the qs_model, which should be referenced in the aggregator function Warning: if the primary key field differs in type from the GFK's fk_field a CAST is not expressed on the JOIN, so the code will fallback gracefully Example: generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk Note: requires presence of a GenericRelation() on the qs_model, which should be referenced in the aggregator function Warning: if the primary key field differs in type from the GFK's fk_field a CAST is not expressed on the JOIN, so the code will fallback gracefully Example: generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Filter a queryset of objects containing GFKs so that they are restricted to only those objects that relate to items in the filter queryset """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) + pk_field_type = get_field_type(filter_qs.model._meta.pk) + gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) + if pk_field_type != gfk_field_type: + return fallback_generic_filter(generic_qs, filter_qs, gfk_field) + return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ SELECT COALESCE(%s(%s), 0) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] + +def fallback_generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): + generic_qs = normalize_qs_model(generic_qs_model) + filter_qs = normalize_qs_model(filter_qs_model) + + if gfk_field is None: + gfk_field = get_gfk_field(generic_qs.model) + + # get the contenttype of our filtered queryset, e.g. Business + filter_model = filter_qs.model + content_type = ContentType.objects.get_for_model(filter_model) + + # filter the generic queryset to only include items of the given ctype + generic_qs = generic_qs.filter(**{gfk_field.ct_field: content_type}) + + # just select the primary keys in the sub-select + filtered_query = filter_qs.values_list('pk').query + inner_query, inner_query_params = query_as_sql(filtered_query) + + where = '%s IN (%s)' % ( + gfk_expression(filter_model, gfk_field), + inner_query, + ) + + return generic_qs.extra( + where=(where,), + params=inner_query_params + )
coleifer/django-generic-aggregation
53c073c218982d0ff3ad6f7c24dcb7b0639c771f
Coalesce since django offers zero by way of sorting nulls last
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index c8e34ec..3e277e1 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,289 +1,289 @@ """ Django does not properly set up casts """ import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection, models from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() def get_field_type(f): if django.VERSION < (1, 4): raw_type = f.db_type() else: raw_type = f.db_type(connection) if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): raw_type = 'integer' return raw_type def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) model = qs.model generic_model = generic_qs.model if gfk_field is None: gfk_field = get_gfk_field(generic_model) content_type = ContentType.objects.get_for_model(model) rel_name = aggregator.lookup.split('__', 1)[0] try: generic_rel_descriptor = getattr(model, rel_name) except AttributeError: # missing the generic relation, so do fallback query return False rel_model = generic_rel_descriptor.field.rel.to if rel_model != generic_model: raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( generic_model, rel_name, rel_model, )) pk_field_type = get_field_type(model._meta.pk) gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return False qs = qs.filter(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation Note: requires presence of a GenericRelation() on the qs_model, which should be referenced in the aggregator function Warning: if the primary key field differs in type from the GFK's fk_field a CAST is not expressed on the JOIN, so the code will fallback gracefully Example: generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.annotate(**{alias: aggregator}) else: # need to fall back since CAST will be missing return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk Note: requires presence of a GenericRelation() on the qs_model, which should be referenced in the aggregator function Warning: if the primary key field differs in type from the GFK's fk_field a CAST is not expressed on the JOIN, so the code will fallback gracefully Example: generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) if prepared_query is not False: return prepared_query.aggregate(aggregate=aggregator)['aggregate'] else: # need to fall back since CAST will be missing return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Filter a queryset of objects containing GFKs so that they are restricted to only those objects that relate to items in the filter queryset """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) ############################################################################### # fallback methods def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = get_field_type(qs_model._meta.pk) gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), qn(qs.model._meta.db_table), # the table and pk from the main qn(qs.model._meta.pk.name) # part of the query ) sql_template = """ - SELECT %s(%s) AS aggregate_score + SELECT COALESCE(%s(%s), 0) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_qs.model._meta.db_table), qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] return qs.extra( select={alias: extra}, select_params=inner_query_params, ) def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) content_type = ContentType.objects.get_for_model(qs.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # since the aggregate may contain a generic relation, strip it if '__' in aggregate_field: _, aggregate_field = aggregate_field.rsplit('__', 1) if gfk_field is None: gfk_field = get_gfk_field(generic_qs.model) qs = qs.values_list('pk') # just the pks query, query_params = query_as_nested_sql(qs.query) # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(qs.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_qs.query.where.children: generic_query = generic_qs.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_qs.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0]
coleifer/django-generic-aggregation
84358b1917ff368651467920ff9d54cb244681c2
Adding fallback methods and tests -- essentially, django will set up the joins correctly but not the necessary cast if the target PK differs from the generic foreign key's fk_field (e.g. django comments uses a textfield) -- which results in a database error. The fallback methods handle proper casting.
diff --git a/generic_aggregation/generic_aggregation_tests/models.py b/generic_aggregation/generic_aggregation_tests/models.py index de0079c..35c0d81 100644 --- a/generic_aggregation/generic_aggregation_tests/models.py +++ b/generic_aggregation/generic_aggregation_tests/models.py @@ -1,33 +1,33 @@ import datetime from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Rating(models.Model): rating = models.IntegerField() created = models.DateTimeField(default=datetime.datetime.now) object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') def __unicode__(self): return '%s rated %s' % (self.content_object, self.rating) class CharFieldGFK(models.Model): name = models.CharField(max_length=255) - object_id = models.CharField(max_length=10) + object_id = models.TextField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') class Food(models.Model): name = models.CharField(max_length=100) ratings = GenericRelation(Rating) char_gfk = GenericRelation(CharFieldGFK) def __unicode__(self): return self.name diff --git a/generic_aggregation/generic_aggregation_tests/tests.py b/generic_aggregation/generic_aggregation_tests/tests.py index c59d5b0..37cb5d9 100644 --- a/generic_aggregation/generic_aggregation_tests/tests.py +++ b/generic_aggregation/generic_aggregation_tests/tests.py @@ -1,136 +1,150 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase -from generic_aggregation import generic_annotate, generic_aggregate, generic_filter +from generic_aggregation import generic_annotate as _generic_annotate, generic_aggregate as _generic_aggregate, generic_filter +from generic_aggregation.utils import fallback_generic_annotate, fallback_generic_aggregate from generic_aggregation.generic_aggregation_tests.models import ( Food, Rating, CharFieldGFK ) class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) + + def generic_annotate(self, *args, **kwargs): + return _generic_annotate(*args, **kwargs) + + def generic_aggregate(self, *args, **kwargs): + return _generic_aggregate(*args, **kwargs) def test_annotation(self): - annotated_qs = generic_annotate(Food.objects.all(), Rating.objects.all(), models.Count('ratings__rating')) + annotated_qs = self.generic_annotate(Food.objects.all(), Rating.objects.all(), models.Count('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') - annotated_qs = generic_annotate(Food.objects.all(), Rating, models.Sum('ratings__rating')) + annotated_qs = self.generic_annotate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') - annotated_qs = generic_annotate(Food, Rating, models.Avg('ratings__rating')) + annotated_qs = self.generic_annotate(Food, Rating, models.Avg('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food - aggregated = generic_aggregate(Food, Rating, models.Count('ratings__rating')) + aggregated = self.generic_aggregate(Food, Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods - aggregated = generic_aggregate(Food.objects.all(), Rating, models.Sum('ratings__rating')) + aggregated = self.generic_aggregate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) - aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Count('ratings__rating')) + aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) - aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Count('ratings__rating')) + aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 3) # avg for apple - aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Avg('ratings__rating')) + aggregated = self.generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 3) # avg for orange - aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Avg('ratings__rating')) + aggregated = self.generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) - annotated_qs = generic_annotate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) + annotated_qs = self.generic_annotate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) - aggregated = generic_aggregate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) + aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(aggregated, 15) - aggregated = generic_aggregate(Food.objects.all(), todays_ratings, models.Count('ratings__rating')) + aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) - annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) + annotated_qs = self.generic_annotate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') - aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) + aggregated = self.generic_aggregate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): - annotated_qs = generic_annotate(Food, Rating, models.Count('ratings__rating'), alias='count') + annotated_qs = self.generic_annotate(Food, Rating, models.Count('ratings__rating'), alias='count') food_a, food_b = annotated_qs.order_by('-count') self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') def test_filter(self): ratings = generic_filter(Rating.objects.all(), Food.objects.filter(name='orange')) self.assertEqual(len(ratings), 3) + +class FallbackTestCase(SimpleTest): + def generic_aggregate(self, *args, **kwargs): + return fallback_generic_annotate(*args, **kwargs) + + def generic_aggregate(self, *args, **kwargs): + return fallback_generic_aggregate(*args, **kwargs) diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 9aca3fd..c8e34ec 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,91 +1,289 @@ +""" +Django does not properly set up casts +""" + import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection, models from django.db.models.query import QuerySet def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) def normalize_qs_model(qs_or_model): if isinstance(qs_or_model, QuerySet): return qs_or_model return qs_or_model._default_manager.all() +def get_field_type(f): + if django.VERSION < (1, 4): + raw_type = f.db_type() + else: + raw_type = f.db_type(connection) + if raw_type.lower().split()[0] in ('serial', 'integer', 'unsigned', 'bigint', 'smallint'): + raw_type = 'integer' + return raw_type + def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): qs = normalize_qs_model(qs_model) generic_qs = normalize_qs_model(generic_qs_model) + model = qs.model + generic_model = generic_qs.model + if gfk_field is None: - gfk_field = get_gfk_field(generic_qs.model) + gfk_field = get_gfk_field(generic_model) - content_type = ContentType.objects.get_for_model(qs.model) + content_type = ContentType.objects.get_for_model(model) rel_name = aggregator.lookup.split('__', 1)[0] + try: + generic_rel_descriptor = getattr(model, rel_name) + except AttributeError: + # missing the generic relation, so do fallback query + return False + + rel_model = generic_rel_descriptor.field.rel.to + if rel_model != generic_model: + raise AttributeError('Model %s does not match the GenericRelation "%s" (%s)' % ( + generic_model, rel_name, rel_model, + )) + + pk_field_type = get_field_type(model._meta.pk) + gfk_field_type = get_field_type(generic_model._meta.get_field(gfk_field.fk_field)) + if pk_field_type != gfk_field_type: + return False + qs = qs.filter(**{ '%s__%s' % (rel_name, gfk_field.ct_field): content_type, '%s__pk__in' % (rel_name): generic_qs.values('pk'), }) return qs def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation Note: requires presence of a GenericRelation() on the qs_model, which should be referenced in the aggregator function + Warning: + if the primary key field differs in type from the GFK's fk_field a CAST + is not expressed on the JOIN, so the code will fallback gracefully + Example: generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) - return prepared_query.annotate(**{alias: aggregator}) + if prepared_query is not False: + return prepared_query.annotate(**{alias: aggregator}) + else: + # need to fall back since CAST will be missing + return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias) def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk Note: requires presence of a GenericRelation() on the qs_model, which should be referenced in the aggregator function + Warning: + if the primary key field differs in type from the GFK's fk_field a CAST + is not expressed on the JOIN, so the code will fallback gracefully + Example: generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) """ prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) - return prepared_query.aggregate(aggregate=aggregator)['aggregate'] + if prepared_query is not False: + return prepared_query.aggregate(aggregate=aggregator)['aggregate'] + else: + # need to fall back since CAST will be missing + return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field) def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Filter a queryset of objects containing GFKs so that they are restricted to only those objects that relate to items in the filter queryset """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), }) + + +############################################################################### +# fallback methods + +def query_as_sql(query): + if django.VERSION < (1, 2): + return query.as_sql() + else: + return query.get_compiler(connection=connection).as_sql() + +def query_as_nested_sql(query): + if django.VERSION < (1, 2): + return query.as_nested_sql() + else: + return query.get_compiler(connection=connection).as_nested_sql() + +def gfk_expression(qs_model, gfk_field): + # handle casting the GFK field if need be + qn = connection.ops.quote_name + + pk_field_type = get_field_type(qs_model._meta.pk) + gfk_field_type = get_field_type(gfk_field.model._meta.get_field(gfk_field.fk_field)) + + if pk_field_type != gfk_field_type: + # cast the gfk to the pk type + gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) + else: + gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK + + return gfk_expr + +def fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): + qs = normalize_qs_model(qs_model) + generic_qs = normalize_qs_model(generic_qs_model) + + content_type = ContentType.objects.get_for_model(qs.model) + + qn = connection.ops.quote_name + aggregate_field = aggregator.lookup + + # since the aggregate may contain a generic relation, strip it + if '__' in aggregate_field: + _, aggregate_field = aggregate_field.rsplit('__', 1) + + if gfk_field is None: + gfk_field = get_gfk_field(generic_qs.model) + + # collect the params we'll be using + params = ( + aggregator.name, # the function that's doing the aggregation + qn(aggregate_field), # the field containing the value to aggregate + qn(gfk_field.model._meta.db_table), # table holding gfk'd item info + qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK + content_type.pk, # the content_type id we need to match + gfk_expression(qs.model, gfk_field), + qn(qs.model._meta.db_table), # the table and pk from the main + qn(qs.model._meta.pk.name) # part of the query + ) + + sql_template = """ + SELECT %s(%s) AS aggregate_score + FROM %s + WHERE + %s=%s AND + %s=%s.%s""" + + extra = sql_template % params + + if generic_qs.query.where.children: + generic_query = generic_qs.values_list('pk').query + inner_query, inner_query_params = query_as_sql(generic_query) + + inner_params = ( + qn(generic_qs.model._meta.db_table), + qn(generic_qs.model._meta.pk.name), + ) + inner_start = ' AND %s.%s IN (' % inner_params + inner_end = ')' + extra = extra + inner_start + inner_query + inner_end + else: + inner_query_params = [] + + return qs.extra( + select={alias: extra}, + select_params=inner_query_params, + ) + +def fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): + qs = normalize_qs_model(qs_model) + generic_qs = normalize_qs_model(generic_qs_model) + + content_type = ContentType.objects.get_for_model(qs.model) + + qn = connection.ops.quote_name + aggregate_field = aggregator.lookup + + # since the aggregate may contain a generic relation, strip it + if '__' in aggregate_field: + _, aggregate_field = aggregate_field.rsplit('__', 1) + + if gfk_field is None: + gfk_field = get_gfk_field(generic_qs.model) + + qs = qs.values_list('pk') # just the pks + query, query_params = query_as_nested_sql(qs.query) + + # collect the params we'll be using + params = ( + aggregator.name, # the function that's doing the aggregation + qn(aggregate_field), # the field containing the value to aggregate + qn(gfk_field.model._meta.db_table), # table holding gfk'd item info + qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK + content_type.pk, # the content_type id we need to match + gfk_expression(qs.model, gfk_field), # the object_id field on the GFK + ) + + query_start = """ + SELECT %s(%s) AS aggregate_score + FROM %s + WHERE + %s=%s AND + %s IN ( + """ % params + + query_end = ")" + + if generic_qs.query.where.children: + generic_query = generic_qs.values_list('pk').query + inner_query, inner_query_params = query_as_sql(generic_query) + + query_params += inner_query_params + + inner_params = ( + qn(generic_qs.model._meta.pk.name), + ) + inner_start = ' AND %s IN (' % inner_params + inner_end = ')' + query_end = query_end + inner_start + inner_query + inner_end + + # pass in the inner_query unmodified as we will use the cursor to handle + # quoting the inner parameters correctly + query = query_start + query + query_end + + cursor = connection.cursor() + cursor.execute(query, query_params) + row = cursor.fetchone() + + return row[0]
coleifer/django-generic-aggregation
3f6ee47f13cdceaa12729f6b9ceca5dbefd59644
version
diff --git a/setup.py b/setup.py index b3f8183..bdd145b 100644 --- a/setup.py +++ b/setup.py @@ -1,33 +1,33 @@ import os from setuptools import setup, find_packages f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() -VERSION = (0, 1, 2) +VERSION = (0, 2, 0) setup( name='django-generic-aggregation', version=".".join(map(str, VERSION)), description='annotate() and aggregate() for generically related data', long_description=readme, author='Charles Leifer', author_email='[email protected]', url='http://github.com/coleifer/django-generic-aggregation/', packages=find_packages(), package_data = { 'generic_aggregation': [ ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], test_suite='runtests.runtests', )
coleifer/django-generic-aggregation
0bf0b47ad40d57cf5487e56d37891279cbefa224
Updating readme
diff --git a/README.rst b/README.rst index 4500504..7bd1721 100644 --- a/README.rst +++ b/README.rst @@ -1,56 +1,58 @@ ========================== django-generic-aggregation ========================== annotate() and aggregate() for generically-related data. also a handy function for filtering GFK-model querysets. +the use of annotate() and aggregate() require a ``GenericRelation``. + Examples -------- You want the most commented on blog entries:: >>> from django.contrib.comments.models import Comment >>> from django.db.models import Count >>> from blog.models import BlogEntry >>> from generic_aggregation import generic_annotate - >>> annotated = generic_annotate(BlogEntry.objects.all(), Comment.content_object, Count('id')) + >>> annotated = generic_annotate(BlogEntry.objects.all(), Comment, Count('comments__id')) >>> for entry in annotated: ... print entry.title, entry.score The most popular 5 The second best 4 Nobody commented 0 You want to figure out which items are highest rated:: from django.db.models import Sum, Avg # assume a Food model and a generic Rating model apple = Food.objects.create(name='apple') # create some ratings on the food Rating.objects.create(content_object=apple, rating=3) Rating.objects.create(content_object=apple, rating=5) Rating.objects.create(content_object=apple, rating=7) - >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, Sum('rating')) + >>> aggregate = generic_aggregate(Food, Rating, Sum('ratings__rating')) >>> print aggregate 15 - >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, Avg('rating')) + >>> aggregate = generic_aggregate(Food, Rating.objects.all(), Avg('ratings__rating')) >>> print aggregate 5 You want to only display ratings for comments made on a given site: >>> from django.contrib.comments.models import Comment >>> from generic_aggregation import generic_filter >>> ratings = Rating.objects.all() # <--- grab all the ratings >>> comments = Comment.objects.filter(site=Site.objects.get_current()) >>> siteified_ratings = generic_filter(ratings, comments) Check the tests - there are more examples there. Tested with postgres & sqlite
coleifer/django-generic-aggregation
2650528e60c3115decfecb36d9fc551164894f7d
By using a GenericRelation it is possible to greatly simplify querying across gfks -- this even extends to annotation and aggregation though the content-type must be filtered for explicitly.
diff --git a/generic_aggregation/generic_aggregation_tests/models.py b/generic_aggregation/generic_aggregation_tests/models.py index c02f069..de0079c 100644 --- a/generic_aggregation/generic_aggregation_tests/models.py +++ b/generic_aggregation/generic_aggregation_tests/models.py @@ -1,29 +1,33 @@ import datetime -from django.contrib.contenttypes.generic import GenericForeignKey +from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models -class Food(models.Model): - name = models.CharField(max_length=100) - - def __unicode__(self): - return self.name - class Rating(models.Model): rating = models.IntegerField() created = models.DateTimeField(default=datetime.datetime.now) object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') def __unicode__(self): return '%s rated %s' % (self.content_object, self.rating) class CharFieldGFK(models.Model): name = models.CharField(max_length=255) object_id = models.CharField(max_length=10) content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') + + +class Food(models.Model): + name = models.CharField(max_length=100) + + ratings = GenericRelation(Rating) + char_gfk = GenericRelation(CharFieldGFK) + + def __unicode__(self): + return self.name diff --git a/generic_aggregation/generic_aggregation_tests/tests.py b/generic_aggregation/generic_aggregation_tests/tests.py index 74712c4..c59d5b0 100644 --- a/generic_aggregation/generic_aggregation_tests/tests.py +++ b/generic_aggregation/generic_aggregation_tests/tests.py @@ -1,143 +1,136 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate, generic_aggregate, generic_filter from generic_aggregation.generic_aggregation_tests.models import ( Food, Rating, CharFieldGFK ) class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def test_annotation(self): - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating')) + annotated_qs = generic_annotate(Food.objects.all(), Rating.objects.all(), models.Count('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating')) + annotated_qs = generic_annotate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) - food_b, food_a = annotated_qs + food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Avg('rating')) + annotated_qs = generic_annotate(Food, Rating, models.Avg('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) - food_b, food_a = annotated_qs + food_b, food_a = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food - aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Count('rating')) + aggregated = generic_aggregate(Food, Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods - aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Sum('rating')) + aggregated = generic_aggregate(Food.objects.all(), Rating, models.Sum('ratings__rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) - aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, models.Count('rating')) + aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) - aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, models.Count('rating')) + aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Count('ratings__rating')) self.assertEqual(aggregated, 3) # avg for apple - aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, models.Avg('rating')) + aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 3) # avg for orange - aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, models.Avg('rating')) + aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating, models.Avg('ratings__rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating'), todays_ratings) + annotated_qs = generic_annotate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(annotated_qs.count(), 2) - food_a, food_b = annotated_qs + food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) - aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Sum('rating'), todays_ratings) + aggregated = generic_aggregate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating')) self.assertEqual(aggregated, 15) - aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Count('rating'), todays_ratings) + aggregated = generic_aggregate(Food.objects.all(), todays_ratings, models.Count('ratings__rating')) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) - annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name')) + annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(annotated_qs.count(), 2) - food_a, food_b = annotated_qs + food_a, food_b = annotated_qs.order_by('-score') self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') - aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name')) + aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK, models.Count('char_gfk__name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), alias='count') - food_a, food_b = annotated_qs + annotated_qs = generic_annotate(Food, Rating, models.Count('ratings__rating'), alias='count') + food_a, food_b = annotated_qs.order_by('-count') self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') - - def test_ascending_order(self): - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), desc=False, alias='count') - food_a, food_b = annotated_qs - - self.assertEqual(food_b.count, 4) - self.assertEqual(food_b.name, 'apple') def test_filter(self): ratings = generic_filter(Rating.objects.all(), Food.objects.filter(name='orange')) self.assertEqual(len(ratings), 3) diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index ff35bcf..9aca3fd 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,178 +1,91 @@ import django from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection, models +from django.db.models.query import QuerySet -def query_as_sql(query): - if django.VERSION < (1, 2): - return query.as_sql() - else: - return query.get_compiler(connection=connection).as_sql() - -def query_as_nested_sql(query): - if django.VERSION < (1, 2): - return query.as_nested_sql() - else: - return query.get_compiler(connection=connection).as_nested_sql() - -def gfk_expression(qs_model, gfk_field): - # handle casting the GFK field if need be - qn = connection.ops.quote_name - - pk_field_type = qs_model._meta.pk.db_type() - gfk_field_type = gfk_field.model._meta.get_field(gfk_field.fk_field).db_type() - - if pk_field_type == 'serial': - pk_field_type = 'integer' - elif pk_field_type.lower() == 'integer auto_increment': - pk_field_type = 'UNSIGNED' - - if pk_field_type != gfk_field_type: - # cast the gfk to the pk type - gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) - else: - gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK - - return gfk_expr def get_gfk_field(model): for field in model._meta.virtual_fields: if isinstance(field, GenericForeignKey): return field raise ValueError('Unable to find gfk field on %s' % model) -def generic_annotate(queryset, gfk_field, aggregator, generic_queryset=None, - desc=True, alias='score'): - if gfk_field is None and generic_queryset: - gfk_field = get_gfk_field(generic_queryset.model) - ordering = desc and '-%s' % alias or alias - content_type = ContentType.objects.get_for_model(queryset.model) - - qn = connection.ops.quote_name - aggregate_field = aggregator.lookup - - # collect the params we'll be using - params = ( - aggregator.name, # the function that's doing the aggregation - qn(aggregate_field), # the field containing the value to aggregate - qn(gfk_field.model._meta.db_table), # table holding gfk'd item info - qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK - content_type.pk, # the content_type id we need to match - gfk_expression(queryset.model, gfk_field), - qn(queryset.model._meta.db_table), # the table and pk from the main - qn(queryset.model._meta.pk.name) # part of the query - ) - - sql_template = """ - SELECT %s(%s) AS aggregate_score - FROM %s - WHERE - %s=%s AND - %s=%s.%s""" +def normalize_qs_model(qs_or_model): + if isinstance(qs_or_model, QuerySet): + return qs_or_model + return qs_or_model._default_manager.all() + +def prepare_query(qs_model, generic_qs_model, aggregator, gfk_field): + qs = normalize_qs_model(qs_model) + generic_qs = normalize_qs_model(generic_qs_model) - extra = sql_template % params + if gfk_field is None: + gfk_field = get_gfk_field(generic_qs.model) - if generic_queryset is not None: - generic_query = generic_queryset.values_list('pk').query - inner_query, inner_query_params = query_as_sql(generic_query) - - inner_params = ( - qn(generic_queryset.model._meta.db_table), - qn(generic_queryset.model._meta.pk.name), - ) - inner_start = ' AND %s.%s IN (' % inner_params - inner_end = ')' - extra = extra + inner_start + inner_query + inner_end - else: - inner_query_params = [] - - queryset = queryset.extra( - select={alias: extra}, - select_params=inner_query_params, - order_by=[ordering] - ) + content_type = ContentType.objects.get_for_model(qs.model) + rel_name = aggregator.lookup.split('__', 1)[0] - return queryset + qs = qs.filter(**{ + '%s__%s' % (rel_name, gfk_field.ct_field): content_type, + '%s__pk__in' % (rel_name): generic_qs.values('pk'), + }) + return qs +def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): + """ + :param qs_model: A model or a queryset of objects you want to perform + annotation on, e.g. blog entries + :param generic_qs_model: A model or queryset containing a GFK, e.g. comments + :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') + :param gfk_field: explicitly specify the field w/the gfk + :param alias: attribute name to use for annotation + + Note: + requires presence of a GenericRelation() on the qs_model, which should + be referenced in the aggregator function + + Example: + + generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) + """ + prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) + return prepared_query.annotate(**{alias: aggregator}) -def generic_aggregate(queryset, gfk_field, aggregator, generic_queryset=None): - if gfk_field is None and generic_queryset: - gfk_field = get_gfk_field(generic_queryset.model) - content_type = ContentType.objects.get_for_model(queryset.model) - - queryset = queryset.values_list('pk') # just the pks - query, query_params = query_as_nested_sql(queryset.query) - - qn = connection.ops.quote_name - aggregate_field = aggregator.lookup - - # collect the params we'll be using - params = ( - aggregator.name, # the function that's doing the aggregation - qn(aggregate_field), # the field containing the value to aggregate - qn(gfk_field.model._meta.db_table), # table holding gfk'd item info - qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK - content_type.pk, # the content_type id we need to match - gfk_expression(queryset.model, gfk_field), # the object_id field on the GFK - ) - - query_start = """ - SELECT %s(%s) AS aggregate_score - FROM %s - WHERE - %s=%s AND - %s IN ( - """ % params - - query_end = ")" - - if generic_queryset is not None: - generic_query = generic_queryset.values_list('pk').query - inner_query, inner_query_params = query_as_sql(generic_query) - - query_params += inner_query_params - - inner_params = ( - qn(generic_queryset.model._meta.pk.name), - ) - inner_start = ' AND %s IN (' % inner_params - inner_end = ')' - query_end = query_end + inner_start + inner_query + inner_end - - # pass in the inner_query unmodified as we will use the cursor to handle - # quoting the inner parameters correctly - query = query_start + query + query_end - - cursor = connection.cursor() - cursor.execute(query, query_params) - row = cursor.fetchone() - return row[0] +def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): + """ + :param qs_model: A model or a queryset of objects you want to perform + annotation on, e.g. blog entries + :param generic_qs_model: A model or queryset containing a GFK, e.g. comments + :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') + :param gfk_field: explicitly specify the field w/the gfk + + Note: + requires presence of a GenericRelation() on the qs_model, which should + be referenced in the aggregator function + + Example: + + generic_annotate(Food.objects.all(), Rating.objects.all(), Avg('ratings__rating')) + """ + prepared_query = prepare_query(qs_model, generic_qs_model, aggregator, gfk_field) + return prepared_query.aggregate(aggregate=aggregator)['aggregate'] -def generic_filter(queryset, filter_queryset, gfk_field=None): - if not gfk_field: - gfk_field = get_gfk_field(queryset.model) - - # get the contenttype of our filtered queryset, e.g. Business - filter_model = filter_queryset.model - content_type = ContentType.objects.get_for_model(filter_model) - - # filter the generic queryset to only include items of the given ctype - queryset = queryset.filter(**{gfk_field.ct_field: content_type}) - - qn = connection.ops.quote_name - # just select the primary keys in the sub-select - filtered_query = filter_queryset.values_list('pk').query - inner_query, inner_query_params = query_as_sql(filtered_query) +def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): + """ + Filter a queryset of objects containing GFKs so that they are restricted to + only those objects that relate to items in the filter queryset + """ + generic_qs = normalize_qs_model(generic_qs_model) + filter_qs = normalize_qs_model(filter_qs_model) - where = '%s IN (%s)' % ( - gfk_expression(filter_model, gfk_field), - inner_query, - ) + if not gfk_field: + gfk_field = get_gfk_field(generic_qs.model) - return queryset.extra( - where=(where,), - params=inner_query_params - ) + return generic_qs.filter(**{ + gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), + '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), + })
coleifer/django-generic-aggregation
1e99bb4add744f0fa6cdb9c6cf82aa51b9961da0
Updating the readme
diff --git a/README.rst b/README.rst index b057e4d..4500504 100644 --- a/README.rst +++ b/README.rst @@ -1,48 +1,56 @@ ========================== django-generic-aggregation ========================== -annotate() and aggregate() for generically-related data. +annotate() and aggregate() for generically-related data. also a handy function +for filtering GFK-model querysets. Examples -------- You want the most commented on blog entries:: >>> from django.contrib.comments.models import Comment >>> from django.db.models import Count >>> from blog.models import BlogEntry >>> from generic_aggregation import generic_annotate >>> annotated = generic_annotate(BlogEntry.objects.all(), Comment.content_object, Count('id')) >>> for entry in annotated: ... print entry.title, entry.score The most popular 5 The second best 4 Nobody commented 0 You want to figure out which items are highest rated:: from django.db.models import Sum, Avg # assume a Food model and a generic Rating model apple = Food.objects.create(name='apple') # create some ratings on the food Rating.objects.create(content_object=apple, rating=3) Rating.objects.create(content_object=apple, rating=5) Rating.objects.create(content_object=apple, rating=7) >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, Sum('rating')) >>> print aggregate 15 >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, Avg('rating')) >>> print aggregate 5 +You want to only display ratings for comments made on a given site: + + >>> from django.contrib.comments.models import Comment + >>> from generic_aggregation import generic_filter + >>> ratings = Rating.objects.all() # <--- grab all the ratings + >>> comments = Comment.objects.filter(site=Site.objects.get_current()) + >>> siteified_ratings = generic_filter(ratings, comments) Check the tests - there are more examples there. Tested with postgres & sqlite
coleifer/django-generic-aggregation
d5d59e70233ec20b88b9f1440e88520403958fdf
Adding a generic_filter method for filtering a GFK queryset by a sub-query of items
diff --git a/generic_aggregation/__init__.py b/generic_aggregation/__init__.py index aac7f1b..aa872d7 100644 --- a/generic_aggregation/__init__.py +++ b/generic_aggregation/__init__.py @@ -1 +1 @@ -from generic_aggregation.utils import generic_aggregate, generic_annotate +from generic_aggregation.utils import generic_aggregate, generic_annotate, generic_filter diff --git a/generic_aggregation/generic_aggregation_tests/tests.py b/generic_aggregation/generic_aggregation_tests/tests.py index c881b45..74712c4 100644 --- a/generic_aggregation/generic_aggregation_tests/tests.py +++ b/generic_aggregation/generic_aggregation_tests/tests.py @@ -1,139 +1,143 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase -from generic_aggregation import generic_annotate, generic_aggregate +from generic_aggregation import generic_annotate, generic_aggregate, generic_filter from generic_aggregation.generic_aggregation_tests.models import ( Food, Rating, CharFieldGFK ) class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def test_annotation(self): annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Avg('rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Count('rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Sum('rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, models.Count('rating')) self.assertEqual(aggregated, 4) aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, models.Count('rating')) self.assertEqual(aggregated, 3) # avg for apple aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, models.Avg('rating')) self.assertEqual(aggregated, 3) # avg for orange aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, models.Avg('rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating'), todays_ratings) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Sum('rating'), todays_ratings) self.assertEqual(aggregated, 15) aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Count('rating'), todays_ratings) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), alias='count') food_a, food_b = annotated_qs self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') def test_ascending_order(self): annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), desc=False, alias='count') food_a, food_b = annotated_qs self.assertEqual(food_b.count, 4) self.assertEqual(food_b.name, 'apple') + + def test_filter(self): + ratings = generic_filter(Rating.objects.all(), Food.objects.filter(name='orange')) + self.assertEqual(len(ratings), 3) diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 180a386..ff35bcf 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,140 +1,178 @@ import django +from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import connection, models def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = qs_model._meta.pk.db_type() gfk_field_type = gfk_field.model._meta.get_field(gfk_field.fk_field).db_type() if pk_field_type == 'serial': pk_field_type = 'integer' elif pk_field_type.lower() == 'integer auto_increment': pk_field_type = 'UNSIGNED' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr +def get_gfk_field(model): + for field in model._meta.virtual_fields: + if isinstance(field, GenericForeignKey): + return field + + raise ValueError('Unable to find gfk field on %s' % model) def generic_annotate(queryset, gfk_field, aggregator, generic_queryset=None, desc=True, alias='score'): + if gfk_field is None and generic_queryset: + gfk_field = get_gfk_field(generic_queryset.model) ordering = desc and '-%s' % alias or alias content_type = ContentType.objects.get_for_model(queryset.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(queryset.model, gfk_field), qn(queryset.model._meta.db_table), # the table and pk from the main qn(queryset.model._meta.pk.name) # part of the query ) sql_template = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_queryset.model._meta.db_table), qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] queryset = queryset.extra( select={alias: extra}, select_params=inner_query_params, order_by=[ordering] ) return queryset def generic_aggregate(queryset, gfk_field, aggregator, generic_queryset=None): + if gfk_field is None and generic_queryset: + gfk_field = get_gfk_field(generic_queryset.model) content_type = ContentType.objects.get_for_model(queryset.model) queryset = queryset.values_list('pk') # just the pks query, query_params = query_as_nested_sql(queryset.query) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(queryset.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0] + +def generic_filter(queryset, filter_queryset, gfk_field=None): + if not gfk_field: + gfk_field = get_gfk_field(queryset.model) + + # get the contenttype of our filtered queryset, e.g. Business + filter_model = filter_queryset.model + content_type = ContentType.objects.get_for_model(filter_model) + + # filter the generic queryset to only include items of the given ctype + queryset = queryset.filter(**{gfk_field.ct_field: content_type}) + + qn = connection.ops.quote_name + + # just select the primary keys in the sub-select + filtered_query = filter_queryset.values_list('pk').query + inner_query, inner_query_params = query_as_sql(filtered_query) + + where = '%s IN (%s)' % ( + gfk_expression(filter_model, gfk_field), + inner_query, + ) + + return queryset.extra( + where=(where,), + params=inner_query_params + )
coleifer/django-generic-aggregation
b8cb7d924e887cbff2bd09813d6971034b6a1892
Allow running with postgres
diff --git a/runtests.py b/runtests.py index a697e19..2cfa802 100755 --- a/runtests.py +++ b/runtests.py @@ -1,31 +1,38 @@ #!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings +if len(sys.argv) > 1 and 'postgres' in sys.argv: + sys.argv.remove('postgres') + db_engine = 'postgresql_psycopg2' + db_name = 'test_main' +else: + db_engine = 'sqlite3' + db_name = '' + if not settings.configured: settings.configure( - DATABASE_ENGINE = 'sqlite3', - # DATABASE_ENGINE = 'postgresql_psycopg2', - # DATABASE_NAME = 'test_main', + DATABASE_ENGINE = db_engine, + DATABASE_NAME = db_name, INSTALLED_APPS = [ 'django.contrib.contenttypes', 'generic_aggregation.generic_aggregation_tests', ], ) from django.test.simple import run_tests def runtests(*test_args): if not test_args: test_args = ['generic_aggregation_tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
coleifer/django-generic-aggregation
7ef7b02cae25f2c7dea90690cf8d577fa86d9252
Small cleanup in generic_aggregation for simpler testing
diff --git a/generic_aggregation/tests/__init__.py b/generic_aggregation/generic_aggregation_tests/__init__.py similarity index 100% rename from generic_aggregation/tests/__init__.py rename to generic_aggregation/generic_aggregation_tests/__init__.py diff --git a/generic_aggregation/tests/models.py b/generic_aggregation/generic_aggregation_tests/models.py similarity index 100% rename from generic_aggregation/tests/models.py rename to generic_aggregation/generic_aggregation_tests/models.py diff --git a/generic_aggregation/tests/tests.py b/generic_aggregation/generic_aggregation_tests/tests.py similarity index 98% rename from generic_aggregation/tests/tests.py rename to generic_aggregation/generic_aggregation_tests/tests.py index 4778e10..c881b45 100644 --- a/generic_aggregation/tests/tests.py +++ b/generic_aggregation/generic_aggregation_tests/tests.py @@ -1,137 +1,139 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate, generic_aggregate -from generic_aggregation.tests.models import Food, Rating, CharFieldGFK +from generic_aggregation.generic_aggregation_tests.models import ( + Food, Rating, CharFieldGFK +) class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def test_annotation(self): annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Avg('rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Count('rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Sum('rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, models.Count('rating')) self.assertEqual(aggregated, 4) aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, models.Count('rating')) self.assertEqual(aggregated, 3) # avg for apple aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, models.Avg('rating')) self.assertEqual(aggregated, 3) # avg for orange aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, models.Avg('rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating'), todays_ratings) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Sum('rating'), todays_ratings) self.assertEqual(aggregated, 15) aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Count('rating'), todays_ratings) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), alias='count') food_a, food_b = annotated_qs self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') def test_ascending_order(self): annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), desc=False, alias='count') food_a, food_b = annotated_qs self.assertEqual(food_b.count, 4) self.assertEqual(food_b.name, 'apple') diff --git a/generic_aggregation/tests/settings.py b/generic_aggregation/tests/settings.py deleted file mode 100644 index 3980318..0000000 --- a/generic_aggregation/tests/settings.py +++ /dev/null @@ -1,8 +0,0 @@ -DATABASE_ENGINE = 'sqlite3' -#DATABASE_ENGINE = 'postgresql_psycopg2' -#DATABASE_NAME = 'test_main' - -INSTALLED_APPS = [ - 'django.contrib.contenttypes', - 'generic_aggregation.tests', -] diff --git a/runtests.py b/runtests.py new file mode 100755 index 0000000..a697e19 --- /dev/null +++ b/runtests.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python +import sys +from os.path import dirname, abspath + +from django.conf import settings + +if not settings.configured: + settings.configure( + DATABASE_ENGINE = 'sqlite3', + # DATABASE_ENGINE = 'postgresql_psycopg2', + # DATABASE_NAME = 'test_main', + INSTALLED_APPS = [ + 'django.contrib.contenttypes', + 'generic_aggregation.generic_aggregation_tests', + ], + ) + +from django.test.simple import run_tests + + +def runtests(*test_args): + if not test_args: + test_args = ['generic_aggregation_tests'] + parent = dirname(abspath(__file__)) + sys.path.insert(0, parent) + failures = run_tests(test_args, verbosity=1, interactive=True) + sys.exit(failures) + + +if __name__ == '__main__': + runtests(*sys.argv[1:]) diff --git a/setup.py b/setup.py index 8800f89..b3f8183 100644 --- a/setup.py +++ b/setup.py @@ -1,32 +1,33 @@ import os from setuptools import setup, find_packages f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() -VERSION = (0, 1, 1) +VERSION = (0, 1, 2) setup( name='django-generic-aggregation', version=".".join(map(str, VERSION)), description='annotate() and aggregate() for generically related data', long_description=readme, author='Charles Leifer', author_email='[email protected]', url='http://github.com/coleifer/django-generic-aggregation/', packages=find_packages(), package_data = { 'generic_aggregation': [ ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], + test_suite='runtests.runtests', )
coleifer/django-generic-aggregation
1666021f3a415facc78dc6792413286b9aa3f948
Removing spurious version constant
diff --git a/generic_aggregation/__init__.py b/generic_aggregation/__init__.py index 992db6d..aac7f1b 100644 --- a/generic_aggregation/__init__.py +++ b/generic_aggregation/__init__.py @@ -1,3 +1 @@ from generic_aggregation.utils import generic_aggregate, generic_annotate - -VERSION = (0, 1, 0)
coleifer/django-generic-aggregation
4d6d5cdae183446053b7f48c3bb88c381a154af9
Fixing issue #3 regarding failure casting PKs w/mysql
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 82fe2ef..180a386 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,138 +1,140 @@ import django from django.contrib.contenttypes.models import ContentType from django.db import connection, models def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = qs_model._meta.pk.db_type() gfk_field_type = gfk_field.model._meta.get_field(gfk_field.fk_field).db_type() if pk_field_type == 'serial': pk_field_type = 'integer' + elif pk_field_type.lower() == 'integer auto_increment': + pk_field_type = 'UNSIGNED' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def generic_annotate(queryset, gfk_field, aggregator, generic_queryset=None, desc=True, alias='score'): ordering = desc and '-%s' % alias or alias content_type = ContentType.objects.get_for_model(queryset.model) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(queryset.model, gfk_field), qn(queryset.model._meta.db_table), # the table and pk from the main qn(queryset.model._meta.pk.name) # part of the query ) sql_template = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_queryset.model._meta.db_table), qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] queryset = queryset.extra( select={alias: extra}, select_params=inner_query_params, order_by=[ordering] ) return queryset def generic_aggregate(queryset, gfk_field, aggregator, generic_queryset=None): content_type = ContentType.objects.get_for_model(queryset.model) queryset = queryset.values_list('pk') # just the pks query, query_params = query_as_nested_sql(queryset.query) qn = connection.ops.quote_name aggregate_field = aggregator.lookup # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(queryset.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0]
coleifer/django-generic-aggregation
fe4cc19e308dc948a31e3b09b682fd02a625b715
Adding manifest
diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..57e5411 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,4 @@ +include AUTHORS +include LICENSE +include MANIFEST.in +include README.rst
coleifer/django-generic-aggregation
44451bf131ef09901f32c85c80a1ef5da204ea45
Importing version imports django which makes setup.py sad
diff --git a/setup.py b/setup.py index ee517c4..8800f89 100644 --- a/setup.py +++ b/setup.py @@ -1,32 +1,32 @@ import os from setuptools import setup, find_packages -from generic_aggregation import VERSION - f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() +VERSION = (0, 1, 1) + setup( name='django-generic-aggregation', version=".".join(map(str, VERSION)), description='annotate() and aggregate() for generically related data', long_description=readme, author='Charles Leifer', author_email='[email protected]', url='http://github.com/coleifer/django-generic-aggregation/', packages=find_packages(), package_data = { 'generic_aggregation': [ ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
coleifer/django-generic-aggregation
07180f31120f8527a1352501197dd61ba43e9eb9
Cleaning up the API of generic aggregation - pass in an aggregator with a lookup instead of both separately
diff --git a/README.rst b/README.rst index 81faba4..b057e4d 100644 --- a/README.rst +++ b/README.rst @@ -1,48 +1,48 @@ ========================== django-generic-aggregation ========================== annotate() and aggregate() for generically-related data. Examples -------- You want the most commented on blog entries:: >>> from django.contrib.comments.models import Comment >>> from django.db.models import Count >>> from blog.models import BlogEntry >>> from generic_aggregation import generic_annotate - >>> annotated = generic_annotate(BlogEntry.objects.all(), Comment.content_object, 'id', Count) + >>> annotated = generic_annotate(BlogEntry.objects.all(), Comment.content_object, Count('id')) >>> for entry in annotated: ... print entry.title, entry.score The most popular 5 The second best 4 Nobody commented 0 You want to figure out which items are highest rated:: from django.db.models import Sum, Avg # assume a Food model and a generic Rating model apple = Food.objects.create(name='apple') # create some ratings on the food Rating.objects.create(content_object=apple, rating=3) Rating.objects.create(content_object=apple, rating=5) Rating.objects.create(content_object=apple, rating=7) - >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', Sum) + >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, Sum('rating')) >>> print aggregate 15 - >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', Avg) + >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, Avg('rating')) >>> print aggregate 5 Check the tests - there are more examples there. Tested with postgres & sqlite diff --git a/generic_aggregation/tests/tests.py b/generic_aggregation/tests/tests.py index 7158610..4778e10 100644 --- a/generic_aggregation/tests/tests.py +++ b/generic_aggregation/tests/tests.py @@ -1,137 +1,137 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate, generic_aggregate from generic_aggregation.tests.models import Food, Rating, CharFieldGFK class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def test_annotation(self): - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count) + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Sum) + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Avg) + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Avg('rating')) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food - aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Count) + aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Count('rating')) self.assertEqual(aggregated, 7) # total of ratings out there for all foods - aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Sum) + aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Sum('rating')) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) - aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, 'rating', models.Count) + aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, models.Count('rating')) self.assertEqual(aggregated, 4) - aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, 'rating', models.Count) + aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, models.Count('rating')) self.assertEqual(aggregated, 3) # avg for apple - aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, 'rating', models.Avg) + aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, models.Avg('rating')) self.assertEqual(aggregated, 3) # avg for orange - aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, 'rating', models.Avg) + aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, models.Avg('rating')) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Sum, todays_ratings) + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Sum('rating'), todays_ratings) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) - aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Sum, todays_ratings) + aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Sum('rating'), todays_ratings) self.assertEqual(aggregated, 15) - aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Count, todays_ratings) + aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, models.Count('rating'), todays_ratings) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) - annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK.content_object, 'name', models.Count) + annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name')) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') - aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK.content_object, 'name', models.Count) + aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK.content_object, models.Count('name')) self.assertEqual(aggregated, 3) def test_custom_alias(self): - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count, alias='count') + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), alias='count') food_a, food_b = annotated_qs self.assertEqual(food_a.count, 4) self.assertEqual(food_a.name, 'apple') def test_ascending_order(self): - annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count, desc=False, alias='count') + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, models.Count('rating'), desc=False, alias='count') food_a, food_b = annotated_qs self.assertEqual(food_b.count, 4) self.assertEqual(food_b.name, 'apple') diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 5b08dab..82fe2ef 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,137 +1,138 @@ import django from django.contrib.contenttypes.models import ContentType from django.db import connection, models def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = qs_model._meta.pk.db_type() gfk_field_type = gfk_field.model._meta.get_field(gfk_field.fk_field).db_type() if pk_field_type == 'serial': pk_field_type = 'integer' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr -def generic_annotate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, - generic_queryset=None, desc=True, alias='score'): +def generic_annotate(queryset, gfk_field, aggregator, generic_queryset=None, + desc=True, alias='score'): ordering = desc and '-%s' % alias or alias content_type = ContentType.objects.get_for_model(queryset.model) qn = connection.ops.quote_name + aggregate_field = aggregator.lookup # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(queryset.model, gfk_field), qn(queryset.model._meta.db_table), # the table and pk from the main qn(queryset.model._meta.pk.name) # part of the query ) sql_template = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_queryset.model._meta.db_table), qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] queryset = queryset.extra( select={alias: extra}, select_params=inner_query_params, order_by=[ordering] ) return queryset -def generic_aggregate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, - generic_queryset=None): +def generic_aggregate(queryset, gfk_field, aggregator, generic_queryset=None): content_type = ContentType.objects.get_for_model(queryset.model) queryset = queryset.values_list('pk') # just the pks query, query_params = query_as_nested_sql(queryset.query) qn = connection.ops.quote_name + aggregate_field = aggregator.lookup # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(queryset.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0]
coleifer/django-generic-aggregation
39537e9839efda74878138ff776b54f7ed39adfc
Fixing a bungled setup.py copy/paste foul
diff --git a/setup.py b/setup.py index 749796b..ee517c4 100644 --- a/setup.py +++ b/setup.py @@ -1,32 +1,32 @@ import os from setuptools import setup, find_packages -from news import VERSION +from generic_aggregation import VERSION f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) readme = f.read() f.close() setup( name='django-generic-aggregation', version=".".join(map(str, VERSION)), description='annotate() and aggregate() for generically related data', long_description=readme, author='Charles Leifer', author_email='[email protected]', url='http://github.com/coleifer/django-generic-aggregation/', packages=find_packages(), package_data = { 'generic_aggregation': [ ], }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
coleifer/django-generic-aggregation
38a2b35197ea6184cfbf032eec3e586831a0f0c1
Adding a gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..394e930 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.pyc +build/ +src/ +pip-log.txt +*DS_Store +*~ +dist/ +*.egg-info/
coleifer/django-generic-aggregation
b25bc8fb5c7e24b471d13fe6a995c2ec8efe31ca
Adding setup.py for use with pip
diff --git a/generic_aggregation/__init__.py b/generic_aggregation/__init__.py index aac7f1b..992db6d 100644 --- a/generic_aggregation/__init__.py +++ b/generic_aggregation/__init__.py @@ -1 +1,3 @@ from generic_aggregation.utils import generic_aggregate, generic_annotate + +VERSION = (0, 1, 0) diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..749796b --- /dev/null +++ b/setup.py @@ -0,0 +1,32 @@ +import os +from setuptools import setup, find_packages + +from news import VERSION + +f = open(os.path.join(os.path.dirname(__file__), 'README.rst')) +readme = f.read() +f.close() + +setup( + name='django-generic-aggregation', + version=".".join(map(str, VERSION)), + description='annotate() and aggregate() for generically related data', + long_description=readme, + author='Charles Leifer', + author_email='[email protected]', + url='http://github.com/coleifer/django-generic-aggregation/', + packages=find_packages(), + package_data = { + 'generic_aggregation': [ + ], + }, + classifiers=[ + 'Development Status :: 4 - Beta', + 'Environment :: Web Environment', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Framework :: Django', + ], +)
coleifer/django-generic-aggregation
1479517888c1aeff5137ecbc54fdb773f0697a7b
Allow an alias to be used for the extra param
diff --git a/generic_aggregation/tests/settings.py b/generic_aggregation/tests/settings.py index fd7977e..3980318 100644 --- a/generic_aggregation/tests/settings.py +++ b/generic_aggregation/tests/settings.py @@ -1,8 +1,8 @@ DATABASE_ENGINE = 'sqlite3' -DATABASE_ENGINE = 'postgresql_psycopg2' -DATABASE_NAME = 'test_main' +#DATABASE_ENGINE = 'postgresql_psycopg2' +#DATABASE_NAME = 'test_main' INSTALLED_APPS = [ 'django.contrib.contenttypes', 'generic_aggregation.tests', ] diff --git a/generic_aggregation/tests/tests.py b/generic_aggregation/tests/tests.py index 1289c21..7158610 100644 --- a/generic_aggregation/tests/tests.py +++ b/generic_aggregation/tests/tests.py @@ -1,123 +1,137 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate, generic_aggregate from generic_aggregation.tests.models import Food, Rating, CharFieldGFK class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def test_annotation(self): annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Sum) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Avg) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Count) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Sum) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, 'rating', models.Count) self.assertEqual(aggregated, 4) aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, 'rating', models.Count) self.assertEqual(aggregated, 3) # avg for apple aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, 'rating', models.Avg) self.assertEqual(aggregated, 3) # avg for orange aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, 'rating', models.Avg) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Sum, todays_ratings) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Sum, todays_ratings) self.assertEqual(aggregated, 15) aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Count, todays_ratings) self.assertEqual(aggregated, 4) def test_charfield_pks(self): a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK.content_object, 'name', models.Count) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_b.score, 1) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 2) self.assertEqual(food_a.name, 'apple') aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK.content_object, 'name', models.Count) self.assertEqual(aggregated, 3) + + def test_custom_alias(self): + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count, alias='count') + food_a, food_b = annotated_qs + + self.assertEqual(food_a.count, 4) + self.assertEqual(food_a.name, 'apple') + + def test_ascending_order(self): + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count, desc=False, alias='count') + food_a, food_b = annotated_qs + + self.assertEqual(food_b.count, 4) + self.assertEqual(food_b.name, 'apple') diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 40e33b1..5b08dab 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,137 +1,137 @@ import django from django.contrib.contenttypes.models import ContentType from django.db import connection, models def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() def gfk_expression(qs_model, gfk_field): # handle casting the GFK field if need be qn = connection.ops.quote_name pk_field_type = qs_model._meta.pk.db_type() gfk_field_type = gfk_field.model._meta.get_field(gfk_field.fk_field).db_type() if pk_field_type == 'serial': pk_field_type = 'integer' if pk_field_type != gfk_field_type: # cast the gfk to the pk type gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) else: gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK return gfk_expr def generic_annotate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, - generic_queryset=None, desc=True): - ordering = desc and '-score' or 'score' + generic_queryset=None, desc=True, alias='score'): + ordering = desc and '-%s' % alias or alias content_type = ContentType.objects.get_for_model(queryset.model) qn = connection.ops.quote_name # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(queryset.model, gfk_field), qn(queryset.model._meta.db_table), # the table and pk from the main qn(queryset.model._meta.pk.name) # part of the query ) sql_template = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s""" extra = sql_template % params if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_queryset.model._meta.db_table), qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] queryset = queryset.extra( - select={'score': extra}, + select={alias: extra}, select_params=inner_query_params, order_by=[ordering] ) return queryset def generic_aggregate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, generic_queryset=None): content_type = ContentType.objects.get_for_model(queryset.model) queryset = queryset.values_list('pk') # just the pks query, query_params = query_as_nested_sql(queryset.query) qn = connection.ops.quote_name # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match gfk_expression(queryset.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0]
coleifer/django-generic-aggregation
d9135d52d1304f299a91fe973e34d015a3fe1ffe
Support for handling non-integer gfk fk_fields, like Comments.
diff --git a/generic_aggregation/tests/models.py b/generic_aggregation/tests/models.py index 1121736..c02f069 100644 --- a/generic_aggregation/tests/models.py +++ b/generic_aggregation/tests/models.py @@ -1,22 +1,29 @@ import datetime from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Food(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Rating(models.Model): rating = models.IntegerField() created = models.DateTimeField(default=datetime.datetime.now) object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') def __unicode__(self): return '%s rated %s' % (self.content_object, self.rating) + + +class CharFieldGFK(models.Model): + name = models.CharField(max_length=255) + object_id = models.CharField(max_length=10) + content_type = models.ForeignKey(ContentType) + content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') diff --git a/generic_aggregation/tests/tests.py b/generic_aggregation/tests/tests.py index bf8c10c..1289c21 100644 --- a/generic_aggregation/tests/tests.py +++ b/generic_aggregation/tests/tests.py @@ -1,104 +1,123 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate, generic_aggregate -from generic_aggregation.tests.models import Food, Rating +from generic_aggregation.tests.models import Food, Rating, CharFieldGFK class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def test_annotation(self): annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Sum) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 12) self.assertEqual(food_a.name, 'apple') annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Avg) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Count) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Sum) self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, 'rating', models.Count) self.assertEqual(aggregated, 4) aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, 'rating', models.Count) self.assertEqual(aggregated, 3) # avg for apple aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, 'rating', models.Avg) self.assertEqual(aggregated, 3) # avg for orange aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, 'rating', models.Avg) self.assertEqual(aggregated, 5) def test_subset_annotation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Sum, todays_ratings) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 8) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 7) self.assertEqual(food_b.name, 'orange') def test_subset_aggregation(self): todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Sum, todays_ratings) self.assertEqual(aggregated, 15) aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Count, todays_ratings) self.assertEqual(aggregated, 4) + + def test_charfield_pks(self): + a1 = CharFieldGFK.objects.create(name='a1', content_object=self.apple) + a2 = CharFieldGFK.objects.create(name='a2', content_object=self.apple) + o1 = CharFieldGFK.objects.create(name='o1', content_object=self.orange) + + annotated_qs = generic_annotate(Food.objects.all(), CharFieldGFK.content_object, 'name', models.Count) + self.assertEqual(annotated_qs.count(), 2) + + food_a, food_b = annotated_qs + + self.assertEqual(food_b.score, 1) + self.assertEqual(food_b.name, 'orange') + + self.assertEqual(food_a.score, 2) + self.assertEqual(food_a.name, 'apple') + + aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK.content_object, 'name', models.Count) + self.assertEqual(aggregated, 3) diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 5da8892..40e33b1 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,117 +1,137 @@ import django from django.contrib.contenttypes.models import ContentType from django.db import connection, models def query_as_sql(query): if django.VERSION < (1, 2): return query.as_sql() else: return query.get_compiler(connection=connection).as_sql() def query_as_nested_sql(query): if django.VERSION < (1, 2): return query.as_nested_sql() else: return query.get_compiler(connection=connection).as_nested_sql() +def gfk_expression(qs_model, gfk_field): + # handle casting the GFK field if need be + qn = connection.ops.quote_name + + pk_field_type = qs_model._meta.pk.db_type() + gfk_field_type = gfk_field.model._meta.get_field(gfk_field.fk_field).db_type() + + if pk_field_type == 'serial': + pk_field_type = 'integer' + + if pk_field_type != gfk_field_type: + # cast the gfk to the pk type + gfk_expr = "CAST(%s AS %s)" % (qn(gfk_field.fk_field), pk_field_type) + else: + gfk_expr = qn(gfk_field.fk_field) # the object_id field on the GFK + + return gfk_expr + + def generic_annotate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, generic_queryset=None, desc=True): ordering = desc and '-score' or 'score' content_type = ContentType.objects.get_for_model(queryset.model) qn = connection.ops.quote_name # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match - qn(gfk_field.fk_field), # the object_id field on the GFK + gfk_expression(queryset.model, gfk_field), qn(queryset.model._meta.db_table), # the table and pk from the main qn(queryset.model._meta.pk.name) # part of the query ) - extra = """ + sql_template = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND - %s=%s.%s - """ % params + %s=%s.%s""" + + extra = sql_template % params if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_queryset.model._meta.db_table), qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] queryset = queryset.extra( select={'score': extra}, select_params=inner_query_params, order_by=[ordering] ) return queryset def generic_aggregate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, generic_queryset=None): content_type = ContentType.objects.get_for_model(queryset.model) queryset = queryset.values_list('pk') # just the pks query, query_params = query_as_nested_sql(queryset.query) qn = connection.ops.quote_name # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match - qn(gfk_field.fk_field), # the object_id field on the GFK + gfk_expression(queryset.model, gfk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_queryset is not None: generic_query = generic_queryset.values_list('pk').query inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0]
coleifer/django-generic-aggregation
dfa93241e71e7cfebcaf43f207bde9d15a8bd539
Adding support for Django 1.2 - verified with 1.1 and 1.2
diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 5a23e0f..5da8892 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,102 +1,117 @@ +import django from django.contrib.contenttypes.models import ContentType from django.db import connection, models +def query_as_sql(query): + if django.VERSION < (1, 2): + return query.as_sql() + else: + return query.get_compiler(connection=connection).as_sql() + +def query_as_nested_sql(query): + if django.VERSION < (1, 2): + return query.as_nested_sql() + else: + return query.get_compiler(connection=connection).as_nested_sql() + def generic_annotate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, generic_queryset=None, desc=True): ordering = desc and '-score' or 'score' content_type = ContentType.objects.get_for_model(queryset.model) qn = connection.ops.quote_name # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match qn(gfk_field.fk_field), # the object_id field on the GFK qn(queryset.model._meta.db_table), # the table and pk from the main qn(queryset.model._meta.pk.name) # part of the query ) extra = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s """ % params if generic_queryset is not None: - inner_query, inner_query_params = generic_queryset.values_list('pk').query.as_sql() + generic_query = generic_queryset.values_list('pk').query + inner_query, inner_query_params = query_as_sql(generic_query) inner_params = ( qn(generic_queryset.model._meta.db_table), qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s.%s IN (' % inner_params inner_end = ')' extra = extra + inner_start + inner_query + inner_end else: inner_query_params = [] queryset = queryset.extra( select={'score': extra}, select_params=inner_query_params, order_by=[ordering] ) return queryset def generic_aggregate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, generic_queryset=None): content_type = ContentType.objects.get_for_model(queryset.model) queryset = queryset.values_list('pk') # just the pks - query, query_params = queryset.query.as_nested_sql() + query, query_params = query_as_nested_sql(queryset.query) qn = connection.ops.quote_name # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match qn(gfk_field.fk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" if generic_queryset is not None: - inner_query, inner_query_params = generic_queryset.values_list('pk').query.as_sql() + generic_query = generic_queryset.values_list('pk').query + inner_query, inner_query_params = query_as_sql(generic_query) query_params += inner_query_params inner_params = ( qn(generic_queryset.model._meta.pk.name), ) inner_start = ' AND %s IN (' % inner_params inner_end = ')' query_end = query_end + inner_start + inner_query + inner_end # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly query = query_start + query + query_end cursor = connection.cursor() cursor.execute(query, query_params) row = cursor.fetchone() return row[0]