array(
			'controller' 	=> 'eurl_admin_ui',
			'path' 			=> null,
			'ui' 			=> 'eurl_admin_form_ui',
			'uipath' 		=> null
		)
	);
	protected $adminMenu = array(
		'main/config'		=> array('caption'=> LAN_EURL_MENU_PROFILES, 'perm' => 'L', 'icon'=>'fas-list'),
		'main/alias' 		=> array('caption'=> LAN_EURL_MENU_ALIASES, 'perm' => 'L', 'icon'=>'fas-edit'),
		'main/simple' 		=> array('caption'=> LAN_EURL_MENU_CONFIG, 'perm' => 'L', 'icon'=>'fas-sliders-h'),
		'main/settings' 	=> array('caption'=> LAN_EURL_MENU_SETTINGS, 'perm' => 'L'),
	//	'main/help' 		=> array('caption'=> LAN_EURL_MENU_HELP, 'perm' => 'L'),
	);
	protected $adminMenuAliases = array();
	
	protected $defaultAction = 'config';
	protected $menuTitle = LAN_EURL_MENU;
	protected $adminMenuIcon = 'e-eurl-24';
}
class eurl_admin_ui extends e_admin_controller_ui
{
	public $api;
	
	protected $prefs = array(
		'url_disable_pathinfo'	=> array('title'=>LAN_EURL_SETTINGS_PATHINFO,	'type'=>'boolean', 'help'=>LAN_EURL_MODREWR_DESCR),
		'url_main_module'	=> array('title'=>LAN_EURL_SETTINGS_MAINMODULE,	'type'=>'dropdown', 'data' => 'string', 'help'=>LAN_EURL_SETTINGS_MAINMODULE_HELP),
		'url_error_redirect'	=> array('title'=>LAN_EURL_SETTINGS_REDIRECT,	'type'=>'boolean', 'help'=>LAN_EURL_SETTINGS_REDIRECT_HELP),
		'url_sef_translate'	=> array('title'=>LAN_EURL_SETTINGS_SEFTRANSLATE,	'type'=>'dropdown', 'data' => 'string', 'help'=>LAN_EURL_SETTINGS_SEFTRANSLATE_HELP),
	);
	
