<?php

/**

 * SEF component for Joomla!

 * 

 * @package   JoomSEF

 * @version   3.11.0

 * @author    ARTIO s.r.o., http://www.artio.net

 * @copyright Copyright (C) 2013 ARTIO s.r.o. 

 * @license   GNU/GPLv3 http://www.artio.net/license/gnu-general-public-license

 */



// no direct access

defined('_JEXEC') or die('Restricted access');



jimport( 'joomla.installer.installer' );

jimport( 'joomla.filesystem.folder' );

jimport( 'joomla.filesystem.file' );



function com_install()

{

    // Load language file

    $lang =& JFactory::getLanguage();

    $lang->load('com_sef');

    

    $db =& JFactory::getDBO();



    // Set the wrapper extension default parameters

    $db->setQuery("SELECT `id` FROM `#__sefexts` WHERE `file` = 'com_wrapper.xml' LIMIT 1");

    $id = $db->loadResult();

    if( empty($id) ) {

        $db->setQuery("INSERT INTO `#__sefexts` (`file`, `params`) VALUES ('com_wrapper.xml', 'ignoreSource=0\nitemid=1\noverrideId=')");

        $res = $db->query();

        if( !$res ) {

            JError::raiseWarning(100, JText::_('COM_SEF_INSTALL_ERR_WRAPPER'));

        }

    }

    

    // Set the content extension default parameters

    $defaultFilters = '+^[0-9]*$=limit,limitstart,month,showall,year\n+^[a-zA-Z]+$=task,type,view\n+^[0-9]+(:.+)?$=catid,id,sectionid';

    $defaultVars = 'acceptVars=view; id; catid; sectionid; type; year; month; filter; limit; limitstart; task; showall';

    $db->setQuery("SELECT `id` FROM `#__sefexts` WHERE `file` = 'com_content.xml' LIMIT 1");

    $id = $db->loadResult();

    if( empty($id) ) {

        $db->setQuery("INSERT INTO `#__sefexts` (`file`, `filters`, `params`) VALUES ('com_content.xml', '{$defaultFilters}', '{$defaultVars}')");

        $res = $db->query();

        if( !$res ) {

            JError::raiseWarning(100, JText::_('COM_SEF_INSTALL_ERR_CONTENT'));

        }

    }



    // Install JoomSEF plugin

    $src = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_sef'.DS.'plugin'.DS;

    $dest = JPATH_ROOT.DS.'plugins'.DS.'system'.DS;



    $res = JFile::copy($src.'joomsef.php', $dest.'joomsef.php');

    $res = $res && JFile::copy($src.'joomsef.xml', $dest.'joomsef.xml');



    // Get the lowest ordering

    $db->setQuery("SELECT MIN(`ordering`) FROM `#__plugins` WHERE `folder` = 'system'");

    $min = $db->loadResult();

    $min -= 10;

    

    $db->setQuery("INSERT INTO #__plugins

	               (id, name, element, folder, access, ordering, published, iscore, client_id, checked_out, checked_out_time, params)

	               VALUES ('', 'System - ARTIO JoomSEF', 'joomsef', 'system', 0, '{$min}', 1, 0, 0, 0, '0000-00-00 00:00:00', '')");

    $res = $res && $db->query();



    // Install JoomSEF Google Analytics plugin

    $res = $res && JFile::copy($src.'joomsefgoogle.php', $dest.'joomsefgoogle.php');

    $res = $res && JFile::copy($src.'joomsefgoogle.xml', $dest.'joomsefgoogle.xml');

    

    $db->setQuery("INSERT INTO #__plugins

	               (id, name, element, folder, access, ordering, published, iscore, client_id, checked_out, checked_out_time, params)

	               VALUES ('', 'System - ARTIO JoomSEF Google Analytics', 'joomsefgoogle', 'system', 0, '0', 1, 0, 0, 0, '0000-00-00 00:00:00', '')");

    $res = $res && $db->query();



    if (!$res) {

        JError::raiseWarning(100, JText::_('WARNING_PLUGIN_NOT_INSTALLED').': '.$src);

    } else {

        JFolder::delete($src);

    }



    // Install content elements if JoomFish is present

    $file = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_joomfish'.DS.'joomfish.php';



    if( JFile::exists($file) ) {

        $src = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_sef'.DS.'contentelements';

        $dest = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_joomfish'.DS.'contentelements';



        $files = JFolder::files($src);



        $res = true;

        foreach($files as $file) {

            $res = $res && JFile::copy($src.DS.$file, $dest.DS.$file);

        }



        if( !$res ) {

            JError::raiseWarning(100, JText::_('COM_SEF_INSTALL_ERR_JOOMFISH').$src);

        } else {

            JFolder::delete($src);

        }

    }

    

    // 20.8.2013 dajo: adapter doesn't need to be installed anymore

    // Install the extension installer adapter if possible

    /*$adapterSrc = JPATH_ADMINISTRATOR.DS.'components'.DS.'com_sef'.DS.'adapters'.DS.'sef_ext.php';

    $adapterDest = JPATH_LIBRARIES.DS.'joomla'.DS.'installer'.DS.'adapters'.DS.'sef_ext.php';

    $adapterInstalled = false;

    if( is_writable(dirname($adapterDest)) ) {

        if( @copy($adapterSrc, $adapterDest) ) {

            $adapterInstalled = true;

        }

    }*/



    // Check former AceSEF and sh404SEF installations

    $formerSEF = false;



    $query = "SELECT * FROM `#__acesef_urls` LIMIT 1";

    $db->setQuery($query);

    $row = $db->loadObject();

    if (!is_null($row)) {

        $formerSEF = true;

    }



    if (!$formerSEF) {

        $query = "SELECT * FROM `#__redirection` LIMIT 1";

        $db->setQuery($query);

        $row = $db->loadObject();

        if( !is_null($row) ) {

            if( isset($row->oldurl) && isset($row->newurl) ) {

                $formerSEF = true;

            }

        }

    }



    ob_start();



    echo '<div class="quote" style="text-align: center;">';

    echo '<h1>'.JText::_('COM_SEF_INSTALL_SUCCESS').'</h1>';

    

    if( $formerSEF ) {

        echo '<h3>'.JText::sprintf('COM_SEF_INSTALL_FORMER_SEF', '<a href="index.php?option=com_sef&amp;controller=sefurls&amp;task=showimport">', '</a>').'</h3><br />';

    }

    

    // Check the host and set handling to redirect to www if needed

    $uri =& JURI::getInstance();

    $host = $uri->getHost();

    if (substr($host, 0, 4) == 'www.') {

        // Import the SEF config file

        include(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_sef'.DS.'classes'.DS.'config.php');

        if (class_exists('SEFConfig')) {

            $sefConfig =& SEFConfig::getConfig();

            $sefConfig->wwwHandling = _COM_SEF_WWW_USE_WWW;

            $sefConfig->saveConfig();

        }

    }

    

    echo '<h3>'.JText::_('COM_SEF_INSTALL_ACTIVATE_CONFIG').'</h3>';

    $readdocs = '<p class="message">'.JText::sprintf('COM_SEF_INSTALL_EXTRA_CONFIG', '<a href="http://www.artio.net/joomsef/documentation" target="_blank">', '</a>');

    if (!(strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') === false)) {

        echo $readdocs.'IIS.</p>';

    }

    else {

        // Get the correct rewrite base

        $base = JURI::root(true);

        if( $base == '' ) {

            $base = '/';

        }



        // Create htaccess content

        $htaccess = '

DirectoryIndex index.php

RewriteEngine On

RewriteBase '.$base.'



########## Begin - Rewrite rules to block out some common exploits

## If you experience problems on your site block out the operations listed below

## This attempts to block the most common type of exploit `attempts` to Joomla!

#

## Deny access to extension xml files (uncomment out to activate)

#<Files ~ "\.xml$">

#Order allow,deny

#Deny from all

#Satisfy all

#</Files>

## End of deny access to extension xml files

# Block out any script trying to set a mosConfig value through the URL

RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]

# Block out any script trying to base64_encode crap to send via URL

RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]

# Block out any script that includes a <script> tag in URL

RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]

# Block out any script trying to set a PHP GLOBALS variable via URL

RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]

# Block out any script trying to modify a _REQUEST variable via URL

RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})

