<?php

/******************************************************************************
 *  
 *  PROJECT: Flynax Classifieds Software
 *  VERSION: 4.5.2
 *  LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *  PRODUCT: Real Estate Classifieds
 *  DOMAIN: savingrack.com
 *  FILE: SETTINGS.INC.PHP
 *  
 *  The software is a commercial product delivered under single, non-exclusive,
 *  non-transferable license for one domain or IP address. Therefore distribution,
 *  sale or transfer of the file in whole or in part without permission of Flynax
 *  respective owners is considered to be illegal and breach of Flynax License End
 *  User Agreement.
 *  
 *  You are not allowed to remove this information from the file without permission
 *  of Flynax respective owners.
 *  
 *  Flynax Classifieds Software 2017 | All copyrights reserved.
 *  
 *  http://www.flynax.com/
 ******************************************************************************/

/* update actions */

$reefless->loadClass('Plan');
$reefless->loadClass('MembershipPlansAdmin', 'admin');

if (isset($_POST['a_config'])) {
	$dConfig = $_POST['post_config'];

	/* clear compile directory */
	if ( isset($dConfig['template']) && ($dConfig['template']['value'] != $config['template']))
	{
		$compile = $reefless -> scanDir( RL_TMP . 'compile' . RL_DS );
		foreach ($compile as $file)
		{
			unlink( RL_TMP . 'compile' . RL_DS . $file );
		}
		
		/* touch files */
		$reefless -> flTouch();
	} else if ($dConfig['pg_upload_thumbnail_width']['value'] != $config['pg_upload_thumbnail_width'] 
		|| $dConfig['pg_upload_thumbnail_height']['value'] != $config['pg_upload_thumbnail_height'] 
		|| $dConfig['pg_upload_large_width']['value'] != $config['pg_upload_large_width'] 
		|| $dConfig['pg_upload_large_height']['value'] != $config['pg_upload_large_height'] 
		|| $dConfig['watermark_using']['value'] != $config['watermark_using'] 
		|| $dConfig['watermark_type']['value'] != $config['watermark_type'] 
		|| $dConfig['watermark_image_url']['value'] != $config['watermark_image_url'] 
		|| $dConfig['watermark_text']['value'] != $config['watermark_text']
        || $dConfig['img_quality']['value'] != $config['img_quality']
        || $dConfig['thumbnails_x2']['value'] != $config['thumbnails_x2']
    ) {
		$_SESSION['sessAdmin']['refreshImagesPrompt'] = true;

        /* add additional columns for 2x thumbnails */
        if ($dConfig['thumbnails_x2']['value'] == '1' && $config['thumbnails_x2'] == '0') {
            $rlDb->addColumnsToTable(
                array('Main_photo_x2' => 'varchar(80) NOT NULL AFTER `Main_photo`'), 
                'listings'
            );
            $rlDb->addColumnsToTable(
                array('Thumbnail_x2' => 'varchar(255) NOT NULL AFTER `Thumbnail`'), 
                'listing_photos'
            );
        }

        /* drop additional columns for 2x thumbnails */
        if ($dConfig['thumbnails_x2']['value'] == '0' && $config['thumbnails_x2'] == '1') {
            $rlDb->dropColumnFromTable('Main_photo_x2', 'listings');
            $rlDb->dropColumnFromTable('Thumbnail_x2', 'listing_photos');
        }
	} elseif ( $dConfig['mf_geo_subdomains']['value'] != $config['mf_geo_subdomains'] && $dConfig['mf_geo_subdomains']['value'] == 1 ) {
			$ltype_on_subdomain = $rlDb -> getOne("ID", "`Links_type` = 'subdomain' AND `Status` = 'active'", "listing_types");

			if ($ltype_on_subdomain) {
				$dConfig['mf_geo_subdomains']['value'] = '0';

				$_SESSION['sessAdmin']['mfSubdomainsDenied'] = true;
			}
	} elseif ($dConfig['cache']['value'] == 1
			&& ($dConfig['cache_method']['value'] == 'memcache' && ((!extension_loaded('memcache') && !extension_loaded('memcached')) || !$rlCache->memcacheConnect())
				|| $dConfig['cache_method']['value'] == 'apc' && !extension_loaded('apc'))
		) {
			$dConfig['cache_method']['value'] = $config['cache_method'];
			$_SESSION['sessAdmin']['cacheMethodDenied'] = true;
	} elseif (
			$dConfig['mail_method']['value'] == 'smtp' 
			&& (
			   $dConfig['mail_method']['value'] != $config['mail_method']
			|| $dConfig['smtp_server']['value'] != $config['smtp_server']
			|| $dConfig['smtp_username']['value'] != $config['smtp_username']
 			|| $dConfig['smtp_password']['value'] != $config['smtp_password']
 			|| $dConfig['smtp_method']['value'] != $config['smtp_method'])
		) {
			$_SESSION['sessAdmin']['debugSmtp'] = true;
	}

	/* update cache */
	if (isset($dConfig['cache']) && $dConfig['cache']['value'] && !$config['cache']) {
		$config['cache'] = 1;
		$rlCache -> update();
	} elseif ($dConfig['cache']['value'] && $dConfig['cache_method']['value'] != $config['cache_method']) {
		$config['cache_method'] = $dConfig['cache_method']['value'];
		$rlCache -> update();
	} elseif ($dConfig['cache']['value'] && $dConfig['cache_divided']['value'] != $config['cache_divided']) {
		$config['cache_divided'] = $dConfig['cache_divided']['value'];
		$rlCache -> update();
	}
	
    // show/hide Flynax Blog Feed
    if ($dConfig['flynax_news_number']['value'] != $config['flynax_news_number']) {
        $rlActions->updateOne(
            array(
                'fields' => array(
                    'Status' => intval($dConfig['flynax_news_number']['value']) == 0 ? 'approval' : 'active'
                ),
                'where' => array(
                    'Key' => 'flynax_news',
                )
            ),
            'admin_blocks'
        );

        // recount order of all admin blocks
        $blocks = $rlDb->fetch(
            array('Column', 'ID'), 
            array('Status' => 'active'), 
            'ORDER BY `Column` ASC', 
            null,
            'admin_blocks'
        );

        foreach ($blocks as $block) {
            $block_index++;

            $update[] = array(
                'fields' => array(
                    'Column' => 'column' . $block_index,
                ),
                'where' => array(
                    'ID' => $block['ID'],
                ),
            );

        }

        if ($blocks) {
            $rlActions->update($update, 'admin_blocks');
        }
    }

	// membership plans
	if ($dConfig['membership_module']['value'] == 0 && $rlMembershipPlansAdmin->getActiveListings() > 0 && $dConfig['base_listing_plan']['value']) {
		$rlMembershipPlansAdmin->assignListingToListingPlan($dConfig['base_listing_plan']['value']);
	}

    $update = array();
    $fields_to_trim = array('google_map_key', 'google_server_map_key');

    foreach ($dConfig as $key => $value) {
        if ($value['d_type'] == 'int') {
            $value['value'] = (int) $value['value'];
        } else if (is_numeric(strpos($value['value'], '[[http'))) {
            $value['value'] = preg_replace("#\[\[http(s)?_pref\]\]#", "http$1", $value['value']);
        } else if (in_array($key, $fields_to_trim)) {
            $value['value'] = trim($value['value']);
        }

        $row['where']['Key']      = $key;
        $row['fields']['Default'] = $value['value'];
        array_push($update, $row);
    }

	$reefless -> loadClass( 'Actions' );
	
	$rlHook -> load('apPhpConfigBeforeUpdate');
	
	if ($rlActions -> update( $update, 'config' ))
	{
		$rlHook -> load('apPhpConfigAfterUpdate');
		
		$reefless -> loadClass( 'Notice' );
		
		$aUrl = array( "controller" => $controller );
		if ( $_POST['group_id'] )
		{
			$aUrl['group'] = $_POST['group_id'];
		}

        if (!$_SESSION['sessAdmin']['mfSubdomainsDenied'] 
        	&& !$_SESSION['sessAdmin']['cacheMethodDenied']
        	&& !isset($_SESSION['admin_notice'])) {
    		$rlNotice -> saveNotice( $lang['config_saved'] );
        }
		$reefless -> redirect( $aUrl );
	}
}

