<?php

require_once XOOPS_ROOT_PATH . '/class/template.php';
require_once XOOPS_ROOT_PATH . '/class/xoopsformloader.php';
require_once dirname(dirname(dirname(__FILE__))) . '/class/core/ActionBase.class.php';

class Xoonips_SystemNotificationAction extends Xoonips_ActionBase {

	protected function doInit(&$request, &$response) {

		// title
		$title = _AM_XOONIPS_SYSTEM_MODULE_TITLE;
		$description = _AM_XOONIPS_SYSTEM_MODULE_DESC;

		// breadcrumbs
		$breadcrumbs = array(
		array(
		    'name' => _AM_XOONIPS_TITLE,
		    'url' => XOOPS_URL.'/modules/'.$this->dirname.'/admin/index.php',
		),
		array(
		    'name' => _AM_XOONIPS_SYSTEM_TITLE,
		    'url' => XOOPS_URL.'/modules/'.$this->dirname.'/admin/system.php',
		),
		array(
		    'name' => $title,
		),
		);

		// get module id
		$module_handler =& xoops_gethandler( 'module' );
		$module =& $module_handler->getByDirname( $this->dirname );
		$module_id = $module->getVar( 'mid' );

		// main logic
		// - $fct = 'preferences'
		// - $op = 'showmod'
		$criteria = new CriteriaCompo( new Criteria( 'conf_modid', $module_id ) );
		// select notification configulations only
		$append_confnames = array(
		  'notification_enabled',
		  'notification_events',
		);
		if ( count( $append_confnames ) > 0 ) {
			$criteria_append = new CriteriaCompo();
			foreach ( $append_confnames as $confname ) {
				$criteria_append->add( new Criteria( 'conf_name', $confname ), 'OR' );
			}
			$criteria->add( $criteria_append );
		}
		$config_handler =& xoops_gethandler( 'config' );
		$config =& $config_handler->getConfigs( $criteria );
		$count = count( $config );
		if ( $count < 1 ) {
			die( 'error : no config' );
		}
		$form = new XoopsThemeForm( $title, $this->dirname . '_admin_system_notification', XOOPS_URL . '/modules/' . $this->dirname . '/admin/system_notification.php');
		$module_handler =& xoops_gethandler( 'module' );
		$module =& $module_handler->get( $module_id );

		// if has comments feature, need comment lang file
		if ( $module->getVar( 'hascomments' ) == 1 ) {
			Xoonips_Utils::readPagetype( 'comment.php' );
		}
		// RMV-NOTIFY
		// if has notification feature, need notification lang file
		if ( $module->getVar( 'hasnotification' ) == 1 ) {
			Xoonips_Utils::readPagetype( 'notification' );
		}

		$button_tray = new XoopsFormElementTray( '' );
		for ( $i = 0; $i < $count; $i++ ) {
			$title4tray = ( ! defined( $config[$i]->getVar( 'conf_desc' ) ) || constant( $config[$i]->getVar( 'conf_desc' ) ) == '' ) ? constant( $config[$i]->getVar( 'conf_title' ) ) : constant( $config[$i]->getVar( 'conf_title' ) ).$this->getTitle4trayHtml( $config, $i );
			$eletitle = '';
			switch ( $config[$i]->getVar( 'conf_formtype' ) ) {
				case 'textarea':
					if ( $config[$i]->getVar( 'conf_valuetype' ) == 'array' ) {
						// this is exceptional.. only when value type is arrayneed a
						// smarter way for this
						$ele = ( $config[$i]->getVar( 'conf_value' ) != '' ) ? new XoopsFormTextArea( $eletitle, $config[$i]->getVar( 'conf_name' ), Xoonips_Utils::htmlSpecialChars( implode( '|', $config[$i]->getConfValueForOutput() ) ), 5, 50 ) : new XoopsFormTextArea( $eletitle, $config[$i]->getVar( 'conf_name' ), '', 5, 50 );
					} else {
						$ele = new XoopsFormTextArea( $eletitle, $config[$i]->getVar( 'conf_name' ), Xoonips_Utils::htmlSpecialChars( $config[$i]->getConfValueForOutput() ), 5, 50 );
					}
					break;
				case 'select':
					$ele = new XoopsFormSelect( $eletitle, $config[$i]->getVar( 'conf_name' ), $config[$i]->getConfValueForOutput() );
					$options =& $config_handler->getConfigOptions( new Criteria( 'conf_id', $config[$i]->getVar( 'conf_id' ) ) );
					$opcount = count( $options );
					for ( $j = 0; $j < $opcount; $j++ ) {
						#if ($j == 1 || $j == 2) continue;
						$optval = defined( $options[$j]->getVar( 'confop_value' ) ) ? constant( $options[$j]->getVar( 'confop_value' ) ) : $options[$j]->getVar( 'confop_value' );
						$optkey = defined( $options[$j]->getVar( 'confop_name' ) ) ? constant( $options[$j]->getVar( 'confop_name' ) ) : $options[$j]->getVar( 'confop_name' );
						#if ($j == 3) $optkey = _AM_XOONIPS_SYSTEM_NOTIFICATION_ENABLED;
						$ele->addOption( $optval, $optkey );
					}
					break;
				case 'checkbox':
					$ele = new XoopsFormCheckBox( $eletitle, $config[$i]->getVar( 'conf_name' ), $config[$i]->getConfValueForOutput(), 5, true );
					$options =& $config_handler->getConfigOptions( new Criteria( 'conf_id', $config[$i]->getVar( 'conf_id' ) ) );
					$opcount = count( $options );
					for ( $j = 0; $j < $opcount; $j++ ) {
						$optval = defined( $options[$j]->getVar( 'confop_value' ) ) ? constant( $options[$j]->getVar( 'confop_value' ) ) : $options[$j]->getVar( 'confop_value' );
						$optkey = defined( $options[$j]->getVar( 'confop_name' ) ) ? constant( $options[$j]->getVar( 'confop_name' ) ) : $options[$j]->getVar( 'confop_name' );
						$ele->addOption( $optval, $optkey."<br>");
					}
					break;
				case 'select_multi':
					$ele = new XoopsFormCheckBox( $eletitle, $config[$i]->getVar( 'conf_name' ), $config[$i]->getConfValueForOutput(), 5, true );
					$options =& $config_handler->getConfigOptions( new Criteria( 'conf_id', $config[$i]->getVar( 'conf_id' ) ) );
					$opcount = count( $options );
					for ( $j = 0; $j < $opcount; $j++ ) {
						$optval = defined( $options[$j]->getVar( 'confop_value' ) ) ? constant( $options[$j]->getVar( 'confop_value' ) ) : $options[$j]->getVar( 'confop_value' );
						$optkey = defined( $options[$j]->getVar( 'confop_name' ) ) ? constant( $options[$j]->getVar( 'confop_name' ) ) : $options[$j]->getVar( 'confop_name' );
						$ele->addOption( $optval, $optkey."<br>");
					}
					break;
				case 'yesno':
					$ele = new XoopsFormRadioYN( $eletitle, $config[$i]->getVar( 'conf_name' ), $config[$i]->getConfValueForOutput(), _YES, _NO );
					break;
				case 'group':
					require_once XOOPS_ROOT_PATH.'/class/xoopslists.php';
					$ele = new XoopsFormSelectGroup( $eletitle, $config[$i]->getVar( 'conf_name' ), false, $config[$i]->getConfValueForOutput(), 1, false );
					break;
				case 'group_multi':
					require_once XOOPS_ROOT_PATH.'/class/xoopslists.php';
					$ele = new XoopsFormSelectGroup( $eletitle, $config[$i]->getVar( 'conf_name' ), false, $config[$i]->getConfValueForOutput(), 5, true );
					break;
					// RMV-NOTIFY: added 'user' and 'user_multi'
				case 'user':
					require_once XOOPS_ROOT_PATH.'/class/xoopslists.php';
					$ele = new XoopsFormSelectUser( $eletitle, $config[$i]->getVar( 'conf_name' ), false, $config[$i]->getConfValueForOutput(), 1, false );
					break;
				case 'user_multi':
					require_once XOOPS_ROOT_PATH.'/class/xoopslists.php';
					$ele = new XoopsFormSelectUser( $eletitle, $config[$i]->getVar( 'conf_name' ), false, $config[$i]->getConfValueForOutput(), 5, true );
					break;
				case 'password':
					$ele = new XoopsFormPassword( $eletitle, $config[$i]->getVar( 'conf_name' ), 50, 255, Xoonips_Utils::htmlSpecialChars( $config[$i]->getConfValueForOutput() ) );
					break;
				case 'textbox':
				default:
					$ele = new XoopsFormText( $eletitle, $config[$i]->getVar( 'conf_name' ), 50, 255, Xoonips_Utils::htmlSpecialChars( $config[$i]->getConfValueForOutput() ) );
					break;
			}
			$hidden = new XoopsFormHidden( 'conf_ids[]', $config[$i]->getVar( 'conf_id' ) );
			$ele_tray = new XoopsFormElementTray( $title4tray, '' );
			$ele_tray->addElement( $ele );
			$ele_tray->addElement( $hidden );
			$form->addElement( $ele_tray );
			unset( $ele_tray );
			unset( $ele );
			unset( $hidden );
		}
		$button_tray->addElement( new XoopsFormHidden( 'action', 'update' ) );
		$button_tray->addElement( new XoopsFormHidden( 'op', 'update' ) );
		$button_tray->addElement( new XoopsFormButton( '', 'button', _AM_XOONIPS_LABEL_UPDATE, 'submit' ) );
		$form->addElement( $button_tray );

		$token_tray = new XoopsFormHiddenToken('');
		$form->addElement( $token_tray );

		// get common viewdata
		$viewData = array();

		$viewData['breadcrumbs'] = $breadcrumbs;
		$viewData['title'] = $title;
		$viewData['description'] = $description;
		$viewData['xoops_form'] = $form->render();
		
		$response->setViewData($viewData);
		$response->setForward('init_success');		
		return true;
	}