# Send all blocked request to homepage with 403 Forbidden error!

RewriteRule ^(.*)$ index.php [F,L]

#

########## End - Rewrite rules to block out some common exploits



RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_URI} !^/index.php

RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]

RewriteRule (.*) index.php

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]

';



        //if (substr(PHP_OS, 0, 3) == 'WIN') {

        //	echo '<p class="error">Found apache on windows, .htaccess is an illegal filename for this system.<br/>You must complete the rest of the configuration manually.</p>';

        //	echo $readdocs."the apache .htaccess file.</p>";

        //}

        //else{

        echo '<p style="text-align: center;">'.JText::_('COM_SEF_INSTALL_HTACCESS_CHECK').'<br />';

        $file = JPATH_ROOT.DS.'.htaccess';

        if( !JFile::exists($file) ) {

            echo JText::_('COM_SEF_INSTALL_HTACCESS_NOT_FOUND').'</p>';



            if( !JFile::write($file, $htaccess) ) {

                echo '<p style="text-align: center;" class="error">'.JText::_('COM_SEF_INSTALL_HTACCESS_NOT_CREATED').'<br/><pre>'.htmlspecialchars(nl2br($htaccess)).'</pre>';

            }

            else{

                echo JText::_('COM_SEF_INSTALL_HTACCESS_CREATED').'<br/><pre>'.htmlspecialchars($htaccess).'</pre>';

            }

            echo JText::_('COM_SEF_INSTALL_HTACCESS_REWRITEBASE');

        }

        else {

            echo '<span class="error">'.JText::_('COM_SEF_INSTALL_HTACCESS_FOUND').'</span></p>';

            echo $readdocs.JText::_('COM_SEF_INSTALL_EXTRA_CONFIG_APACHE').'</p>';

        }

        echo '</div>';

    }



    //include( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_sef'.DS.'views'.DS.'info'.DS.'tmpl'.DS.'readme.inc.html' );

    

    ?>

    <h2 style="color: #A1B754"><?php echo JText::_('COM_SEF_INSTALL_START'); ?></h2>

    <div id="cpanel" class="icons">

        <div class="icon">

            <a href="index.php?option=com_sef" title="<?php echo JText::_('COM_SEF_TT_CONTROL_PANEL'); ?>">

            <img src="components/com_sef/assets/images/icon-48-artio.png" alt="" width="48" height="48" border="0"/>

            <span><?php echo JText::_('COM_SEF_CONTROL_PANEL'); ?></span>

            </a>

        </div>

        <div class="icon">

            <a href="http://www.artio.net/joomsef/documentation" target="_blank" title="<?php echo JText::_('COM_SEF_TT_DOCUMENTATION'); ?>">

                <img src="components/com_sef/assets/images/icon-48-docs.png" alt="" width="48" height="48" align="middle" border="0"/>

                <span><?php echo JText::_('Documentation'); ?></span>

            </a>

        </div>

        <div class="icon">

            <a href="index.php?option=com_sef&amp;controller=info&amp;task=changelog" title="<?php echo JText::_('COM_SEF_TT_CHANGELOG'); ?>">

                <img src="components/com_sef/assets/images/icon-48-info.png" alt="" width="48" height="48" align="middle" border="0"/>

                <span><?php echo JText::_('Changelog'); ?></span>

            </a>

        </div>

        <div class="icon">

            <a href="index.php?option=com_sef&amp;controller=info&amp;task=help" title="<?php echo JText::_('COM_SEF_TT_SUPPORT'); ?>">

                <img src="components/com_sef/assets/images/icon-48-help.png" alt="" width="48" height="48" align="middle" border="0"/>

                <span><?php echo JText::_('Support'); ?></span>

            </a>

        </div>

    </div>

    

    <?php



    $output = ob_get_contents();

    ob_end_clean();



    echo $output;

}

?>