# AI News - WordPress Plugin

[![WordPress Plugin Version](https://img.shields.io/badge/WordPress-6.8%20Tested-blue.svg)](https://wordpress.org/plugins/ai-news/)
[![PHP Version](https://img.shields.io/badge/PHP-7.0%2B-purple.svg)](https://php.net/)
[![License](https://img.shields.io/badge/License-GPL%20v2%2B-green.svg)](https://www.gnu.org/licenses/gpl-2.0.html)

A professional WordPress plugin that automatically generates AI-powered news articles using Google's Gemini API. Features smart automation, multi-language support, AI-generated featured images, and comprehensive content management for modern WordPress sites.

## 🚀 Key Features

### AI Content Generation
- 🤖 **Google Gemini 2.0 Flash (experimental) Integration**: Professional-grade AI content generation
- 📰 **News-Quality Articles**: Structured content with headlines, introductions, and detailed paragraphs
- 🌍 **Multi-Language Support**: Generate content in English and Chinese with localized prompts
- 🎯 **16+ Tech Topics**: AI, ML, Blockchain, IoT, Cybersecurity, Quantum Computing, and more

### Smart Automation
- ⚡ **Dual Generation Modes**: Manual on-demand and automated scheduled generation
- 📅 **Flexible Scheduling**: Hourly, daily, weekly, or custom intervals (1 minute to 1 week)
- 🎲 **Smart Topic Rotation**: Automatically rotates between selected topics for diverse content
- 📊 **Batch Generation**: Create 1-10 articles per session with intelligent rate limiting

### Featured Image Generation
- 🖼️ **AI-Generated Images**: Automatically create relevant featured images using multiple AI services
- 🎨 **Multiple Services**: SiliconFlow, OpenAI DALL-E, DeepSeek, Unsplash, Pixabay support
- 🎭 **Style Customization**: News, Modern, Creative, Minimal image styles
- 📐 **Dimension Options**: 20+ preset sizes optimized for WordPress themes and social media

### Content Management
- 📝 **Advanced Prompt System**: Built-in templates with custom prompt creation and management
- 🔄 **Import/Export**: Backup and share prompt configurations
- 📋 **Generation History**: Complete tracking with edit/view links and statistics
- 🎛️ **Publishing Control**: Draft, publish, pending, or private post status options

### Professional Features
- 🔒 **WordPress Standards Compliant**: Built following WordPress security and coding standards
- 🛡️ **Enhanced Security**: CSRF protection, input sanitization, output escaping
- 📱 **Modern UI**: Responsive admin interface with tabbed navigation and real-time updates
- 🧪 **Built-in Testing**: API connection testing, image generation testing, and diagnostic tools

## Installation

1. Download the plugin files
2. Upload the `ainews.php` file to your WordPress `/wp-content/plugins/` directory
3. Activate the plugin through the 'Plugins' menu in WordPress
4. Navigate to 'AI News' in your WordPress admin menu

## Configuration

### 1. Get a Gemini API Key
- Visit [Google AI Studio](https://aistudio.google.com/app/apikey)
- Create a new API key
- Copy the key for use in the plugin

### 2. Plugin Settings
Access the plugin settings via **AI News** in your WordPress admin menu:

#### API Configuration
- **Gemini API Key**: Your Google Gemini API key (required)
- **Auto Publish**: Toggle to automatically publish generated articles or save as drafts
- **Post Category**: Select a category for generated articles (optional)

#### Generation Settings
- **Generation Schedule**: Choose how often to generate articles:
  - Every Minute (Testing Only)
  - Every 6 Hours
  - Daily
  - Weekly
- **Articles per Generation**: Number of articles to create each time (1-10)
- **News Topics**: Select multiple topics for article generation:
  - **Tech Frontiers**: AI, Machine Learning, Data Science, Deep Learning
  - **Applications**: AI Healthcare, Autonomous Vehicles, Smart Manufacturing, FinTech AI
  - **Emerging Tech**: Quantum Computing, Blockchain, IoT, VR/AR
  - **Industry Applications**: EdTech, Smart Cities, Cybersecurity, Cloud Computing
- **Content Language**: Choose between English or Chinese content
- **Prompt Template**: Select from available prompt templates:
  - Default AI News (supports {topic} variable)
  - Tech Industry News (professional business tone)
  - Research Breakthrough (scientific reporting style)
  - Custom Prompt (write your own prompt)

#### Custom Prompts
You can create custom prompts by:
1. Selecting "Custom Prompt" from the Prompt Template dropdown
2. Writing your own prompt in the text area that appears
3. Or editing the `prompts.json` file to add new template options

## Usage

### Manual Generation
1. Configure your API key and settings
2. Click "Test Connection" to verify your API setup
3. Click "Generate Article Now" to create an article immediately

### Automatic Generation
Once configured, the plugin will automatically generate articles according to your schedule settings. The system will randomly select from your chosen topics for each article generation. Check the "Next Generation" time in the plugin sidebar.

### Topic Selection
1. **Choose Topics**: Select one or more topics from the four categories
2. **Multiple Selection**: Use checkboxes to select multiple topics
3. **Quick Actions**: Use "Select All" or "Clear All" buttons
4. **Smart Rotation**: The system automatically rotates between selected topics

### Prompt Management
You can view and edit prompt templates using the Prompt Management section in the sidebar:

1. **Select Language**: Choose English or Chinese
2. **Select Template**: Pick from available prompt templates
3. **View Prompt**: Click "View Prompt" to see the current prompt content
4. **Edit Prompt**: Modify the prompt text in the textarea
5. **Save Changes**: Click "Save Changes" to update the prompt
6. **Cancel**: Click "Cancel" to discard changes

**Note**: Changes to prompts are saved directly to the `prompts.json` file and will affect future article generation.

## Generated Content Structure

Each AI-generated article includes:
- Compelling headline
- Brief introduction
- 2-3 paragraphs of detailed content
- Professional, news-appropriate formatting

## 🎨 Modern Plugin Experience

### Enhanced Plugin Information Display
- **Interactive Plugin Info Modal**: Click "Plugin Info" in the plugins page for detailed information
- **Real-time Statistics**: View generation counts, current version, and operational status
- **Quick Action Links**: Direct access to settings, documentation, support, and ratings
- **Responsive Design**: Optimized for desktop and mobile WordPress admin interfaces

### Professional Integration
- **WordPress.org Ready**: Fully compliant with WordPress.org plugin standards
- **Standard Plugin Headers**: Complete metadata including compatibility and requirements
- **Action Links**: Settings and Plugin Info links directly in the plugins list
- **Row Meta**: Documentation, Support, and Rate Plugin links for easy access

## 📊 Plugin Information

- **Version**: 1.2.7
- **Author**: Ausdata Science
- **License**: GPL v2 or later
- **Text Domain**: ai-news
- **WordPress Compatibility**: 4.0 - 6.8
- **PHP Requirement**: 7.0+
- **Plugin URI**: https://wordpress.org/plugins/ai-news/

## 🔧 Technical Details

### WordPress Standards Compliance
- **Security**: CSRF protection, nonce verification, input sanitization, output escaping
- **Performance**: Optimized database queries, efficient caching, rate limiting
- **File Operations**: Secure file handling restricted to wp-content/uploads directory
- **Code Quality**: Follows WordPress Coding Standards and best practices

### Plugin Architecture
```
ai-news/
├── ainews.php                 # Main plugin file
├── includes/
│   ├── ajax-handlers.php      # AJAX request handlers
│   ├── featured-image-generator.php  # AI image generation
│   └── plugin-info.php        # Plugin information display
├── prompts.json              # Prompt templates
├── logo.svg                  # Plugin icon
├── readme.txt               # WordPress.org readme
└── uninstall.php            # Clean uninstall script
```

### Constants Defined
- `AINEWS_VERSION`: Plugin version (1.2.7)
- `AINEWS_PLUGIN_DIR`: Plugin directory path
- `AINEWS_PLUGIN_URL`: Plugin URL

### Database Options
**Core Settings:**
- `ainews_api_key`: Gemini API key (encrypted storage)
- `ainews_language`: Content language (en/zh)
- `ainews_post_status`: Default post status
- `ainews_post_category`: Default category assignment
- `ainews_selected_topics`: Selected topics (comma-separated)

**Automation Settings:**
- `ainews_schedule_interval`: Generation frequency
- `ainews_article_count`: Articles per generation batch
- `ainews_auto_enabled`: Auto generation status
- `ainews_schedule_paused`: Pause status
- `ainews_auto_generated_count`: Total generated articles

**Featured Image Settings:**
- `ainews_auto_featured_image`: Auto image generation toggle
- `ainews_image_generation_service`: Selected AI service
- `ainews_image_style`: Image style preference
- `ainews_image_dimensions`: Image size settings
- API keys for various image services

### File Management
- **Prompt Storage**: wp-content/uploads/ainews/prompts.json (user-writable)
- **Fallback Prevention**: No fallback to plugin directory (WordPress.org compliant)
- **Secure Operations**: All file operations use WordPress filesystem API

### Scheduled Events
- **Hook**: `ainews_generate_articles`
- **Custom Intervals**: Support for custom cron schedules
- **Conflict Prevention**: Automatic cleanup and rescheduling

## Requirements

- WordPress 4.0 or higher
- PHP 7.0 or higher
- Active internet connection for API calls
- Valid Google Gemini API key

## API Usage

The plugin uses Google's Gemini 2.0 Flash experimental model for content generation via the v1beta API. Each article generation makes one API call with appropriate rate limiting (2-second delays between multiple generations).

## Security Features

- Nonce verification for AJAX requests
- API key stored securely in WordPress options
- Input sanitization and validation
- Prevents direct file access

## Troubleshooting

### Common Issues

1. **"API key is not set" error**
   - Ensure you've entered your Gemini API key in the settings
   - Verify the key is correct and has appropriate permissions

2. **"Connection failed" error**
   - Check your internet connection
   - Verify your API key is valid and active
   - Ensure your server can make outbound HTTPS requests

3. **Articles not generating automatically**
   - Check that WordPress cron is working on your site
   - Verify your schedule settings are saved correctly
   - Check the "Next Generation" time in the plugin sidebar

4. **Custom prompts not working**
   - Ensure the `prompts.json` file exists in the plugin directory
   - Check that the JSON format is valid
   - Verify your custom prompt text is not empty

## Uninstallation

When you deactivate or uninstall the plugin:
- All scheduled events are cleared
- Plugin options remain in database (deactivation)
- All plugin data is removed from database (uninstall)

## 🌟 Recent Updates

### v1.2.7 - Enhanced Security & WordPress.org Compliance
- ✅ **JavaScript Security**: Fixed nonce escaping in JavaScript contexts using esc_js()
- ✅ **CSS Attribute Security**: Enhanced escaping for CSS style attributes using esc_attr()
- ✅ **Context-Aware Escaping**: Uses appropriate escaping functions (esc_html, esc_attr, esc_url, esc_js) for each context
- ✅ **Advanced XSS Prevention**: Comprehensive protection against cross-site scripting in all contexts

### v1.2.6 - WordPress.org Security Audit Compliance
- ✅ **Nonce Security**: Fixed all wp_verify_nonce calls with proper input sanitization
- ✅ **Data Sanitization**: Enhanced POST/GET data sanitization throughout the plugin
- ✅ **Output Escaping**: Improved escaping for all error messages and user-facing text
- ✅ **Security Audit**: Full compliance with WordPress.org plugin review requirements
- ✅ **Code Quality**: Enhanced following WordPress coding standards

### Security Improvements (v1.2.6 & v1.2.7)
- 🔒 **Enhanced Nonce Verification**: All nonce checks now use sanitize_text_field(wp_unslash())
- 🛡️ **Input Validation**: Comprehensive sanitization of all user inputs
- 🚫 **XSS Prevention**: Proper output escaping for all dynamic content including JavaScript and CSS
- 📋 **Audit Ready**: Plugin now passes WordPress.org security review standards

## 📞 Support & Resources

### Official Links
- **WordPress.org Plugin Page**: [https://wordpress.org/plugins/ai-news/](https://wordpress.org/plugins/ai-news/)

### Getting Help
1. **Check Documentation**: Comprehensive guides and tutorials
2. **Search Support Forum**: Common issues and solutions
3. **Submit Support Request**: For technical assistance
4. **Rate the Plugin**: Help others discover AI News

### External Services Used
- **Google Gemini API**: AI content generation (required)
- **SiliconFlow API**: AI image generation (optional)
- **OpenAI API**: Image generation and prompt optimization (optional)
- **DeepSeek API**: Prompt optimization (optional)
- **Unsplash API**: Stock photography (optional)
- **Pixabay API**: Free stock images (optional)

*Note: Only Google Gemini API is required. All image services are optional.*

## 📄 License

This plugin is licensed under the **GPL v2 or later**.

```
AI News WordPress Plugin
Copyright (C) 2024 Ausdata Science

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
```

---

## ⚠️ Important Notes

### Content Review
This plugin generates AI content. Please review all generated articles before publication to ensure they meet your quality standards and comply with your site's content policies.

### API Usage
The plugin uses external AI services. Please review the terms of service and privacy policies of any services you choose to use:
- [Google Gemini API Terms](https://ai.google.dev/gemini-api/terms)
- [OpenAI Terms](https://openai.com/terms/)
- [SiliconFlow Terms](https://siliconflow.cn/terms)

### Performance Considerations
- Enable caching for better performance with frequent generation
- Monitor API usage to stay within service limits
- Consider server resources when using automated generation

**Ready to transform your WordPress site with AI-powered content? Install AI News today!** 🚀