	protected function doUpdate(&$request, &$response) {

		// check token ticket
		if ( !$this->validateToken( XOOPS_TOKEN_DEFAULT ) ) {
			$response->setSystemError('Ticket error');
			return false;
		}

		// main logic
		// - $fct = 'preferences'
		// - $op = 'save'		
		$xoopsTpl = new XoopsTpl();
		$xoopsTpl->clear_all_cache();
		// regenerate admin menu file
		xoops_module_write_admin_menu( xoops_module_get_admin_menu() );
		$conf_ids = ( ! empty( $_POST['conf_ids'] ) ) ? $_POST['conf_ids'] : array();
		$count = count( $conf_ids );
		$tpl_updated = false;
		$theme_updated = false;
		$startmod_updated = false;
		$lang_updated = false;
		if ( $count > 0 ) {
			for ( $i = 0; $i < $count; $i++ ) {
				$config_handler =& xoops_gethandler( 'config' );
				$config =& $config_handler->getConfig( $conf_ids[$i] );
				$new_value =& $_POST[$config->getVar( 'conf_name' )];
				if ( is_array( $new_value ) || $new_value != $config->getVar( 'conf_value' ) ) {
					// if language has been changed
					if ( ! $lang_updated && $config->getVar( 'conf_catid' ) == XOOPS_CONF && $config->getVar( 'conf_name' ) == 'language' ) {
						// regenerate admin menu file
						$xoopsConfig['language'] = $_POST[$config->getVar( 'conf_name' )];
						xoops_module_write_admin_menu( xoops_module_get_admin_menu() );
						$lang_updated = true;
					}

					// if default theme has been changed
					if ( ! $theme_updated && $config->getVar( 'conf_catid' ) == XOOPS_CONF && $config->getVar( 'conf_name' ) == 'theme_set' ) {
						$member_handler =& xoops_gethandler( 'member' );
						$member_handler->updateUsersByField( 'theme', $_POST[$config->getVar( 'conf_name' )] );
						$theme_updated = true;
					}

					// if default template set has been changed
					if ( ! $tpl_updated && $config->getVar( 'conf_catid' ) == XOOPS_CONF && $config->getVar( 'conf_name' ) == 'template_set' ) {
						// clear cached/compiled files and regenerate them if default theme has been changed
						if ( $xoopsConfig['template_set'] != $_POST[$config->getVar( 'conf_name' )] ) {
							$newtplset = $_POST[$config->getVar( 'conf_name' )];

							// clear all compiled and cachedfiles
							$xoopsTpl->clear_compiled_tpl();

							// generate compiled files for the new theme
							// block files only for now..
							$tplfile_handler =& xoops_gethandler( 'tplfile' );
							$dtemplates =& $tplfile_handler->find( 'default', 'block' );
							$dcount = count( $dtemplates );

							// need to do this to pass to xoops_template_touch function
							$GLOBALS['xoopsConfig']['template_set'] = $newtplset;

							for ( $i = 0; $i < $dcount; $i++ ) {
								$found =& $tplfile_handler->find( $newtplset, 'block', $dtemplates[$i]->getVar( 'tpl_refid' ), null );
								if ( count( $found ) > 0 ) {
									// template for the new theme found, compile it
									xoops_template_touch( $found[0]->getVar( 'tpl_id' ) );
								} else {
									// not found, so compile 'default' template file
									xoops_template_touch( $dtemplates[$i]->getVar( 'tpl_id' ) );
								}
							}

							// generate image cache files from image binary data, save them under cache/
							$image_handler =& xoops_gethandler( 'imagesetimg' );
							$imagefiles =& $image_handler->getObjects( new Criteria( 'tplset_name', $newtplset ), true );
							foreach ( array_keys( $imagefiles ) as $i ) {
								if ( ! $fp = fopen( XOOPS_CACHE_PATH.'/'.$newtplset.'_'.$imagefiles[$i]->getVar( 'imgsetimg_file' ), 'wb' ) ) {
								} else {
									fwrite( $fp, $imagefiles[$i]->getVar( 'imgsetimg_body' ) );
									fclose( $fp );
								}
							}
						}
						$tpl_updated = true;
					}

					// add read permission for the start module to all groups
					if ( ! $startmod_updated && $new_value != '--' && $config->getVar( 'conf_catid' ) == XOOPS_CONF && $config->getVar( 'conf_name' ) == 'startpage' ) {
						$member_handler =& xoops_gethandler( 'member' );
						$groups =& $member_handler->getGroupList();
						$moduleperm_handler =& xoops_gethandler( 'groupperm' );
						$module_handler =& xoops_gethandler( 'module' );
						$module =& $module_handler->getByDirname( $new_value );
						foreach ( $groups as $groupid => $groupname ) {
							if ( ! $moduleperm_handler->checkRight( 'module_read', $module->getVar( 'mid' ), $groupid ) ) {
								$moduleperm_handler->addRight( 'module_read', $module->getVar( 'mid' ), $groupid );
							}
						}
						$startmod_updated = true;
					}
					$config->setConfValueForInput( $new_value );
					$config_handler->insertConfig( $config );
				}
				unset( $new_value );
			}
		}
		
		$viewData['url'] = XOOPS_URL.'/modules/'.$this->dirname.'/admin/system_notification.php';
		$viewData['redirect_msg'] = _AM_XOONIPS_MSG_DBUPDATED;
		
		$response->setViewData($viewData);
		$response->setForward('update_success');
		return true;
	}
		
	private function getTitle4trayHtml( $config, $i ){
			$root =& XCube_Root::getSingleton();
			$root->mContext->mModule->setAdminMode(true);
			$controller = $root->getController();
			$render =$controller->mRoot->mContext->mModule->getRenderTarget();
			$render->setTemplateName('system_notification.inc.html');
			$render->setAttribute('confDesc', constant( $config[$i]->getVar( 'conf_desc' ) ));			
			$renderSystem =$controller->mRoot->getRenderSystem($controller->mRoot->mContext->mModule->getRenderSystemName());
			$renderSystem->renderMain($render);
			$ret = $render->getResult();
			return $ret;
	}
}

