<?php

/**
 * ---=== ProfiCaptcha 0.5 ===---
 * v. 0.5.0.0
 * 
 * (c) Леонтьев Валерий (Компания "Профигруп"), 2007—2008
 * (c) Leontyev Valera (Profigroup Company), 2007—2008
 * 
 * Разработчик: Валерий Леонтьев (feedbee@gmail.com)
 * Версия 0.1 разработана Александром Сукачем, но переписана на 90%.
 * Developers: Valery Leontyev (feedbee@gmail.com)
 * Basic 0.1 version was developed by Alex Sukach and 90% rewriten
 * 
 * Требования: PHP5 с установленными библиотеками GD и FreeType.
 * Стандартный движек сессий PHP должен быть включен и работать корректно.
 * Requirements: PHP5 with GD library and the FreeType library installed.
 * Standart session engine must be enabled and work propertly.
 * 
 * Лицензия: BSD / License: BSD
 * 
 * Copyright (c) 2007—2008, Leontyev Valera (Profigroup Company)
 *
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * - Neither the name of Leontyev Valera or the Profigroup Company nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */

/**
 * 
 * !!! README !!!
 * 
 * Этот файл генерирует изображение и выводит его в браузер.
 * Сгенерированный контрольный код сохранятеся в сессии в массив
 * $_SESSION[ProfiCaptchaOptions::SESSION_KEY]. Константа класса
 * ProfiCaptchaOptions::SESSION_KEY устанавливается ниже в файле Settings.php.
 * При получении данных в Вашем скрипте просто проверьте, содержится ли
 * введенный пользователем код в этом массиве. Если не содержится, код неверный.
 * 
 * This generates an image file and displays it in a browser.
 * Generated check-code is stored in session in the
 * $_SESSION[ProfiCaptchaOptions::SESSION_KEY] array.Class constant
 * ProfiCaptchaOptions::SESSION_KEY established in Settings.php. In your script
 * just check whether the code introduced by the user present in this array.
 * If it is not, the code is invalid.
 * 
 */

// Файл настроек / Options file
require_once('Settings.php');

/**
 * =================================================================================================
 * Скрипт вывода картинки. Не меняйте ничего далее.
 * Image output script. Do not change anything below.
 */

// Start session - the script relies on standart PHP sessions
session_start();

// Include main-class file
include(ProfiCaptchaOptions::CLASS_FILE_PATH.'ProfiCaptcha.class.php');

// Create object of picture generator
$ImageO = new ProfiCaptcha(
	ProfiCaptchaOptions::$Alphabet,
	ProfiCaptchaOptions::BACKGROUNDS_PATH,
	ProfiCaptchaOptions::FONTS_PATH,
	ProfiCaptchaOptions::SYMBOLS_COUNT,
	ProfiCaptchaOptions::$Correction
);
// Generate the code
$ImageO->Generate();

// Replace the first code in continer on overflow
if ( ProfiCaptchaOptions::CODES_COUNT_LIMIT != 0 // ... if no limit
	&& (isset($_SESSION[ProfiCaptchaOptions::SESSION_KEY])
	&& is_array($_SESSION[ProfiCaptchaOptions::SESSION_KEY])
	&& count($_SESSION[ProfiCaptchaOptions::SESSION_KEY]) > ProfiCaptchaOptions::CODES_COUNT_LIMIT) )
{
	unset($_SESSION[ProfiCaptchaOptions::SESSION_KEY][0]);
	$_SESSION[ProfiCaptchaOptions::SESSION_KEY] =
		array_values($_SESSION[ProfiCaptchaOptions::SESSION_KEY]);
}

// Add generated code to session array of codes
if ( !isset($_SESSION[ProfiCaptchaOptions::SESSION_KEY]) ||
	!is_array($_SESSION[ProfiCaptchaOptions::SESSION_KEY]) )
{
	$_SESSION[ProfiCaptchaOptions::SESSION_KEY] = array();
}
$_SESSION[ProfiCaptchaOptions::SESSION_KEY][] = $ImageO->GetGeneratedCode();

// output image
try
{
	if ( !ProfiCaptchaOptions::CREATE_FROM_IMAGE )
		$ImageO->PrintPicture(ProfiCaptchaOptions::$GenerationSize['width'], ProfiCaptchaOptions::$GenerationSize['height']);
	else
		$ImageO->PrintPicture();
}
catch (Exception $e)
{
	print "Sorry, error while generation picture / Ошибка генерации изобажения";
}

?>