<?php
class Admin_ServicesController extends Zend_Controller_Action 
{
	
	public function init()
	{
	    $this->view->addHelperPath('library/Atmail/View/Helper/', 'Atmail_View_Helper');
		$this->_helper->pluginCall('initAdminController', $this);
		 
		$this->request  = $this->getRequest();
		$this->requestParams = $this->request->getParams();
		
		$this->view->baseUrl = $this->request->getBaseUrl();
		$this->view->appBaseUrl = $this->request->getBaseUrl() . (strpos($this->request->getBaseUrl(),'index.php')?'':DIRECTORY_SEPARATOR . 'index.php');
		$this->view->siteBaseUrl = Zend_Registry::get('siteBaseUrl');
		$this->view->moduleBaseUrl = $this->view->appBaseUrl . ($this->request->module == 'default'?'':DIRECTORY_SEPARATOR . $this->request->module);
		$this->view->global = Zend_Registry::get('config')->global;
		$this->view->exim = Zend_Registry::get('config')->exim;
		$this->view->archiveVault = Zend_Registry::get('config')->archiveVault;
		$this->dbAdapter = Zend_Registry::get('dbAdapter');
		$this->dbTables = new dbTables();
		
		require_once 'application/models/admin.php';
		$this->admin = new admin();
		
		// check is an XML request or not only allow index to be rendered normally (i.e. full page load)
		if ($this->request->action == 'index' )
			return;
			
		if( !isset($this->view->errors) )
			$this->view->errors = array();
		if( !isset($this->view->notices) )    
			$this->view->notices = array();
		if( !isset($this->view->jsonIdsToRender) )    
			$this->view->jsonIdsToRender = array();
		require_once 'library/jQuery/jQuery.php';
		
	}
	
	public function preDispatch() 
	{
		
		// Check the session is active, otherwise redirect to the login page
		$this->view->userData = $this->admin->getCurrentAdminData();
		
		if( empty($this->view->userData) ) 
		{

			$this->_forward( 'timeout', 'index', 'default' );
			return;			

		}
		
		Atmail_Locale::setupLocaleAndTranslation( $this->view->userData['Language'] );
		
	}
	
	public function indexAction() 
	{
		
	}

	public function smtpAction() 
	{
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');		
		}
		
		// Before show DKIM, is it supported?
		$this->view->exim['dkim_installed'] = `/usr/local/atmail/mailserver/bin/exim -dd 2>&1 | grep "Support for" | grep DKIM`;
		