/* get all config groups */
$g_sql = "SELECT `T1`.*, `T2`.`Status` AS `Plugin_status` FROM `".RL_DBPREFIX."config_groups` AS `T1` ";
$g_sql .= "LEFT JOIN `".RL_DBPREFIX."plugins` AS `T2` ON `T1`.`Plugin` = `T2`.`Key` GROUP BY `ID` ";
$configGroups = $rlDb -> getAll($g_sql);

$configGroups = $rlLang -> replaceLangKeys( $configGroups, 'config_groups', 'name', RL_LANG_CODE, 'admin' );
$rlSmarty -> assign_by_ref( 'configGroups', $configGroups );

foreach ($configGroups as $key => $value)
{
	$groupIDs[] = $value['ID'];
}

/* get all configs */
$configsLsit = $rlDb -> fetch( '*', null, "WHERE `Group_ID` = '".implode("' OR `Group_ID` = '", $groupIDs).")' ORDER BY `Position`", null, 'config' );
$configsLsit = $rlLang -> replaceLangKeys( $configsLsit, 'config', array( 'name', 'des' ), RL_LANG_CODE, 'admin' );
$rlAdmin -> mixSpecialConfigs( $configsLsit );

foreach($configsLsit as $key => $value)
{
	$configs[$value['Group_ID']][] = $value;
}
$rlSmarty -> assign_by_ref('listing_plans', $rlPlan->getPlans());

$rlSmarty -> assign_by_ref( 'configs', $configs );
unset($configGroups, $configsLsit);

$rlHook -> load('apPhpConfigBottom');

/* prompt to rebuild images, if dimensions were changed */
if ($_SESSION['sessAdmin']['refreshImagesPrompt']) {
	unset($_SESSION['sessAdmin']['refreshImagesPrompt']);
	$rlSmarty -> assign('refreshImagesPrompt', true);
} elseif ($_SESSION['sessAdmin']['mfSubdomainsDenied']) {
    unset($_SESSION['sessAdmin']['mfSubdomainsDenied']);
    $rlSmarty -> assign('mfSubdomainsDenied', true);
} elseif ($_SESSION['sessAdmin']['cacheMethodDenied']) {
    unset($_SESSION['sessAdmin']['cacheMethodDenied']);
    $rlSmarty -> assign('cacheMethodDenied', true);
} elseif ($_SESSION['sessAdmin']['debugSmtp']) {
	$reefless->loadClass('Mail');
	$smtp_debug = $rlMail->testSMTP();
	preg_match("#250 OK#", $smtp_debug, $match);
	
	if ($match) {
		$_SESSION['admin_notice'] = $lang['notice_smtp_ok'];
	} else {
		$_SESSION['admin_notice'] = $lang['notice_smtp_failed'];
		$rlSmarty -> assign('smtpDebug', $smtp_debug);
	}
	
	unset($_SESSION['sessAdmin']['debugSmtp']);
}

$rlXajax->registerFunction(array('checkActiveListings', $rlMembershipPlansAdmin, 'ajaxCheckActiveListings'));