	public function init()
	{
		if(e_AJAX_REQUEST)
		{
			$tp = e107::getParser();
			if(!empty($_POST['pk']) && !empty($_POST['value']))
			{
				$cfg = e107::getConfig();
				list($plug,$key) = explode("|", $_POST['pk']);
				if(is_string($cfg->get('e_url_alias')))
				{
					$cfg->setPostedData('e_url_alias', array(e_LAN => array($plug => array($key => $tp->filter($_POST['value']))) ), false);
				}
				else
				{
					$cfg->setPref('e_url_alias/'.e_LAN.'/'.$plug."/".$key, $tp->filter($_POST['value']));
				}
				$cfg->save(true, true, true);
			}
		//	file_put_contents(e_LOG."e_url.log", print_r($cfg->get('e_url_alias'),true));
			exit;
		}
		$htaccess = file_exists(e_BASE.".htaccess");
		if(function_exists('apache_get_modules'))
		{
			$modules = apache_get_modules();
			$modRewrite = in_array('mod_rewrite', $modules );
		}
		else
		{
			$modRewrite = true; //we don't really know.
		}
		if($modRewrite === false)
		{
			e107::getMessage()->addInfo("Apache mod_rewrite was not found on this server and is required to use this feature. ");
			e107::getMessage()->addDebug(print_a($modules,true));
		}
		if($htaccess && $modRewrite && !deftrue('e_MOD_REWRITE'))
		{
			e107::getMessage()->addInfo("Mod-rewrite is disabled. To enable, please add the following line to your e107_config.php  file:
define('e_MOD_REWRITE',true); ");
		}
	
		if(isset($_POST['rebuild']) && is_array($_POST['rebuild']))
		{
			$table = key($_POST['rebuild']);
			list($primary, $input, $output) = explode("::",$_POST['rebuild'][$table]);
			$this->rebuild($table, $primary, $input, $output);	
		}
		
		
		$this->api = e107::getInstance();
		$this->addTitle(LAN_EURL_NAME);
		
		if($this->getAction() != 'settings') return;
		
	
		
	}
	
	/**
	 * Rebuild SEF Urls for a particular table
	 * @param $table
	 * @param primary field id. 
	 * @param input field (title)
	 * @param output field (sef)
	 */
	private function rebuild($table, $primary='', $input='',$output='')
	{
		if(empty($table) || empty($input) || empty($output) || empty($primary))
		{
			e107::getMessage()->addError("Missing Generator data");	
			return;
		}
		
		$sql = e107::getDb();
		
		$data = $sql->retrieve($table, $primary.",".$input, $input ." != '' ", true);
		
		$success = 0;
		$failed = 0;
		
		foreach($data as $row)
		{
			$sef = eHelper::title2sef($row[$input]);
			
			if($sql->update($table, $output ." = '".$sef."' WHERE ".$primary. " = ".intval($row[$primary]). " LIMIT 1")!==false)
			{
				$success++;
			}
			else
			{
				$failed++;
			}
			
			// echo $row[$input]." => ".$output ." = '".$sef."'  WHERE ".$primary. " = ".intval($row[$primary]). " LIMIT 1 ".$table." ".$table." ";
		$text .= $frm->open('simpleSef');
		$multilan = "
".$tp->toGlyph('fa-language')." ";
		$home = "
".SITEURL.' ';
		//  e107::getDebug()->log($sefActive);
		$plg = e107::getPlug();
		foreach($eUrl as $plug=>$val)
		{
			$plg->load($plug);
			$active = !empty($sefActive[$plug]) ? true : false;
			$text .= "
			
				 ";
			$name = 'urlstatus['.$plug.']';
			$switch = $frm->radio_switch($name, $active, LAN_ON, LAN_OFF, array(
				'switch' => 'mini',
			));
			$text .= "" . $plg->getName() . " " . $switch . " ".LAN_EURL_KEY." ".LAN_EURL_REGULAR_EXPRESSION." 
			".LAN_URL." 
			
					".$k." 
					".$aliasRender." 
					". $v['redirect']." 
					 ";
			}
		
					
			$text .= "
";
		}	
		$text .= "
".$frm->button('saveSimpleSef',LAN_SAVE, 'submit')."
";
		$text .= $frm->token();
		$text .= $frm->close();
		$text .= "
".$label." ".$selector." ";
			$text .= (!empty($generate[$plug])) ? $form->admin_button('generate['.$plug.']', $plug,'delete', LAN_EURL_REBUILD) : "";
			$text .= " ";
        $text .= $title;  
        $text .= ' ';
        
        $text .= '
         
            
				
	                
	                
	                ';
        
        $text .= $info;
       
                
        $text .= '
                 
                
                 
                  ';
        
        return $text;
        
    }
    
    
    
    
	
	public function moduleRows($data)
	{
		$text = '';
		$tp = e107::getParser();
		$frm = e107::getForm();
		if(empty($data))
		{
			return "
				
					".LAN_EURL_EMPTY." 
				 
			";
		}
		
        $PLUGINS_DIRECTORY = e107::getFolder("PLUGINS");
        $srch = array("{SITEURL}","{e_PLUGIN_ABS}");
        $repl = array(SITEURL,SITEURL.$PLUGINS_DIRECTORY);
        
		foreach ($data as $obj) 
		{
			$admin 		= $obj->config->admin();
			$section 	= vartrue($admin['labels'], array());
            $rowspan 	= count($obj->locations)+1;
            $module 	= $obj->module;
			$generate 	= vartrue($admin['generate'], array());
           
          /*
			$info .= "
                
                    
                    ".vartrue($section['name'], eHelper::labelize($obj->module))."
                      
            ";
          */
            $opt = "";   
			$info = "";
            
			foreach ($obj->locations as $index => $location) 
			{
				$objSub = $obj->defaultLocation != $location ? eDispatcher::getConfigObject($obj->module, $location) : false; 
				if($objSub) 
				{
					$admin = $objSub->admin();
					$section = vartrue($admin['labels'], array());
				} 
				elseif($obj->defaultLocation != $location) $section = array();
				
				$id = 'eurl-'.str_replace('_', '-', $obj->module).'-'.$index;
				
				$checked = (isset($obj->current[$module]) && $obj->current[$module] == $location) ? ' checked="checked"' : '';
				
				$path = eDispatcher::getConfigPath($module, $location, false);
				if(!is_readable($path))
				{
				    $path = str_replace('/url.php', '/', $tp->replaceConstants(eDispatcher::getConfigPath($module, $location, true), true)).' ('.LAN_EURL_LOCATION_NONE.') ';
                    $diz = LAN_EURL_DEFAULT;
                }
				else
				{
				    $path = $tp->replaceConstants(eDispatcher::getConfigPath($module, $location, true), true);
                    $diz  = (basename($path) != 'url.php' ) ? LAN_EURL_FRIENDLY : LAN_EURL_DEFAULT;
				}
				    
				$label = vartrue($section['label'], $index == 0 ? LAN_EURL_DEFAULT : eHelper::labelize(ltrim(strstr($location, '/'), '/')));
			//	$cssClass = $checked ? 'e-showme' : 'e-hideme';
				$cssClass = 'e-hideme'; // always hidden for now, some interface changes could come after pre-alpha
				 $exampleUrl = array();
				 if(!empty($section['examples']))
				 {
	                foreach($section['examples'] as $ex)
	                {
	                    $exampleUrl[] = str_replace($srch,$repl,$ex);
	                }
				 }
/*
                 if(strpos($path,'noid')!==false)
                {
                 $exampleUrl .= "    ‡";    //XXX Add footer - denotes more CPU required. ?
                }
 */
                $selected = (isset($obj->current[$module]) && ($obj->current[$module] == $location)) ? "selected='selected'" : '';
				$opt .= "".$diz.": ".varset($exampleUrl[0])." ";
				$info .= "".$label."
					
					 
					".LAN_EURL_LOCATION." : ".$path."
                    ".vartrue($section['description'], LAN_EURL_PROFILE_INFO)."
".implode(" 
";
			$title = vartrue($section['name'], eHelper::labelize($obj->module));
			
			$text .= "
                
                    ".$this->moreInfo($title, $info)." 
                    ".$opt." ";
		
			$bTable = varset($admin['generate']['table']);
			$bInput = varset($admin['generate']['input']);
			$bOutput = varset($admin['generate']['output']);
			$bPrimary = varset($admin['generate']['primary']);
			
		
			$text .= (is_array($admin['generate'])) ? $frm->admin_button('rebuild['.$bTable.']', $bPrimary."::".$bInput."::".$bOutput,'delete', LAN_EURL_REBUILD) : "";	  
				  
			$text .= " 
                ";
		}
		
		
		
		
		
		
		
		
		/*
		For Miro - intuitive interface example. All configs are contained within one e_url.php file. 
		Root namespacing automatically calculated based on selection. 
		ie. choosing option 1 below will set root namespacing for news. 
		Known bug (example): 
		  News title: Nothing's Gonna Change my World!
		  Currently becomes: /Nothing%26%23039%3Bs%20Gonna%20Change%20my%20World%21
		 Should become: /nothings-gonna-change-my-world
		 Good SEF reference: http://davidwalsh.name/generate-search-engine-friendly-urls-php-function
		 
		 [Miro] Solution comes from the module itself, not related with URL assembling in anyway (as per latest Skype discussion)
		 */
		
		// Global On/Off Switch Example
		// [Miro] there is no reason of switch, everything could go through single entry point at any time, without a need of .htaccess (path info)
		// Control is coming per configuration file.
		$example = "
		Enable Search-Engine-Friendly URLs 
		News 
					
					";
					
		$example .= " 
					
					".LAN_EURL_EMPTY." 
				 
			";
		}
		
		$text = '';
		$tp = e107::getParser();
		$text .= "
			Module 
			 ";
		$lng = e107::getLanguage();
		foreach ($modules as $module => $obj) 
		{
			$cfg = $obj->config->config();
			if(isset($cfg['config']['noSingleEntry']) && $cfg['config']['noSingleEntry']) continue;
			
			if($module == 'index')
			{
				$text .= "
				
					
						".LAN_EURL_CORE_INDEX."
					 
					
						
						
 
							
							
								".LAN_EURL_CORE_INDEX_INFO."
							 
							
								".e107::getUrl()->create('/', '', array('full' => 1))."
							  
						
					 
				 
				";
				continue;
			}
			$help = array();
			$admin = $obj->config->admin();
			$lan = $lanDef[0];
			$url = e107::getUrl()->create($module, '', array('full' => 1, 'encode' => 0));
			$defVal = isset($currentAliases[$lan]) && in_array($module, $currentAliases[$lan]) ? array_search($module, $currentAliases[$lan]) : $module; 
			$section = vartrue($admin['labels'], array());
			
			$text .= "
				
					
						".vartrue($section['name'], ucfirst(str_replace('_', ' ', $obj->module)))."
						
						".LAN_EURL_FORM_HELP_ALIAS_0." {$module} 
					 
					
			";
			
			
			// default language
			$text .= "
 ";
			$text .= "
			".ADLAN_132." 
			".LAN_EURL_NAME_ALIASES." 
			".LAN_EURL_FORM_HELP_EXAMPLE." 
		 ";
			$text .= "";
			$text .= "".$lanDef[1].$this->help(LAN_EURL_FORM_HELP_DEFAULT)." ";
			$text .= "";
			$text .= $this->text('eurl_aliases['.$lanDef[0].']['.$module.']', $defVal, 255, 'size=xlarge');
		//	$text .= ' ['.$lanDef[1].']';
			$text .= " ";
			$text .= " ";
		//	$help[] = '['.$lanDef[1].'] '.LAN_EURL_FORM_HELP_EXAMPLE.':'.$url.' ';
			$text .= " ";
			if(e107::getUrl()->router()->isMainModule($module))
			{
				$help = " ".$tp->toGlyph('fa-home')." ";
				//$readonly = 1; // may be used later.
				$readonly = 0;
			}
			else
			{
				$help = '';
				$readonly=0;
			}
			if($lans)
			{
				foreach ($lans as $code => $lan) 
				{
					$url = e107::getUrl()->create($module, '', array('lan' => $code, 'full' => 1, 'encode' => 0)); 
					$defVal = isset($currentAliases[$code]) && in_array($module, $currentAliases[$code]) ? array_search($module, $currentAliases[$code]) : $module;
				//	$help .= '['.$lan.'] '.LAN_EURL_FORM_HELP_EXAMPLE.':'.$url.' ';
					$text .= "";
					$text .= "".$lan." ";
					$text .= "". $this->text('eurl_aliases['.$code.']['.$module.']', $defVal, 255, array('size' => 'xlarge', 'readonly'=>$readonly));
					$text .=  $help;
					$text .= " ";
					$text .= "";
					//	$text .= $this->help(LAN_EURL_FORM_HELP_ALIAS_1.' '.$lan.' ');
				//	$text .= $this->help(LAN_EURL_FORM_HELP_ALIAS_1.' '.$lan.' ');
					$url = $lng->subdomainUrl($lan,$url);
					$text .= $url;
					$text .= " ";
				//	$text .= "".
				//	$text .= '['.$lan.'] '.LAN_EURL_FORM_HELP_EXAMPLE.':'.$url.' ';
				//	$text .= " ";
					$text .= " ";
				}
			}
			$text .= "
				  ";
			
			/*$text .= "
					
					
						".implode("
", $help)."
					 
				
			";*/
		//	$text .= "";
		}
		return $text;
	}
}
class eurlAdminEmptyConfig extends eUrlConfig
{
	public function config()
	{
		return array();
	}
}
new eurl_admin();
require_once(e_ADMIN.'auth.php');
e107::getAdminUI()->runPage();
require_once(e_ADMIN.'footer.php');