		if(file_exists("/usr/local/atmail/mailserver/ssl/certs/dkim.pem")) 
		{
		
			$this->view->exim['dkim_message'] = file_get_contents("/usr/local/atmail/mailserver/ssl/certs/dkim.pem");
			$this->view->exim['dkim_message'] = str_replace('-----BEGIN PUBLIC KEY-----', '', $this->view->exim['dkim_message']);
			$this->view->exim['dkim_message'] = str_replace('-----END PUBLIC KEY-----', '', $this->view->exim['dkim_message']);
			$this->view->exim['dkim_message'] = str_replace("\n", '', $this->view->exim['dkim_message']);
			$this->view->exim['dkim_message'] = str_replace("\r", '', $this->view->exim['dkim_message']);

			if(!$this->view->exim['dkim_message'])
			{
			
				$this->view->exim['dkim_message'] = 'Could not generate a DKIM key.'; 
				$this->view->exim['dkim_enable_outbound'] = 0;
			
			}
			else
			{
				$this->view->exim['dkim_message'] = 'mail._domainkey.' . $this->view->exim['dkim_domain'] . '. IN TXT "v=DKIM1; g=*; k=rsa; p=' . $this->view->exim['dkim_message'] . '"';			
			}
		
		}

	}
	
	public function smtpsaveAction() 
	{		
		
		if( $this->view->global['demo'] == 1 )
			throw new Exception('Disabled in online demo');
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');

        if( $this->request->fields['dkim_enable_outbound'] && $this->request->fields['dkim_domain'] == '' )
        {
            throw new Exception('Please enter the primary domain used for the DKIM header.');

        }

		// Before we save DKIM, is it supported?
		$dkim_installed = `/usr/local/atmail/mailserver/bin/exim -dd 2>&1 | grep "Support for" | grep DKIM`;
		
		if( !empty($this->request->fields['dkim_enable_outbound']) && $this->request->fields['dkim_enable_outbound'] != 0 && $dkim_installed )
		{

			// DKIM key creation
			if(!file_exists('/usr/local/atmail/mailserver/ssl/private/dkim.key') && file_exists("/usr/bin/openssl"))
			{

		    	system("/usr/bin/openssl genrsa -out /usr/local/atmail/mailserver/ssl/private/dkim.key 1024");
		    	system("/usr/bin/openssl rsa -in /usr/local/atmail/mailserver/ssl/private/dkim.key -out /usr/local/atmail/mailserver/ssl/certs/dkim.pem -pubout -outform PEM");

			}

		}

		try 
		{
			
			require_once 'application/models/config.php';
			config::save('exim', $this->request->fields);
		    config::publishServerConfigFiles('exim');
			if( file_exists("/usr/local/atmail/mailserver/bin/atmail-services-restart") ) //is appliance
			{
				exec("/usr/local/atmail/mailserver/bin/atmail-services-restart");
				jQuery::addMessage( $this->view->translate('The settings have been updated. Atmail appliance services have been restarted.') );
			}
			else
				jQuery::addMessage( $this->view->translate('The settings have been updated, however Atmail services must be restarted before changes take effect.') );
		 
		}
		catch( Exception $e ) 
		{
			
			jQuery::addError( $this->view->translate('Failed saving config:') . ' ' . $e->getMessage());
			
		}
		
		$this->render('global/jsonresponse', null, true);
		
	}
	public function webmailAction()
	{

		$this->view->global = Zend_Registry::get('config')->global;
		$groupDefaultResult = $this->admin->groupGet('default');

		if( $groupDefaultResult['status'] == 'success' )
		{
			$this->view->groupDefault = $groupDefaultResult['response']['results'];
		}
		else
		{
			throw new Exception( $groupDefaultResult['response']['message'] );
		}
	}

	public function webmailsaveAction()
	{

		if( $this->view->global['demo'] == 1 )
		{

			throw new Exception('Disabled in online demo');

		}

			// Verify the submitted data// Verify the submitted data
		try
		{
			//pull out groupDefault data before pushing rest to Config
			$defaultSettings = array();
			if( array_key_exists('Webmail', $this->request->fields) )
			{

				$defaultSettings = array('Webmail' => $this->request->fields['Webmail']);
				unset( $this->request->fields['Webmail'] );
				$this->admin->groupUpdate('default', $defaultSettings);

			}

			config::save('global', $this->request->fields);
			jQuery::addMessage( $this->view->translate('Settings saved.'));

		}
		catch (Zend_Exception $e)
		{
			$error = $e->getMessage();
			jQuery::addError('Failed saving config: ' . $error);
		}

		$this->render('global/jsonresponse', null, true);

	}

	// POP3 IMAP
	
    public function pop3imapAction() 
	{
        
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			
			throw new Exception('MasterAdmin rights required.');
			
		}
		
		$this->view->dovecot = Zend_Registry::get('config')->dovecot;
		$groupDefaultResult = $this->admin->groupGet('default');
		if( $groupDefaultResult['status'] == 'success' )
		{
			$this->view->groupDefault = $groupDefaultResult['response']['results'];
		}                                
		else
		{
			throw new Exception( $groupDefaultResult['response']['message'] );	
		}
		

	}

    public function pop3imapsaveAction() 
	{
        if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');
		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
		$this->request  = $this->getRequest();

		try 
		{                                       
			//pull out fields that may be saved alsewhere like Groups.POP3Support
			$defaultSettings = array();
			if( array_key_exists('POP3Support', $this->request->fields) )
			{
				$defaultSettings['POP3Support'] = $this->request->fields['POP3Support'];
				unset( $this->request->fields['POP3Support'] );
			}
			if( array_key_exists('IMAPSupport', $this->request->fields) )
			{
				$defaultSettings['IMAPSupport'] = $this->request->fields['IMAPSupport'];
				unset( $this->request->fields['IMAPSupport'] );
			}
			if( count($defaultSettings) > 0 )
			{
				$this->admin->groupUpdate('default', $defaultSettings);
			}
			
			require_once 'application/models/config.php';
            config::save('dovecot', $this->request->fields);
            config::publishServerConfigFiles('dovecot');
			if( file_exists("/usr/local/atmail/mailserver/bin/atmail-services-restart") ) //is appliance
			{
				exec("/usr/local/atmail/mailserver/bin/atmail-services-restart");
				jQuery::addMessage( $this->view->translate('The settings have been updated. Atmail appliance services have been restarted.') );
			}
			else
				jQuery::addMessage( $this->view->translate('The settings have been updated, however Atmail services must be restarted before changes take effect.') );

        }
		catch( Exception $e ) 
		{  
			jQuery::addMessage('Failed saving config: ' . $e->getMessage());
        }

        $this->render('global/jsonresponse', null, true);

    }

    public function spamAction() 
	{

        if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
		if ($this->view->global['install_type'] == "server")
		{
			$this->view->reg = Zend_Registry::get('config')->reg;
					
			if(time() > strtotime($this->view->reg['expiry'])) {
				$this->view->licenseExpired = "Auto-Update Anti-Spam " . $this->admin->getLicenseStatusExpired();
			}
			
			$this->view->spamTokens = $this->dbAdapter->fetchOne("select count(id) from bayes_token where spam_count > 0");
			$this->view->nonspamTokens = $this->dbAdapter->fetchOne("select count(id) from bayes_token where ham_count > 0");
			$this->view->awlTokens = $this->dbAdapter->fetchOne("select count(email) from awl");

			$this->view->spamSettings = users::getSpamSettings('GLOBAL');
		}
		
    }

    public function spamsaveAction() 
	{
        if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');
		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');		
		}
		
		try 
		{
                require_once 'application/models/config.php';
                
                if ($this->view->config['install_type'] != "server")
                {
					config::save('global', $this->request->fields);
					jQuery::addMessage( $this->view->translate('The settings have been updated.') );
				}
				else
				{
					config::save('exim', $this->request->fields);
					
					$restartServices = 0;
					
					// List of settings which require Spamassassin reload
					foreach(array('filter_sa_enable', 'filter_trusted_networks', 'filter_uridns_support', 'filter_uridnsbl_servers', 'filter_spf_support', 'filter_awl_support', 'filter_use_bayes') as $key)
					{	
						if($this->request->fields[$key] != $this->view->exim[$key])
						{
							$restartServices = 1;
						}
					}				
					
					config::publishServerConfigFiles('spamassassin');
					config::publishServerConfigFiles('exim');

					if( empty($restartServices) )
						jQuery::addMessage( $this->view->translate('The settings have been updated.') );
					else
					{
					
						if( file_exists("/usr/local/atmail/mailserver/bin/atmail-services-restart") ) //is appliance
						{
							exec("/usr/local/atmail/mailserver/bin/atmail-services-restart");
							jQuery::addMessage( $this->view->translate('The settings have been updated. Atmail appliance services have been restarted.') );
						}
						else
							jQuery::addMessage( $this->view->translate('The settings have been updated, however Atmail services must be restarted before changes take effect.') );
					
					}
					
					// Update the global whitelist/blacklist
					$SpamSettings = array(
						'whitelist_from' => $this->requestParams['whitelist_from'],
						'blacklist_from' => $this->requestParams['blacklist_from']
					);

					users::saveSpamSettings('GLOBAL', $SpamSettings);
				}

        } 
		catch( Exception $e ) 
		{

                jQuery::addMessage('Failed saving config: ' . $e->getMessage());

        }

        $this->render('global/jsonresponse', null, true);

    }

	
    public function avAction() 
	{
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');
		
		$stats = stat("/usr/local/atmail/av/share/clamav/daily.cld");
		if( $stats === false )
			$this->view->signatureDate = 'Never';
		else
			$this->view->signatureDate = strftime("%c", $stats['mtime']);
		
    }

    public function avsaveAction() 
	{
	
		if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');
		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');	
		}

        try 
		{
        
        	require_once 'application/models/config.php';
            config::save('exim', $this->request->fields);
            config::publishServerConfigFiles('exim');
			if( file_exists("/usr/local/atmail/mailserver/bin/atmail-services-restart") ) //is appliance
			{
				exec("/usr/local/atmail/mailserver/bin/atmail-services-restart");
				jQuery::addMessage( $this->view->translate('The settings have been updated. Atmail appliance services have been restarted.') );
			}
			else
				jQuery::addMessage( $this->view->translate('The settings have been updated, however Atmail services must be restarted before changes take effect.') );
			

        }
		catch( Exception $e ) 
		{

                jQuery::addMessage('Failed saving config: ' . $e->getMessage());

        }

        $this->render('global/jsonresponse', null, true);

    }

	public function davAction() 
	{
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
		$groupDefaultResult = $this->admin->groupGet('default');
		if( $groupDefaultResult['status'] == 'success' )
		{
			$this->view->groupDefault = $groupDefaultResult['response']['results'];
		}                               
		else
		{
			throw new Exception( $groupDefaultResult['response']['message'] );
		}
		
	}

	public function davsaveAction()
	{        
		
		if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');
		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
		try 
		{
			
			//pull out groupDefault data before pushing rest to Config
			
			$defaultSettings = array();
            $settings = array('Calendar','CalDAVServer','CardDAVServer','Carddav','WebDAVRootUrl');
            foreach($settings as $setting) {
                if (!isset($this->request->fields[$setting])) {
                    continue;
                }

                $defaultSettings[$setting] = $this->request->fields[$setting];
                unset($this->request->fields[$setting]);
                
            }

            $this->admin->groupUpdate('default', $defaultSettings);
			
			jQuery::addMessage( $this->view->translate('The settings have been updated.') );
			
		} 
		catch( Exception $e ) 
		{
			
			jQuery::addMessage('Failed saving config: ' . $e->getMessage());
			
		}		
		$this->render('global/jsonresponse', null, true);
		
	}
	
	public function filesstorageAction() 
	{
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');
		
		$groupDefaultResult = $this->admin->groupGet('default');
		if( $groupDefaultResult['status'] == 'success' )
			$this->view->groupDefault = $groupDefaultResult['response']['results'];
		else
			throw new Exception( $groupDefaultResult['response']['message'] );
		
	}

	public function filesstoragesaveAction()
	{        
		
		if( $this->view->global['demo'] == 1 )
			throw new Exception('Disabled in online demo');
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');
		
		try 
		{
			
			//pull out groupDefault data before pushing rest to Config
			
			$defaultSettings = array();
			$settings = array('WebDavEnabled','StorageTabEnabled','FileSharingEnabled');
			foreach($settings as $setting) 
			{
				
				if( !isset($this->request->fields[$setting]) )
					continue;
				$defaultSettings[$setting] = $this->request->fields[$setting];
				unset($this->request->fields[$setting]);

			}
			$this->admin->groupUpdate('default', $defaultSettings);
			jQuery::addMessage( $this->view->translate('The settings have been updated.') );
			
		} 
		catch( Exception $e ) 
		{
			
			jQuery::addMessage('Failed saving config: ' . $e->getMessage());
			
		}		
		$this->render('global/jsonresponse', null, true);
		
	}

	public function activesyncAction() 
	{
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');
		                                                                                                                            
		$this->view->pushReady = function_exists("imap_open") && file_exists(APP_ROOT . "push/index.php");
		$groupDefaultResult = $this->admin->groupGet('default');
		if( $groupDefaultResult['status'] == 'success' )
			$this->view->groupDefault = $groupDefaultResult['response']['results'];
		else
			throw new Exception( $groupDefaultResult['response']['message'] );
		
		$expiry = Zend_Registry::get('config')->reg['expiry'];
		if(time() > strtotime($expiry) && !empty($expiry)) { //TODO: calculate off last PRO expiry (more accurate)
		    $this->view->licenseExpired = 1;
		    $this->view->expiry = $expiry;
		}

	}

	public function activesyncsaveAction()
	{        
		
		if( $this->view->global['demo'] == 1 )
			throw new Exception('Disabled in online demo');
		
		if( $this->view->userData['UMasterAdmin'] != '1' )
			throw new Exception('MasterAdmin rights required.');
				
		if( array_key_exists('PushSupport', $this->request->fields) )
			$result = $this->admin->groupUpdate('default', array('PushSupport' => $this->request->fields['PushSupport']) );
			
		require_once 'application/models/config.php';
		if( isset($this->request->global) )
			config::save( 'global', $this->request->global);
		
		if( $result['status'] == 'failed' )
		{
			if( isset($result['response']['errorCode']) && $result['response']['errorCode'] == '1' )
				jQuery::addError( $this->view->translate('Failed saving config:') . ' ' . $this->view->translate('Invalid license') );
			else
				jQuery::addError( $this->view->translate('Failed saving config:') . ' ' . $result['response']['message'] );
		}
		else
			jQuery::addMessage( $this->view->translate('The settings have been updated.') );
		$this->render('global/jsonresponse', null, true);
		
	}

	public function archivevaultAction() 
	{
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');		
		}
		
	    $this->licenseType = strtoupper(chr(Zend_Registry::get('w4m70Yt0hYrduM2r2lUrIuY0zgKG4A3vvftl4NbbCWfW')));
	    
		$this->view->archivevault = 1;
		
		
		// Does the SMTP server connect?
		try 
		{
			
			if(!empty($this->view->exim['smtp_archivevault_enable'])) 
			{
				
				$tr = new Zend_Mail_Protocol_Smtp($this->view->exim['smtp_archivevault_hostname'], $this->view->exim['smtp_archivevault_port']);
				$tr->connect();
				$this->view->archivevaultStatus = 'Online';
				
			} 
			else
			{
				$this->view->archivevaultStatus = 'Unavailable';
			}
		} 
		catch( Exception $e ) 
		{
			$this->view->archivevaultStatus = 'Could not connect to specified server';	
		}
		// Try connect to ArchiveVault API service
		if( isset($this->view->exim['smtp_archivevault_enable']) && $this->view->exim['smtp_archivevault_enable'] == '1') 
		{
		    
			$configArchiveVault = Zend_Registry::get('config')->archiveVault;
		
			if(!empty($configArchiveVault['archiveVaultURL'])) 
			{
				$args = archiveVaultAPIClient::splitUrl( $configArchiveVault['archiveVaultURL'] );
				$args['apiKey'] = $configArchiveVault['archiveVaultAPIKey'];
				$archiveVaultAPIClient = new archiveVaultAPIClient( $args );
				$result = $archiveVaultAPIClient->validateSettings();
			}
			
			if( $result['status'] == 'failed' )
			{

				jQuery::addError('Failed adding new Subadmin user to ArchiveVault: ' . $result['response']['message']); 
				$errorYet = true;

			}
			Zend_Registry::get('log')->debug( "\n" . print_r($result, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$result \n");
			
			if( isset($result['status']) && $result['status'] == 'success' )
				{
				$this->view->archiveVaultAPIStatus = 'API Service appears to be online and API Key validated successfully';
			}
			else
			{
				$this->view->archiveVaultAPIStatus = 'API Service appears to be online but API Key authentication failed: ' . $result['response']['message'];	
			}
			
		}
		else
		{
  				$this->view->archiveVaultAPIStatus = 'Not enabled';
		}

	}

	public function archivevaultsaveAction()
	{        

		if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');		
		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
		$fields = $this->request->fields;
		
		//first check if can successfully connect the the server with these details so that if a fatal error is thrown because user entered bad details then those details are not saved
        //remove the archivevault fields and save them to Config::archivevault
		$archiveVaultFields = array();
		$archiveVaultFields['archiveVaultURL'] 	= $fields['archiveVaultURL'];
		$archiveVaultFields['archiveVaultAPIKey'] 	= $fields['archiveVaultAPIKey'];
		//cleanup path if missing //
		//unset these fields so they dont get bulk saved in Config.exim
		unset($fields['archiveVaultURL']);
		unset($fields['archiveVaultAPIKey']);
		
		// Try connect to ArchiveVault API service
		if( isset($fields['smtp_archivevault_enable']) && $fields['smtp_archivevault_enable'] == '1') 
		{

			$urlArray = archiveVaultAPIClient::splitUrl($archiveVaultFields['archiveVaultURL']);
	        $archiveVaultFields['archiveVaultURL'] = $urlArray['url'];
			$urlArray['apiKey'] = $archiveVaultFields['archiveVaultAPIKey'];
			$archiveVaultAPIClient = new archiveVaultAPIClient( $urlArray );
		    $result = $archiveVaultAPIClient->validateSettings();
			$archiveVaultAPIStatus = $result['response']['message'];
			
		}
		else
		{	
			$archiveVaultAPIStatus = 'Not enabled';
		}
		jQuery('#archivevaultStatus', '#Archive_Vault')->html( $archiveVaultAPIStatus );
		
		
		//force hostname to ip address if localhost supplied
		if( $fields['smtp_archivevault_hostname'] == 'localhost' )
		{	
			$fields['smtp_archivevault_hostname'] = '127.0.0.1';			
		}

		try 
		{
			
			require_once 'application/models/config.php';
			
			config::save('archiveVault', $archiveVaultFields);
			config::save('exim', $fields);
		    config::publishServerConfigFiles('exim');
		 
			// Create the MAIL_TAP_HOST file with the localhost domain ( For exim router )
			file_put_contents("/usr/local/atmail/mailserver/MAIL_TAP_HOST", "localhost");

		}
		catch( Exception $e ) 
		{
			
			jQuery::addError( $this->view->translate('Failed saving config:') . ' ' . $e->getMessage());
			
		}
        
		// Does the SMTP server connect?
		try 
		{
			
			if(!empty($this->request->fields['smtp_archivevault_enable'])) 
			{
			
				$tr = new Zend_Mail_Protocol_Smtp($this->request->fields['smtp_archivevault_hostname'], $this->request->fields['smtp_archivevault_port']);
				$tr->connect();
				jQuery::evalScript("$('#archiveVaultAPIStatus', '#Archive_Vault').html('Online');");
			} 
			else
			{
				jQuery::evalScript("$('#archiveVaultAPIStatus', '#Archive_Vault').html('Unavailable');");
			}
			jQuery::addMessage( $this->view->translate('The settings have been updated.') );
		} 
		catch( Exception $e ) 
		{
			$this->view->archivevaultStatus = 'Could not connect to specified server';
			jQuery::addError( $this->view->translate('Cannot connect via the specified hostname/port. Please try again') . ' ' . $e->getMessage());
			jQuery::evalScript("$('#archiveVaultAPIStatus', '#Archive_Vault').html('Could not connect to specified server');");
		}
		
		//push possibly updated fields out again
		jQuery('#smtp_archivevault_hostname', '#Archive_Vault')->attr('value', $fields['smtp_archivevault_hostname']);
		jQuery('#archiveVaultURL', '#Archive_Vault')->attr('value', $urlArray['url']);
		
		$this->render('global/jsonresponse', null, true);
		
	}

	public function aliasesAction() 
	{

		if( $this->view->userData['UMasterAdmin'] != '1' && ($this->view->userData['UAlias'] != 1))
		{
			throw new Exception('MasterAdmin rights required.');
		}


	}
	
	public function aliascreateAction() 
	{
		
		if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');			
		}
		
		$this->requestParams['AliasTo'] = $this->requestParams['AliasTo' . $this->requestParams['aliasType']];
		$this->requestParams['AliasName'] = $this->requestParams['AliasName' . $this->requestParams['aliasType']];
		
		$result = $this->admin->aliasesCreate($this->requestParams);
        
		// User could not be created
		if( $result['status'] == 'failed' ) 
		{
			
			jQuery::evalScript("$('#AliasTo" . $this->requestParams['aliasType'] . "',  '#service_aliases').focus();");
			jQuery::evalScript("$('#AliasTo" . $this->requestParams['aliasType'] . "',  '#service_aliases').select();");
			
			jQuery::addError( addslashes((string)$result['response']['message']) );
			
			
		} 
		else 
		{
			
			// Alias was successfully created
			//Reset input fields
			jQuery::evalScript("$('#AliasTo" . $this->requestParams['aliasType'] . "',  '#service_aliases').val('');");
			jQuery::evalScript("$('#AliasName" . $this->requestParams['aliasType'] . "',  '#service_aliases').val('');");

			//jQuery::addMessage( $this->view->translate('Alias successfully created') );
			jQuery::evalScript("$.php('" . $this->view->moduleBaseUrl . "/services/aliaslist');");

		}
		
		$this->render('global/jsonresponse', null, true);                                                             		
	}
	
	
	public function aliaslistAction() 
	{
	
		if( $this->view->userData['UMasterAdmin'] != '1' && ($this->view->userData['UAlias'] != 1))
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
		$this->view->aliaseslist = $this->admin->aliaseslist($this->requestParams);
        
		$this->view->jsonIdsToRender['alias-table'] = 'services/listaliases.phtml';
		$this->render('global/jsonresponse', null, true);
		
	}

	public function aliasdeleteAction() 
	{
		
		if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');
		}
		
		$ids = $this->requestParams['id'];
		
		if( is_array($ids) ) 
		{

			foreach($ids as $id) 
			{
				
				$result = $this->admin->aliasesDelete($id);
				
				if( $result['status'] == 'success' )
				{
					jquery::evalScript("$('#checkEntry[value=$id]', '#service_aliases').parent().parent().fadeOut();");
				}
			}
		}
		else
		{
			
			$result = $this->admin->aliasesDelete( $ids );			
			if( $result['status'] == 'success' || strpos($result['response']['message'], 'does not exist') !== false )
			{
 				jquery::evalScript("$('#checkEntry[value=$ids]', '#service_aliases').parent().parent().fadeOut();");
			}
			
		}
		
		$this->render('global/jsonresponse', null, true);                                                             		
	
	}

	public function mailrelayAction() 
	{

		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
	}

	public function mailrelaylistAction() 
	{
	
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');			
		}
		
		$this->view->mailrelay = $this->dbAdapter->select()
												 ->from('MailRelay')
												 ->where("IPaddress like " . $this->dbAdapter->quote('%' . $this->requestParams['filter'] . '%'))
												 ->order('DateAdded desc')
												 ->query()
												 ->fetchAll();

		$this->view->jsonIdsToRender['relay-table'] = 'services/listrelay.phtml';
		$this->render('global/jsonresponse', null, true);
		
	}

	public function mailrelaysaveAction() 
	{
	
		if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');	
		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');			
		}
		
		if(!preg_match('/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\/\d\d)?\b/', $this->requestParams['IPaddress'])) 
		{

			jQuery::evalScript("$('#IPaddress',  '#service_relay').focus();");
			jQuery::addError( addslashes('Please specify a valid IP address or netblock') );			
			$this->render('global/jsonresponse', null, true);
			return;
			
		}
		else
		{
			$result = $this->admin->mailrelayCreate($this->requestParams);
		}

		// User could not be created
		if( $result['status'] == 'failed' )
		{
			
			jQuery::addError( addslashes((string)$result['response']['message']) );			
			jQuery::evalScript("$('#IPaddress',  '#service_relay').focus();");
						
		}
		else
		{
			
			// Alias was successfully created
			jQuery::evalScript("$('#IPaddress',  '#service_relay').val('');");

			//jQuery::addMessage( $this->view->translate('IP successfully created') );
			jQuery::evalScript("$.php('" . $this->view->moduleBaseUrl . "/services/mailrelaylist');");

		}
		
		$this->render('global/jsonresponse', null, true);
	}

	public function mailrelaydeleteAction() 
	{
		
		if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');
		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
		$ids = $this->requestParams['id'];
		
		if( is_array($ids) ) 
			{
			foreach($ids as $id) 
			{
				$result = $this->admin->mailrelayDelete($id);
				if($result['status'] == 'success')
				{
					jquery::evalScript("$('#checkEntry[value=$id]', '#service_relay').parent().parent().fadeOut();");
				}
			}	
		}
		else
		{
			$result = $this->admin->mailrelayDelete( $this->requestParams['id'] );			
		}

		$this->render('global/jsonresponse', null, true);

	}
	
	public function massmailAction()
	{
		
		$this->view->requestParams = $this->requestParams;
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');
		$this->view->domains = domains::getList();
		$this->view->groups = groups::getList();

	}
	
	public function massmailcomposeAction()
	{

		//Zend_Registry::get('log')->debug( "\n" . print_r($this->requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$this->requestParams \n");
		$this->view->requestParams = $this->requestParams;
		//take filter criteria and build address count to show in composer screen with link to see recipients for now  in a popup
		$addresses = $this->getmassmailList($this->view->requestParams);
		$this->view->matchedUserCount = count($addresses);
		//Zend_Registry::get('log')->debug( "\n" . print_r($addresses, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$addresses \n");

		$this->view->jsonIdsToRender['Mass_Mail #primary_content_inner'] = 'services/massmailcompose.phtml';
		jQuery('#Mass_Mail #primary_header')->append('<div id="back_button" class="buttonGeneric"><span class="stronglastword">' .  $this->view->translate('Back') . '</span></div>');
		$this->render('global/jsonresponse', null, true);
		
	}
	
	public function massmailviewlistAction()
	{
		
		if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');
		}
		
		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
		//Zend_Registry::get('log')->debug( "\n" . print_r($this->requestParams, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$this->requestParams \n");
		$this->view->requestParams = $this->requestParams;
		//take filter criteria and build address count to show in composer screen with link to see recipients for now  in a popup
		$this->view->addresses = $this->getmassmailList($this->view->requestParams);
		
		
	}
	
	public function massmailsendAction()
	{

		if( $this->view->global['demo'] == 1 )
		{
			throw new Exception('Disabled in online demo');
		}

		if( $this->view->userData['UMasterAdmin'] != '1')
		{
			throw new Exception('MasterAdmin rights required.');
		}
		
		$transportClass = $this->_helper->pluginCall("smtpTransportClass");
        if( empty($transportClass) )
            $transportClass = "Atmail_Mail_Transport_Smtp";
        
        // Decide if to enable SMTP auth or regular connection
		$config = array();
		if( !empty($this->_globalConfig['smtpauth_username']) && !empty($this->_globalConfig['smtpauth_password']) && !empty($this->_globalConfig['smtp_auth']) )
			$config = array( 'auth' => 'login', 'username' => $this->_globalConfig['smtpauth_username'], 'password' => $this->_globalConfig['smtpauth_password'] );
		if(PHP_OS == "Darwin")
			$config['name'] = php_uname('n');
		
		$adminEmail = $this->view->global['admin_email'];
        
		$newMessage = new Atmail_Mail( 'UTF-8' );
        $newMessage->setMessageId();
		$newMessage->setFrom( $adminEmail, $this->view->translate('Admin') );
		$newMessage->addHeader('X-Mailer', "Atmail Mass Mail " . $this->view->global['version'] );
		
		// Set the subject and misc fields
		$emailSubject = html_entity_decode( $this->requestParams['emailSubject'] , ENT_QUOTES, 'UTF-8' );
		$newMessage->setSubject( $emailSubject );
		$newMessage->setDate();
		// Add the HTML and text parts
		require_once('class.html2text.inc');
		$html2text = new html2text($this->requestParams['emailBodyHtml']);
		$emailBodyText = $html2text->get_text();
		$newMessage->setBodyText($emailBodyText);

		//check/wrap HTML body with <html><body></html></body>
		if( !preg_match("'<body[^>]*>(.*?)</body>'i", $this->requestParams['emailBodyHtml'] ) )
			$this->requestParams['emailBodyHtml'] = '<body>' . $this->requestParams['emailBodyHtml'] . '</body>';
        if( !preg_match("'<html[^>]*>(.*?)</html>'i", $this->requestParams['emailBodyHtml'] ) )
			$this->requestParams['emailBodyHtml'] = '<html>' . $this->requestParams['emailBodyHtml'] . '</html>';
        
		$newMessage->setBodyHtml($this->requestParams['emailBodyHtml']);
		
		//unpack same filter criteria and build recipient list to send to.
		$addresses = $this->getmassmailList($this->requestParams);
		//Zend_Registry::get('log')->debug( "\n" . print_r($addresses, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$addresses \n");
		
		$this->view->massmailResults = array();
		$transport = new $transportClass($this->view->global['smtphost'], $config);
		
		foreach( $addresses as $address )
		{

			$newMessage->addTo($address);
			$directory = users::getUserMailFolder( $address ) . DIRECTORY_SEPARATOR . 'new' . DIRECTORY_SEPARATOR;
			
			//if( $this->global['install_type'] == 'server' && $directory !== false )
			if( $this->view->global['install_type'] == 'server' && $directory !== false )
			{
				// Try write the message to disk first.
				$failed = false;
				try
				{
					$messageIdTrimmed = trim($newMessage->createMessageId(), ' <>');
					@file_put_contents( $directory . $messageIdTrimmed, $transport->getRawMessage($newMessage) );
					$this->view->massmailResults[] = array( 'address' => $address, 'result' => 'OK: Maildir');
				}
				catch( Exception $e )
				{
					$failed = true;
				}
				if( $failed || !file_exists($directory . $messageIdTrimmed) )
				{
					
					try
					{
						
						$newMessage->send($transport);
						$this->view->massmailResults[] = array( 'address' => $address, 'result' => 'OK: SMTP');
					
					}
					catch( Exception $e2 )
					{
						
						$this->view->massmailResults[] = array( 'address' => $address, 'result' => 'FAILED: ' . $e2->getMessage() . ', ' . $e2->getMessage() );
						
					}
				}
				
			}
			else
			{
				try
				{
					$newMessage->send($transport);
					$this->view->massmailResults[] = array( 'address' => $address, 'result' => 'OK: SMTP');
				}
				catch( Exception $e )
				{
					$this->view->massmailResults[] = array( 'address' => $address, 'result' => 'FAILED: ' . $e->getMessage() );
				}
			}
            $newMessage->clearRecipients();
		}
        $this->view->jsonIdsToRender['Mass_Mail #primary_content_inner'] = 'services/massmailsendresult.phtml';
		jQuery('#Mass_Mail #back_button')->remove();
		$this->render('global/jsonresponse', null, true);

	}
	
	
	public function apiAction() 
	{
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');
		                                                                                                                            		
	}

	public function apisaveAction()
	{        
		
		if( $this->view->global['demo'] == 1 )
			throw new Exception('Disabled in online demo');
		
		if( $this->view->userData['UMasterAdmin'] != '1' )
			throw new Exception('MasterAdmin rights required.');

		require_once 'application/models/config.php';
		if( isset($this->request->fields) )
			config::save( 'global', $this->request->fields);
		
		jQuery::addMessage( $this->view->translate('The settings have been updated.') );
		$this->render('global/jsonresponse', null, true);
		
	}	
	
	// Private functions
	private function getmassmailList($args)
	{
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');
		
		if( $args['sendToAllSubadmins'] == 1 )
		{
			
			$q = "SELECT EmailAddress FROM AdminUsers WHERE UMasterAdmin != '1'";
			$results =  $this->dbAdapter->query($q)->fetchAll();
			$addresses = array();
			foreach( $results as $result )
				if( $result['EmailAddress'] != null && $result['EmailAddress'] != '')
					$addresses[] = $result['EmailAddress'];
			return $addresses;
			
		}
		$join = '';
		$where = "(CalUser != '1' OR CalUser IS NULL)";
		if( $args['sendToAll'] == '0' )
		{
			
			if( $args['Account'] != '' )
			{

				if( $args['account_o'] == '=' )
					$where .= " AND " . $this->dbTables->UserSession . ".Account = " . $this->dbAdapter->quote($args['Account']);
				else if( $args['account_o'] == '!=' )
					$where .= " AND " . $this->dbTables->UserSession . ".Account != " . $this->dbAdapter->quote($args['Account']);
				else if( $args['account_o'] == 'like' )
					$where .= " AND " . $this->dbTables->UserSession . ".Account LIKE " . $this->dbAdapter->quote('%' . $args['Account'] . '%');
				else if( $args['account_o'] == 'not like' )
					$where .= " AND " . $this->dbTables->UserSession . ".Account NOT LIKE " . $this->dbAdapter->quote('%' . $args['Account'] . '%');
				else
					$where .= " AND FALSE";

			}	
			if( $args['Ugroup'] != '' )
			{
			
				$join .= " RIGHT JOIN  " . $this->dbTables->Users . " ON UserSession.Account = Users.Account";
				$where .= " AND  " . $this->dbTables->Users . ".Ugroup = " . $this->dbAdapter->quote( $args['Ugroup'] );
				
			}
			if( $args['domain'] != '' )
				$where .= " AND  " . $this->dbTables->UserSession . ".Account LIKE " . $this->dbAdapter->quote( '%@' . $args['domain'] );
		
		}
		$q = "SELECT  " . $this->dbTables->UserSession . ".Account FROM  " . $this->dbTables->UserSession . $join . " WHERE (" . $where . ")";
		//Zend_Registry::get('log')->debug( "\n" . print_r($q, true) . "\n" . __METHOD__ . ' #' . __LINE__ . ": \$q \n");
		
		$results = $this->dbAdapter->query($q)->fetchAll();
		
		if( $this->view->global['install_type'] == 'server' )
		{
			//only local users
			$domains = domains::getList();
		
			$accounts = array();
			foreach( $results as &$result )
			{
			
				if( in_array(substr( $result['Account'], (strpos($result['Account'], '@')+1)), $domains) )
					$accounts[] = $result['Account'];
			
			}
		}
		else
		{
			foreach( $results as &$result )
			{
				
				$accounts[] = $result['Account'];
				
			}
			
		}
		return $accounts;
		
	}
	
	public function iosAction()
	{
	}

	public function iossaveAction()
	{
		if( $this->view->global['demo'] == 1 )
			throw new Exception('Disabled in online demo');

		if( $this->view->userData['UMasterAdmin'] != '1' )
			throw new Exception('MasterAdmin rights required.');

		require_once 'application/models/config.php';
		if( isset($this->request->fields) )
			config::save( 'global', $this->request->fields);

		jQuery::addMessage( $this->view->translate('The settings have been updated.') );
		$this->render('global/jsonresponse', null, true);
	}

	public function mobileuiAction()
	{
	}

	public function mobileuisaveAction()
	{
		if( $this->view->global['demo'] == 1 )
			throw new Exception('Disabled in online demo');

		if( $this->view->userData['UMasterAdmin'] != '1' )
			throw new Exception('MasterAdmin rights required.');

		require_once 'application/models/config.php';
		if( isset($this->request->fields) )
			config::save( 'global', $this->request->fields);

		jQuery::addMessage( $this->view->translate('The settings have been updated.') );
		$this->render('global/jsonresponse', null, true);
	}


	public function serviceprovidersAction() 
	{
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');
		
		$this->view->hasLicenseWithVOIP = Zend_Registry::get('w4m70Yt0hYUduM2r2lrrIuY0bgKG4A3vvftl4NbzCWfW') & LICENSE_FEATURE_VOIP;
		$this->view->formEnabled = $this->view->hasLicenseWithVOIP;

	}

	public function serviceproviderssaveAction()
	{        
		
		if( $this->view->global['demo'] == 1 )
			throw new Exception('Disabled in online demo');
		
		if( $this->view->userData['UMasterAdmin'] != '1')
			throw new Exception('MasterAdmin rights required.');
		
		
		
		require_once 'application/models/config.php';
		if( isset($this->request->fields) )
			config::save( 'global', $this->request->fields);
		
		jQuery::addMessage( $this->view->translate('The settings have been updated.') );
		//jQuery::addMessage('Failed saving config: ' . $e->getMessage());
		$this->render('global/jsonresponse', null, true);
		
	}
}
