text:
<?php

namespace Nette\Application\UI;

use Nette,
	Nette\Application,
	Nette\Application\Responses,
	Nette\Http,
	Nette\Reflection;

/**
 * Presenter component represents a webpage instance. It converts Request to IResponse.
 *
 * @author     David Grudl
 *
 * @property-read Nette\Application\Request $request
 * @property-read array|NULL $signal
 * @property-read string $action
 * @property      string $view
 * @property      string $layout
 * @property-read \stdClass $payload
 * @property-read bool $ajax
 * @property-read Nette\Application\Request $lastCreatedRequest
 * @property-read Nette\Http\SessionSection $flashSession
 * @property-read \SystemContainer|Nette\DI\Container $context
 * @property-read Nette\Application\Application $application
 * @property-read Nette\Http\Session $session
 * @property-read Nette\Security\User $user
 */
abstract class Presenter extends Control implements Application\IPresenter
{
	/** bad link handling {@link Presenter::$invalidLinkMode} */
	const INVALID_LINK_SILENT = 1,
		INVALID_LINK_WARNING = 2,
		INVALID_LINK_EXCEPTION = 3;

	/** @internal special parameter key */
	const SIGNAL_KEY = 'do',
		ACTION_KEY = 'action',
		FLASH_KEY = '_fid',
		DEFAULT_ACTION = 'default';

	/** @var int */
	public $invalidLinkMode;

	/** @var array of function(Presenter $sender, IResponse $response = NULL); Occurs when the presenter is shutting down */
	public $onShutdown;

	/** @var Nette\Application\Request */
	private $request;

	/** @var Nette\Application\IResponse */
	private $response;

	/** @var bool  automatically call canonicalize() */
	public $autoCanonicalize = TRUE;

	/** @var bool  use absolute Urls or paths? */
	public $absoluteUrls = FALSE;

	/** @var array */
	private $globalParams;

	/** @var array */
	private $globalState;

	/** @var array */
	private $globalStateSinces;

	/** @var string */
	private $action;

	/** @var string */
	private $view;

	/** @var string */
	private $layout;

	/** @var \stdClass */
	private $payload;

	/** @var string */
	private $signalReceiver;

	/** @var string */
	private $signal;

	/** @var bool */
	private $ajaxMode;

	/** @var bool */
	private $startupCheck;

	/** @var Nette\Application\Request */
	private $lastCreatedRequest;

	/** @var array */
	private $lastCreatedRequestFlag;

	/** @var \SystemContainer|Nette\DI\Container */
	private $context;

	public function __construct(Nette\DI\Container $context = NULL)
	{
		$this->context = $context;
		if ($context && $this->invalidLinkMode === NULL) {
			$this->invalidLinkMode = $context->parameters['productionMode'] ? self::INVALID_LINK_SILENT : self::INVALID_LINK_WARNING;
		}
	}

	/**
	 * @return Nette\Application\Request
	 */
	public function getRequest()
	{
		return $this->request;
	}

	/**
	 * Returns self.
	 * @return Presenter
	 */
	public function getPresenter($need = TRUE)
	{
		return $this;
	}

	/**
	 * Returns a name that uniquely identifies component.
	 * @return string
	 */
	public function getUniqueId()
	{
		return '';
	}

	/********************* interface IPresenter ****************d*g**/

	/**
	 * @return Nette\Application\IResponse
	 */
	public function run(Application\Request $request)
	{
		try {
			// STARTUP
			$this->request = $request;
			$this->payload = new \stdClass;
			$this->setParent($this->getParent(), $request->getPresenterName());

			if (!$this->getHttpResponse()->isSent()) {
				$this->getHttpResponse()->addHeader('Vary', 'X-Requested-With');
			}

			$this->initGlobalParameters();
			$this->checkRequirements($this->getReflection());
			$this->startup();
			if (!$this->startupCheck) {
				$class = $this->getReflection()->getMethod('startup')->getDeclaringClass()->getName();
				throw new Nette\InvalidStateException("Method $class::startup() or its descendant doesn't call parent::startup().");
			}
			// calls $this->action<Action>()
			$this->tryCall($this->formatActionMethod($this->getAction()), $this->params);

			// autoload components
			foreach ($this->globalParams as $id => $foo) {
				$this->getComponent($id, FALSE);
			}

			if ($this->autoCanonicalize) {
				$this->canonicalize();
			}
			if ($this->getHttpRequest()->isMethod('head')) {
				$this->terminate();
			}

			// SIGNAL HANDLING
			// calls $this->handle<Signal>()
			$this->processSignal();

			// RENDERING VIEW
			$this->beforeRender();
			// calls $this->render<View>()
			$this->tryCall($this->formatRenderMethod($this->getView()), $this->params);
			$this->afterRender();

			// save component tree persistent state
			$this->saveGlobalState();
			if ($this->isAjax()) {
				$this->payload->state = $this->getGlobalState();
			}

			// finish template rendering
			$this->sendTemplate();

		} catch (Application\AbortException $e) {
			// continue with shutting down
			if ($this->isAjax()) try {
				$hasPayload = (array) $this->payload; unset($hasPayload['state']);
				if ($this->response instanceof Responses\TextResponse && $this->isControlInvalid()) {
					$this->snippetMode = TRUE;
					$this->response->send($this->getHttpRequest(), $this->getHttpResponse());
					$this->sendPayload();

				} elseif (!$this->response && $hasPayload) { // back compatibility for use terminate() instead of sendPayload()
					$this->sendPayload();
				}
			} catch (Application\AbortException $e) { }

			if ($this->hasFlashSession()) {
				$this->getFlashSession()->setExpiration($this->response instanceof Responses\RedirectResponse ? '+ 30 seconds' : '+ 3 seconds');
			}

			// SHUTDOWN
			$this->onShutdown($this, $this->response);
			$this->shutdown($this->response);

			return $this->response;
		}
	}

	/**
	 * @return void
	 */
	protected function startup()
	{
		$this->startupCheck = TRUE;
	}

	/**
	 * Common render method.
	 * @return void
	 */
	protected function beforeRender()
	{
	}

	/**
	 * Common render method.
	 * @return void
	 */
	protected function afterRender()
	{
	}

	/**
	 * @param  Nette\Application\IResponse
	 * @return void
	 */
	protected function shutdown($response)
	{
	}

	/**
	 * Checks authorization.
	 * @return void
	 */
	public function checkRequirements($element)
	{
		$user = (array) $element->getAnnotation('User');
		if (in_array('loggedIn', $user, TRUE) && !$this->getUser()->isLoggedIn()) {
			throw new Application\ForbiddenRequestException;
		}
	}

	/********************* signal handling ****************d*g**/

	/**
	 * @return void
	 * @throws BadSignalException
	 */
	public function processSignal()
	{
		if ($this->signal === NULL) {
			return;
		}

		try {
			$component = $this->signalReceiver === '' ? $this : $this->getComponent($this->signalReceiver, FALSE);
		} catch (Nette\InvalidArgumentException $e) {}

		if (isset($e) || $component === NULL) {
			throw new BadSignalException("The signal receiver component '$this->signalReceiver' is not found.", NULL, isset($e) ? $e : NULL);

		} elseif (!$component instanceof ISignalReceiver) {
			throw new BadSignalException("The signal receiver component '$this->signalReceiver' is not ISignalReceiver implementor.");
		}

		$component->signalReceived($this->signal);
		$this->signal = NULL;
	}

	/**
	 * Returns pair signal receiver and name.
	 * @return array|NULL
	 */
	public function getSignal()
	{
		return $this->signal === NULL ? NULL : array($this->signalReceiver, $this->signal);
	}

	/**
	 * Checks if the signal receiver is the given one.
	 * @param  mixed  component or its id
	 * @param  string signal name (optional)
	 * @return bool
	 */
	public function isSignalReceiver($component, $signal = NULL)
	{
		if ($component instanceof Nette\ComponentModel\Component) {
			$component = $component === $this ? '' : $component->lookupPath(__CLASS__, TRUE);
		}

		if ($this->signal === NULL) {
			return FALSE;

		} elseif ($signal === TRUE) {
			return $component === ''
				|| strncmp($this->signalReceiver . '-', $component . '-', strlen($component) + 1) === 0;

		} elseif ($signal === NULL) {
			return $this->signalReceiver === $component;

		} else {
			return $this->signalReceiver === $component && strcasecmp($signal, $this->signal) === 0;
		}
	}

	/********************* rendering ****************d*g**/

	/**
	 * Returns current action name.
	 * @return string
	 */
	public function getAction($fullyQualified = FALSE)
	{
		return $fullyQualified ? ':' . $this->getName() . ':' . $this->action : $this->action;
	}

	/**
	 * Changes current action. Only alphanumeric characters are allowed.
	 * @param  string
	 * @return void
	 */
	public function changeAction($action)
	{
		if (is_string($action) && Nette\Utils\Strings::match($action, '#^[a-zA-Z0-9][a-zA-Z0-9_\x7f-\xff]*\z#')) {
			$this->action = $action;
			$this->view = $action;

		} else {
			$this->error('Action name is not alphanumeric string.');
		}
	}

	/**
	 * Returns current view.
	 * @return string
	 */
	public function getView()
	{
		return $this->view;
	}

	/**
	 * Changes current view. Any name is allowed.
	 * @param  string
	 * @return self
	 */
	public function setView($view)
	{
		$this->view = (string) $view;
		return $this;
	}

	/**
	 * Returns current layout name.
	 * @return string|FALSE
	 */
	public function getLayout()
	{
		return $this->layout;
	}

	/**
	 * Changes or disables layout.
	 * @param  string|FALSE
	 * @return self
	 */
	public function setLayout($layout)
	{
		$this->layout = $layout === FALSE ? FALSE : (string) $layout;
		return $this;
	}

	/**
	 * @return void
	 * @throws Nette\Application\BadRequestException if no template found
	 * @throws Nette\Application\AbortException
	 */
	public function sendTemplate()
	{
		$template = $this->getTemplate();
		if (!$template) {
			return;
		}

		if ($template instanceof Nette\Templating\IFileTemplate && !$template->getFile()) { // content template
			$files = $this->formatTemplateFiles();
			foreach ($files as $file) {
				if (is_file($file)) {
					$template->setFile($file);
					break;
				}
			}

			if (!$template->getFile()) {
				$file = preg_replace('#^.*([/\\\\].{1,70})\z#U', "\xE2\x80\xA6\$1", reset($files));
				$file = strtr($file, '/', DIRECTORY_SEPARATOR);
				$this->error("Page not found. Missing template '$file'.");
			}
		}

		$this->sendResponse(new Responses\TextResponse($template));
	}

	/**
	 * Finds layout template file name.
	 * @return string
	 * @internal
	 */
	public function findLayoutTemplateFile()
	{
		if ($this->layout === FALSE) {
			return;
		}
		$files = $this->formatLayoutTemplateFiles();
		foreach ($files as $file) {
			if (is_file($file)) {
				return $file;
			}
		}

		if ($this->layout) {
			$file = preg_replace('#^.*([/\\\\].{1,70})\z#U', "\xE2\x80\xA6\$1", reset($files));
			$file = strtr($file, '/', DIRECTORY_SEPARATOR);
			throw new Nette\FileNotFoundException("Layout not found. Missing template '$file'.");
		}
	}

	/**
	 * Formats layout template file names.
	 * @return array
	 */
	public function formatLayoutTemplateFiles()
	{
		$name = $this->getName();
		$presenter = substr($name, strrpos(':' . $name, ':'));
		$layout = $this->layout ? $this->layout : 'layout';
		$dir = dirname($this->getReflection()->getFileName());
		$dir = is_dir("$dir/templates") ? $dir : dirname($dir);
		$list = array(
			"$dir/templates/$presenter/@$layout.latte",
			"$dir/templates/$presenter.@$layout.latte",
			"$dir/templates/$presenter/@$layout.phtml",
			"$dir/templates/$presenter.@$layout.phtml",
		);
		do {
			$list[] = "$dir/templates/@$layout.latte";
			$list[] = "$dir/templates/@$layout.phtml";
			$dir = dirname($dir);
		} while ($dir && ($name = substr($name, 0, strrpos($name, ':'))));
		return $list;
	}

	/**
	 * Formats view template file names.
	 * @return array
	 */
	public function formatTemplateFiles()
	{
		$name = $this->getName();
		$presenter = substr($name, strrpos(':' . $name, ':'));
		$dir = dirname($this->getReflection()->getFileName());
		$dir = is_dir("$dir/templates") ? $dir : dirname($dir);
		return array(
			"$dir/templates/$presenter/$this->view.latte",
			"$dir/templates/$presenter.$this->view.latte",
			"$dir/templates/$presenter/$this->view.phtml",
			"$dir/templates/$presenter.$this->view.phtml",
		);
	}

	/**
	 * Formats action method name.
	 * @param  string
	 * @return string
	 */
	protected static function formatActionMethod($action)
	{
		return 'action' . $action;
	}

	/**
	 * Formats render view method name.
	 * @param  string
	 * @return string
	 */
	protected static function formatRenderMethod($view)
	{
		return 'render' . $view;
	}

	/********************* partial AJAX rendering ****************d*g**/

	/**
	 * @return \stdClass
	 */
	public function getPayload()
	{
		return $this->payload;
	}

	/**
	 * Is AJAX request?
	 * @return bool
	 */
	public function isAjax()
	{
		if ($this->ajaxMode === NULL) {
			$this->ajaxMode = $this->getHttpRequest()->isAjax();
		}
		return $this->ajaxMode;
	}

	/**
	 * Sends AJAX payload to the output.
	 * @return void
	 * @throws Nette\Application\AbortException
	 */
	public function sendPayload()
	{
		$this->sendResponse(new Responses\JsonResponse($this->payload));
	}

	/********************* navigation & flow ****************d*g**/

	/**
	 * Sends response and terminates presenter.
	 * @return void
	 * @throws Nette\Application\AbortException
	 */
	public function sendResponse(Application\IResponse $response)
	{
		$this->response = $response;
		$this->terminate();
	}

	/**
	 * Correctly terminates presenter.
	 * @return void
	 * @throws Nette\Application\AbortException
	 */
	public function terminate()
	{
		if (func_num_args() !== 0) {
			trigger_error(__METHOD__ . ' is not intended to send a Application\Response; use sendResponse() instead.', E_USER_WARNING);
			$this->sendResponse(func_get_arg(0));
		}
		throw new Application\AbortException();
	}

	/**
	 * Forward to another presenter or action.
	 * @param  string|Request
	 * @param  array|mixed
	 * @return void
	 * @throws Nette\Application\AbortException
	 */
	public function forward($destination, $args = array())
	{
		if ($destination instanceof Application\Request) {
			$this->sendResponse(new Responses\ForwardResponse($destination));
		}

		$this->createRequest($this, $destination, is_array($args) ? $args : array_slice(func_get_args(), 1), 'forward');
		$this->sendResponse(new Responses\ForwardResponse($this->lastCreatedRequest));
	}

	/**
	 * Redirect to another URL and ends presenter execution.
	 * @param  string
	 * @param  int HTTP error code
	 * @return void
	 * @throws Nette\Application\AbortException
	 */
	public function redirectUrl($url, $code = NULL)
	{
		if ($this->isAjax()) {
			$this->payload->redirect = (string) $url;
			$this->sendPayload();

		} elseif (!$code) {
			$code = $this->getHttpRequest()->isMethod('post')
				? Http\IResponse::S303_POST_GET
				: Http\IResponse::S302_FOUND;
		}
		$this->sendResponse(new Responses\RedirectResponse($url, $code));
	}

	/** @deprecated */
	function redirectUri($url, $code = NULL)
	{
		trigger_error(__METHOD__ . '() is deprecated; use ' . __CLASS__ . '::redirectUrl() instead.', E_USER_WARNING);
		$this->redirectUrl($url, $code);
	}

	/**
	 * Throws HTTP error.
	 * @param  string
	 * @param  int HTTP error code
	 * @return void
	 * @throws Nette\Application\BadRequestException
	 */
	public function error($message = NULL, $code = Http\IResponse::S404_NOT_FOUND)
	{
		throw new Application\BadRequestException($message, $code);
	}

	/**
	 * Link to myself.
	 * @return string
	 */
	public function backlink()
	{
		return $this->getAction(TRUE);
	}

	/**
	 * Returns the last created Request.
	 * @return Nette\Application\Request
	 * @internal
	 */
	public function getLastCreatedRequest()
	{
		return $this->lastCreatedRequest;
	}

	/**
	 * Returns the last created Request flag.
	 * @param  string
	 * @return bool
	 * @internal
	 */
	public function getLastCreatedRequestFlag($flag)
	{
		return !empty($this->lastCreatedRequestFlag[$flag]);
	}

	/**
	 * Conditional redirect to canonicalized URI.
	 * @return void
	 * @throws Nette\Application\AbortException
	 */
	public function canonicalize()
	{
		if (!$this->isAjax() && ($this->request->isMethod('get') || $this->request->isMethod('head'))) {
			try {
				$url = $this->createRequest($this, $this->action, $this->getGlobalState() + $this->request->getParameters(), 'redirectX');
			} catch (InvalidLinkException $e) {}
			if (isset($url) && !$this->getHttpRequest()->getUrl()->isEqual($url)) {
				$this->sendResponse(new Responses\RedirectResponse($url, Http\IResponse::S301_MOVED_PERMANENTLY));
			}
		}
	}

	/**
	 * Attempts to cache the sent entity by its last modification date.
	 * @param  string|int|DateTime  last modified time
	 * @param  string strong entity tag validator
	 * @param  mixed  optional expiration time
	 * @return void
	 * @throws Nette\Application\AbortException
	 * @deprecated
	 */
	public function lastModified($lastModified, $etag = NULL, $expire = NULL)
	{
		if ($expire !== NULL) {
			$this->getHttpResponse()->setExpiration($expire);
		}

		if (!$this->getHttpContext()->isModified($lastModified, $etag)) {
			$this->terminate();
		}
	}

	/**
	 * Request/URL factory.
	 * @param  PresenterComponent  base
	 * @param  string   destination in format "[[module:]presenter:]action" or "signal!" or "this"
	 * @param  array    array of arguments
	 * @param  string   forward|redirect|link
	 * @return string   URL
	 * @throws InvalidLinkException
	 * @internal
	 */
	protected function createRequest($component, $destination, array $args, $mode)
	{
		// note: createRequest supposes that saveState(), run() & tryCall() behaviour is final

		// cached services for better performance
		static $presenterFactory, $router, $refUrl;
		if ($presenterFactory === NULL) {
			$presenterFactory = $this->getApplication()->getPresenterFactory();
			$router = $this->getApplication()->getRouter();
			$refUrl = new Http\Url($this->getHttpRequest()->getUrl());
			$refUrl->setPath($this->getHttpRequest()->getUrl()->getScriptPath());
		}

		$this->lastCreatedRequest = $this->lastCreatedRequestFlag = NULL;

		// PARSE DESTINATION
		// 1) fragment
		$a = strpos($destination, '#');
		if ($a === FALSE) {
			$fragment = '';
		} else {
			$fragment = substr($destination, $a);
			$destination = substr($destination, 0, $a);
		}

		// 2) ?query syntax
		$a = strpos($destination, '?');
		if ($a !== FALSE) {
			parse_str(substr($destination, $a + 1), $args); // requires disabled magic quotes
			$destination = substr($destination, 0, $a);
		}

		// 3) URL scheme
		$a = strpos($destination, '//');
		if ($a === FALSE) {
			$scheme = FALSE;
		} else {
			$scheme = substr($destination, 0, $a);
			$destination = substr($destination, $a + 2);
		}

		// 4) signal or empty
		if (!$component instanceof Presenter || substr($destination, -1) === '!') {
			$signal = rtrim($destination, '!');
			$a = strrpos($signal, ':');
			if ($a !== FALSE) {
				$component = $component->getComponent(strtr(substr($signal, 0, $a), ':', '-'));
				$signal = (string) substr($signal, $a + 1);
			}
			if ($signal == NULL) {  // intentionally ==
				throw new InvalidLinkException("Signal must be non-empty string.");
			}
			$destination = 'this';
		}

		if ($destination == NULL) {  // intentionally ==
			throw new InvalidLinkException("Destination must be non-empty string.");
		}

		// 5) presenter: action
		$current = FALSE;
		$a = strrpos($destination, ':');
		if ($a === FALSE) {
			$action = $destination === 'this' ? $this->action : $destination;
			$presenter = $this->getName();
			$presenterClass = get_class($this);

		} else {
			$action = (string) substr($destination, $a + 1);
			if ($destination[0] === ':') { // absolute
				if ($a < 2) {
					throw new InvalidLinkException("Missing presenter name in '$destination'.");
				}
				$presenter = substr($destination, 1, $a - 1);

			} else { // relative
				$presenter = $this->getName();
				$b = strrpos($presenter, ':');
				if ($b === FALSE) { // no module
					$presenter = substr($destination, 0, $a);
				} else { // with module
					$presenter = substr($presenter, 0, $b + 1) . substr($destination, 0, $a);
				}
			}
			try {
				$presenterClass = $presenterFactory->getPresenterClass($presenter);
			} catch (Application\InvalidPresenterException $e) {
				throw new InvalidLinkException($e->getMessage(), NULL, $e);
			}
		}

		// PROCESS SIGNAL ARGUMENTS
		if (isset($signal)) { // $component must be IStatePersistent
			$reflection = new PresenterComponentReflection(get_class($component));
			if ($signal === 'this') { // means "no signal"
				$signal = '';
				if (array_key_exists(0, $args)) {
					throw new InvalidLinkException("Unable to pass parameters to 'this!' signal.");
				}

			} elseif (strpos($signal, self::NAME_SEPARATOR) === FALSE) {
				// counterpart of signalReceived() & tryCall()
				$method = $component->formatSignalMethod($signal);
				if (!$reflection->hasCallableMethod($method)) {
					throw new InvalidLinkException("Unknown signal '$signal', missing handler {$reflection->name}::$method()");
				}
				if ($args) { // convert indexed parameters to named
					self::argsToParams(get_class($component), $method, $args);
				}
			}

			// counterpart of IStatePersistent
			if ($args && array_intersect_key($args, $reflection->getPersistentParams())) {
				$component->saveState($args);
			}

			if ($args && $component !== $this) {
				$prefix = $component->getUniqueId() . self::NAME_SEPARATOR;
				foreach ($args as $key => $val) {
					unset($args[$key]);
					$args[$prefix . $key] = $val;
				}
			}
		}

		// PROCESS ARGUMENTS
		if (is_subclass_of($presenterClass, __CLASS__)) {
			if ($action === '') {
				$action = self::DEFAULT_ACTION;
			}

			$current = ($action === '*' || strcasecmp($action, $this->action) === 0) && $presenterClass === get_class($this);

			$reflection = new PresenterComponentReflection($presenterClass);
			if ($args || $destination === 'this') {
				// counterpart of run() & tryCall()
				$method = $presenterClass::formatActionMethod($action);
				if (!$reflection->hasCallableMethod($method)) {
					$method = $presenterClass::formatRenderMethod($action);
					if (!$reflection->hasCallableMethod($method)) {
						$method = NULL;
					}
				}

				// convert indexed parameters to named
				if ($method === NULL) {
					if (array_key_exists(0, $args)) {
						throw new InvalidLinkException("Unable to pass parameters to action '$presenter:$action', missing corresponding method.");
					}

				} elseif ($destination === 'this') {
					self::argsToParams($presenterClass, $method, $args, $this->params);

				} else {
					self::argsToParams($presenterClass, $method, $args);
				}
			}

			// counterpart of IStatePersistent
			if ($args && array_intersect_key($args, $reflection->getPersistentParams())) {
				$this->saveState($args, $reflection);
			}

			if ($mode === 'redirect') {
				$this->saveGlobalState();
			}

			$globalState = $this->getGlobalState($destination === 'this' ? NULL : $presenterClass);
			if ($current && $args) {
				$tmp = $globalState + $this->params;
				foreach ($args as $key => $val) {
					if (http_build_query(array($val)) !== (isset($tmp[$key]) ? http_build_query(array($tmp[$key])) : '')) {
						$current = FALSE;
						break;
					}
				}
			}
			$args += $globalState;
		}

		// ADD ACTION & SIGNAL & FLASH
		if ($action) {
			$args[self::ACTION_KEY] = $action;
		}
		if (!empty($signal)) {
			$args[self::SIGNAL_KEY] = $component->getParameterId($signal);
			$current = $current && $args[self::SIGNAL_KEY] === $this->getParameter(self::SIGNAL_KEY);
		}
		if (($mode === 'redirect' || $mode === 'forward') && $this->hasFlashSession()) {
			$args[self::FLASH_KEY] = $this->getParameter(self::FLASH_KEY);
		}

		$this->lastCreatedRequest = new Application\Request(
			$presenter,
			Application\Request::FORWARD,
			$args,
			array(),
			array()
		);
		$this->lastCreatedRequestFlag = array('current' => $current);

		if ($mode === 'forward' || $mode === 'test') {
			return;
		}

		// CONSTRUCT URL
		$url = $router->constructUrl($this->lastCreatedRequest, $refUrl);
		if ($url === NULL) {
			unset($args[self::ACTION_KEY]);
			$params = urldecode(http_build_query($args, NULL, ', '));
			throw new InvalidLinkException("No route for $presenter:$action($params)");
		}

		// make URL relative if possible
		if ($mode === 'link' && $scheme === FALSE && !$this->absoluteUrls) {
			$hostUrl = $refUrl->getHostUrl() . '/';
			if (strncmp($url, $hostUrl, strlen($hostUrl)) === 0) {
				$url = substr($url, strlen($hostUrl) - 1);
			}
		}

		return $url . $fragment;
	}

	/**
	 * Converts list of arguments to named parameters.
	 * @param  string  class name
	 * @param  string  method name
	 * @param  array   arguments
	 * @param  array   supplemental arguments
	 * @return void
	 * @throws InvalidLinkException
	 */
	private static function argsToParams($class, $method, & $args, $supplemental = array())
	{
		$i = 0;
		$rm = new \ReflectionMethod($class, $method);
		foreach ($rm->getParameters() as $param) {
			$name = $param->getName();
			if (array_key_exists($i, $args)) {
				$args[$name] = $args[$i];
				unset($args[$i]);
				$i++;

			} elseif (array_key_exists($name, $args)) {
				// continue with process

			} elseif (array_key_exists($name, $supplemental)) {
				$args[$name] = $supplemental[$name];

			} else {
				continue;
			}

			if ($args[$name] === NULL) {
				continue;
			}

			$def = $param->isDefaultValueAvailable() && $param->isOptional() ? $param->getDefaultValue() : NULL; // see PHP bug #62988
			$type = $param->isArray() ? 'array' : gettype($def);
			if (!PresenterComponentReflection::convertType($args[$name], $type)) {
				throw new InvalidLinkException("Invalid value for parameter '$name' in method $class::$method(), expected " . ($type === 'NULL' ? 'scalar' : $type) . ".");
			}

			if ($args[$name] === $def || ($def === NULL && is_scalar($args[$name]) && (string) $args[$name] === '')) {
				$args[$name] = NULL; // value transmit is unnecessary
			}
		}

		if (array_key_exists($i, $args)) {
			$method = $rm->getName();
			throw new InvalidLinkException("Passed more parameters than method $class::$method() expects.");
		}
	}

	/**
	 * Invalid link handler. Descendant can override this method to change default behaviour.
	 * @return string
	 * @throws InvalidLinkException
	 */
	protected function handleInvalidLink(InvalidLinkException $e)
	{
		if ($this->invalidLinkMode === self::INVALID_LINK_SILENT) {
			return '#';

		} elseif ($this->invalidLinkMode === self::INVALID_LINK_WARNING) {
			return 'error: ' . $e->getMessage();

		} else { // self::INVALID_LINK_EXCEPTION
			throw $e;
		}
	}

	/********************* request serialization ****************d*g**/

	/**
	 * Stores current request to session.
	 * @param  mixed  optional expiration time
	 * @return string key
	 */
	public function storeRequest($expiration = '+ 10 minutes')
	{
		$session = $this->getSession('Nette.Application/requests');
		do {
			$key = Nette\Utils\Strings::random(5);
		} while (isset($session[$key]));

		$session[$key] = array($this->getUser()->getId(), $this->request);
		$session->setExpiration($expiration, $key);
		return $key;
	}

	/**
	 * Restores request from session.
	 * @param  string key
	 * @return void
	 */
	public function restoreRequest($key)
	{
		$session = $this->getSession('Nette.Application/requests');
		if (!isset($session[$key]) || ($session[$key][0] !== NULL && $session[$key][0] !== $this->getUser()->getId())) {
			return;
		}
		$request = clone $session[$key][1];
		unset($session[$key]);
		$request->setFlag(Application\Request::RESTORED, TRUE);
		$params = $request->getParameters();
		$params[self::FLASH_KEY] = $this->getParameter(self::FLASH_KEY);
		$request->setParameters($params);
		$this->sendResponse(new Responses\ForwardResponse($request));
	}

	/********************* interface IStatePersistent ****************d*g**/

	/**
	 * Returns array of persistent components.
	 * This default implementation detects components by class-level annotation @persistent(cmp1, cmp2).
	 * @return array
	 */
	public static function getPersistentComponents()
	{
		return (array) Reflection\ClassType::from(/*5.2*func_get_arg(0)*//**/get_called_class()/**/)
			->getAnnotation('persistent');
	}

	/**
	 * Saves state information for all subcomponents to $this->globalState.
	 * @return array
	 */
	private function getGlobalState($forClass = NULL)
	{
		$sinces = & $this->globalStateSinces;

		if ($this->globalState === NULL) {
			$state = array();
			foreach ($this->globalParams as $id => $params) {
				$prefix = $id . self::NAME_SEPARATOR;
				foreach ($params as $key => $val) {
					$state[$prefix . $key] = $val;
				}
			}
			$this->saveState($state, $forClass ? new PresenterComponentReflection($forClass) : NULL);

			if ($sinces === NULL) {
				$sinces = array();
				foreach ($this->getReflection()->getPersistentParams() as $name => $meta) {
					$sinces[$name] = $meta['since'];
				}
			}

			$components = $this->getReflection()->getPersistentComponents();
			$iterator = $this->getComponents(TRUE, 'Nette\Application\UI\IStatePersistent');

			foreach ($iterator as $name => $component) {
				if ($iterator->getDepth() === 0) {
					// counts with Nette\Application\RecursiveIteratorIterator::SELF_FIRST
					$since = isset($components[$name]['since']) ? $components[$name]['since'] : FALSE; // FALSE = nonpersistent
				}
				$prefix = $component->getUniqueId() . self::NAME_SEPARATOR;
				$params = array();
				$component->saveState($params);
				foreach ($params as $key => $val) {
					$state[$prefix . $key] = $val;
					$sinces[$prefix . $key] = $since;
				}
			}

		} else {
			$state = $this->globalState;
		}

		if ($forClass !== NULL) {
			$since = NULL;
			foreach ($state as $key => $foo) {
				if (!isset($sinces[$key])) {
					$x = strpos($key, self::NAME_SEPARATOR);
					$x = $x === FALSE ? $key : substr($key, 0, $x);
					$sinces[$key] = isset($sinces[$x]) ? $sinces[$x] : FALSE;
				}
				if ($since !== $sinces[$key]) {
					$since = $sinces[$key];
					$ok = $since && (is_subclass_of($forClass, $since) || $forClass === $since);
				}
				if (!$ok) {
					unset($state[$key]);
				}
			}
		}

		return $state;
	}

	/**
	 * Permanently saves state information for all subcomponents to $this->globalState.
	 * @return void
	 */
	protected function saveGlobalState()
	{
		$this->globalParams = array();
		$this->globalState = $this->getGlobalState();
	}

	/**
	 * Initializes $this->globalParams, $this->signal & $this->signalReceiver, $this->action, $this->view. Called by run().
	 * @return void
	 * @throws Nette\Application\BadRequestException if action name is not valid
	 */
	private function initGlobalParameters()
	{
		// init $this->globalParams
		$this->globalParams = array();
		$selfParams = array();

		$params = $this->request->getParameters();
		if ($this->isAjax()) {
			$params += $this->request->getPost();
		}

		foreach ($params as $key => $value) {
			if (!preg_match('#^((?:[a-z0-9_]+-)*)((?!\d+\z)[a-z0-9_]+)\z#i', $key, $matches)) {
				continue;
			} elseif (!$matches[1]) {
				$selfParams[$key] = $value;
			} else {
				$this->globalParams[substr($matches[1], 0, -1)][$matches[2]] = $value;
			}
		}

		// init & validate $this->action & $this->view
		$this->changeAction(isset($selfParams[self::ACTION_KEY]) ? $selfParams[self::ACTION_KEY] : self::DEFAULT_ACTION);

		// init $this->signalReceiver and key 'signal' in appropriate params array
		$this->signalReceiver = $this->getUniqueId();
		if (isset($selfParams[self::SIGNAL_KEY])) {
			$param = $selfParams[self::SIGNAL_KEY];
			if (!is_string($param)) {
				$this->error('Signal name is not string.');
			}
			$pos = strrpos($param, '-');
			if ($pos) {
				$this->signalReceiver = substr($param, 0, $pos);
				$this->signal = substr($param, $pos + 1);
			} else {
				$this->signalReceiver = $this->getUniqueId();
				$this->signal = $param;
			}
			if ($this->signal == NULL) { // intentionally ==
				$this->signal = NULL;
			}
		}

		$this->loadState($selfParams);
	}

	/**
	 * Pops parameters for specified component.
	 * @param  string  component id
	 * @return array
	 * @internal
	 */
	public function popGlobalParameters($id)
	{
		if (isset($this->globalParams[$id])) {
			$res = $this->globalParams[$id];
			unset($this->globalParams[$id]);
			return $res;

		} else {
			return array();
		}
	}

	/********************* flash session ****************d*g**/

	/**
	 * Checks if a flash session namespace exists.
	 * @return bool
	 */
	public function hasFlashSession()
	{
		return !empty($this->params[self::FLASH_KEY])
			&& $this->getSession()->hasSection('Nette.Application.Flash/' . $this->params[self::FLASH_KEY]);
	}

	/**
	 * Returns session namespace provided to pass temporary data between redirects.
	 * @return Nette\Http\SessionSection
	 */
	public function getFlashSession()
	{
		if (empty($this->params[self::FLASH_KEY])) {
			$this->params[self::FLASH_KEY] = Nette\Utils\Strings::random(4);
		}
		return $this->getSession('Nette.Application.Flash/' . $this->params[self::FLASH_KEY]);
	}

	/********************* services ****************d*g**/

	/**
	 * @return void
	 */
	public function injectPrimary(Nette\DI\Container $context)
	{
		$this->context = $context;
	}

	/**
	 * Gets the context.
	 * @return \SystemContainer|Nette\DI\Container
	 */
	public function getContext()
	{
		return $this->context;
	}

	/**
	 * @deprecated
	 */
	public function getService($name)
	{
		return $this->context->getService($name);
	}

	/**
	 * @return Nette\Http\Request
	 */
	protected function getHttpRequest()
	{
		return $this->context->getByType('Nette\Http\IRequest');
	}

	/**
	 * @return Nette\Http\Response
	 */
	protected function getHttpResponse()
	{
		return $this->context->getByType('Nette\Http\IResponse');
	}

	/**
	 * @return Nette\Http\Context
	 */
	protected function getHttpContext()
	{
		return $this->context->getByType('Nette\Http\Context');
	}

	/**
	 * @return Nette\Application\Application
	 */
	public function getApplication()
	{
		return $this->context->getByType('Nette\Application\Application');
	}

	/**
	 * @param  string
	 * @return Nette\Http\Session|Nette\Http\SessionSection
	 */
	public function getSession($namespace = NULL)
	{
		$handler = $this->context->getByType('Nette\Http\Session');
		return $namespace === NULL ? $handler : $handler->getSection($namespace);
	}

	/**
	 * @return Nette\Security\User
	 */
	public function getUser()
	{
		return $this->context->getByType('Nette\Security\User');
	}

}


text:
{
    'result': {
        'taskid': str,  # new, not changeable
        'project': str,  # new, not changeable
        'url': str,  # new, not changeable
        'result': str,  # json string
        'updatetime': int,
    }
}

class ResultDB(object):
    """
    database for result
    """
    projects = set()  # projects in resultdb

    def save(self, project, taskid, url, result):
        raise NotImplementedError

    def select(self, project, fields=None, offset=0, limit=None):
        raise NotImplementedError

    def count(self, project):
        raise NotImplementedError

    def get(self, project, taskid, fields=None):
        raise NotImplementedError

    def drop(self, project):
        raise NotImplementedError

    def copy(self):
        '''
        database should be able to copy itself to create new connection

        it's implemented automatically by pyspider.database.connect_database
        if you are not create database connection via connect_database method,
        you should implement this
        '''
        raise NotImplementedError

redpajama_set_name: RedPajamaGithub


text:
class Subject < ActiveRecord::Base
    has_many :poem_subjects
    has_many :poems, :through => :poem_subjects
end


text:
<?php

class MyProject_Item_Db_Schema extends BaseZF_Item_Db_Schema_Abstract
{

}


text:
<?php

App::uses('CakeLog', 'Log');
App::uses('ClassRegistry', 'Utility');
App::uses('File', 'Utility');
App::uses('GeoPlugin', 'Install.Lib/Utility');
App::uses('TenantSettings', 'MtSites.Utility');
App::uses('IniReader', 'Configure');
App::uses('SchemaShell', 'Console/Command');

/**
 *  Funciones de instalacion Installer
 *
 * @package Install.Lib.Utility
 */
class Installer {

    public static function createDatabaseFile($data) {
        App::uses('File', 'Utility');
        App::uses('ConnectionManager', 'Model');

        $defaultConfig = array(
            'name' => 'default',
            'datasource' => Configure::read('Risto.dataSourceType'),
            'persistent' => false,
            'host' => 'localhost',
            'login' => 'root',
            'password' => '',
            'database' => 'risto',
            'schema' => null,
            'prefix' => null,
            'encoding' => 'UTF8',
            'port' => null,
        );

        $config = $defaultConfig;

        $database_file = copy(App::pluginPath('Install') . 'Config' . DS . 'CoreInstallFiles' . DS . 'database.php.default', APP . 'Config' . DS . 'database.php');

        if (!$database_file) {
            return __d('croogo', 'No se puede copiar el database.php para iniciar la instalación.');
        }

        foreach ($data['Install'] as $key => $value) {
            if (isset($data['Install'][$key])) {
                $config[$key] = $value;
            }
        }

        $file = new File(APP . 'Config' . DS . 'database.php', true);
        $content = $file->read();

        foreach ($config as $configKey => $configValue) {
            $content = str_replace('{default_' . $configKey . '}', $configValue, $content);
        }

        $write_to_file = $file->write($content);

        if (!$write_to_file) {
            return __d('croogo', 'No se puede escribir por el archivo database.php.');
        }

        $file->close();

        try {
            ConnectionManager::create('default', $config);
            $db = ConnectionManager::getDataSource('default');
        }
        catch (MissingConnectionException $e) {
            return __d('croogo', 'No se pude conectar al abase de datos: ') . $e->getMessage();
        }
        if (!$db->isConnected()) {
            return __d('croogo', 'No se puede conectar a la base de datos.');
        }

        return true;
    }

    public static function setupDatabase() {
        return self::loadFileSchema('Risto', 'default');
    }

    /**
    *
    *
    *   @param $file string FIle name
    *   @param $connection database connection
    *   @param $mode 'string' cant be "create" or "update". create is the default value
    **/
    public static function loadFileSchema( $name, $connection, $mode = 'create' ) {
        $archs = array(
            'generic'    => 'GenericTenant',
            'hotel'      => 'HotelTenant',
            'restaurant' => 'RestaurantTenant',
            );
        $m = new SchemaShell();
        $m->params = array(
            'force' => 1,
            'name' => $archs[$name],
            'plugin' => 'Risto',
            'connection' => $connection,
            'yes' => true,
            );
        $m->startup();
        $m->create();
        return true;
    }

    public static function createTenantsDir($site_slug = null)
    {
        $dir = new Folder(APP . 'Tenants' . DS . $site_slug, true);

        if( !$dir) {
            throw new CakeException('No se pudo crear el sitio: '.$site_slug. ' verifique que tenga permisos de escritura.');
        }

        return $dir;
    }

    public static function copyTenantSettingFile( $data = array() )
    {
        $site_slug = $data['Site']['alias'];
        $defaultSettingsConfig = array(
            'name' => 'default',
            'datasource' => Configure::read('Risto.dataSourceType'),
            'persistent' => false,
          );
        $installSettingsIniPath = App::pluginPath('Install') . 'Config' . DS . 'TenantInstallFiles' . DS . $data['Site']['type'] . DS;

        $IniSetting = new IniReader($installSettingsIniPath);
        $settings = $IniSetting->read( 'settings.ini' );
        $settings['Config']['timezone'] = $data['Site']['timezone'];
        $settings['Site']['ip'] = $data['Site']['ip'];
        $settings['Site']['name'] = $data['Site']['name'];
        $settings['Site']['alias'] = $data['Site']['alias'];

        $settings['Geo'] = GeoPlugin::locate($data['Site']['ip']);
        unset( $settings['Geo']['currency_symbol'] ); // el simbolo me rompe el settings.ini file
        TenantSettings::write( $settings, $site_slug);

        return true;
    }

    public static function dumpTenantDB( $data = null)
    {
        App::uses('ConnectionManager', 'Model');

        $slug = $data['Site']['alias'];

        $tenantDB = MtSites::getTenantDbName( $slug );

        // 1) Primero se corrobora si se puede crear la base de datos, sino se puede promover la desinstalacion del site
        $create_tenant = ConnectionManager::getDataSource('default')->query("CREATE DATABASE ".$tenantDB);

        if(!empty($create_tenant)) {
            throw new CakeException('No se pudo crear la base de datos del tenant: '.$tenantDB.'. Verifique que su usuario de conexión tenga los permisos suficientes. Tal vez la base de datos ya exista.');
        }

        MtSites::connectDatasourceWithCurrentTenant( $slug );
        $datasource = MtSites::getTenantDataSourceName( $slug );

        $tenantType = $data['Site']['type'];

        return self::loadFileSchema($tenantType, $datasource);

    }

    public static function createCoresFile () {
        $emailFilePath = APP . 'Config' . DS . 'email.php';
        $newEmailFilePath = App::pluginPath('Install') . 'Config' . DS . 'CoreInstallFiles' . DS . 'email.php.default';
        if ( !file_exists($emailFilePath) && !copy($newEmailFilePath, $emailFilePath) ) {
            throw new CakeException(__d('install', 'No se puede escribir el archivo email.php.'));
        }

        $newRistoConfigFilePath = App::pluginPath('Install') . 'Config' . DS . 'CoreInstallFiles' . DS .  'risto.php.install';
        $ristoFilePath =  APP . 'Config' . DS . 'risto.php';
        if( !file_exists($ristoFilePath) && !copy($newRistoConfigFilePath,$ristoFilePath)) {
            throw new CakeException(__d('install', 'No se puede escribir el archivo risto.php.'));
        }
        return true;
    }

    public static function checkPerms()
    {
        $res = true;

        if (!is_writable(TMP)) {
            $res = false;
        }

        if (!is_writable(APP . 'Config')) {
            $res = false;
        }

        if (!is_writable(APP . 'Controller')) {
            $res = false;
        }

        if (!is_writable(APP . 'Model')) {
            $res = false;
        }

        if (!is_writable(APP . 'Tenants')) {
            $res = false;
        }

        return $res;

    }

    /**
    *
    *
    *   @return integer 0 si no esta instalada, 1 si estan los archivos pero no hay Bases de Datos instaladas y 2 si esta completamente instalada
    **/
    public static function checkAppInstalled()
    {
        $res = 0;
        if( file_exists(APP . 'Config' . DS . 'database.php') && file_exists(APP . 'Config' . DS . 'risto.php') ) {
            // Si exxiste los dos hacemos un checkeo si existen por lo menos una tabla
            $res++;
            $checkUserAdmin = Installer::check_table_exists();
            if ( $checkUserAdmin ) {
                $res++;
            }
        }
        return $res;
    }

    public static function check_table_exists()
    {
        $db = ConnectionManager::getDataSource('default');
        $tables = $db->listSources();
        // De existir tabla, suponemos paso el apso dos en donde se crea la estructura y se coloca los dos primeros users, aun asi debe pasar al metodo adminuser para añadir un ter usuario antes de comnzar con la carga de los tenants
        if(count($tables))
        {
            App::import('model','Users.User');
            $user = new User();
            $geUserCount = $user->find("count");
            if($geUserCount<3)
            {
                return false;
            }
            else if($geUserCount>=3)
            {
                return true;
            }
        }

        return count($tables);
    }
    public static function cancelInstall()
    {

        $database = new File(APP . 'Config' . DS . 'database.php');
        if($database->exists())
        {
            // Si existe la base de datos, entoncs debemos de elimanr todas las tablas
            try {
                $db = ConnectionManager::getDataSource('default');
                $tables = $db->listSources();
                if(!empty($tables))
                {
                    foreach($tables as $index => $tablename)
                    {
                        $db->query("DROP TABLE IF EXISTS ".$tablename.";");
                    }
                }
            }
            catch (MissingConnectionException $e) {
                return __d('croogo', 'No se pude conectar al abase de datos: ') . $e->getMessage();
            }
            if($database->delete())
            {
                return true;
            }
            else
            {
                return __d('croogo','No se puede borrar el database.php, corrobore los permisos de escritura sobre este archivo.');
            }
        }
        else
        {
            return true;
        }
    }

    public static function deleteSite( $site_alias = null )
    {
        self::_removeDatabase( $site_alias );
        self::_deleteTenantFolder( $site_alias );
        return true;
    }

    public static function _removeDatabase($site_alias) {
        App::uses('ConnectionManager', 'Model');

        $db = ConnectionManager::getDataSource('default');
        $tenantDB = $db->config['database']."_".$site_alias;
        $delete_db = $db->query("DROP DATABASE IF EXISTS ".$tenantDB);

        return true;
    }

    public static function _deleteTenantFolder($site_alias) {
        App::uses('Folder', 'Utility');

        $folder = new Folder( APP . 'Tenants' . DS . $site_alias);
        $folder->delete();

        return true;
    }
}


text:
// DlgAggroStatistics.cpp : implementation file
//

#include "stdafx.h"
#include "WinDE.h"
#include "DlgAggroStatistics.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// DlgAggroStatistics dialog

DlgAggroStatistics::DlgAggroStatistics(CWnd* pParent /*=NULL*/)
	: CTabPageSSL(DlgAggroStatistics::IDD, pParent)
{
	//{{AFX_DATA_INIT(DlgAggroStatistics)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
}

void DlgAggroStatistics::DoDataExchange(CDataExchange* pDX)
{
	CTabPageSSL::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(DlgAggroStatistics)
	DDX_Control(pDX, IDC_MSCHART1, m_ChartControl);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(DlgAggroStatistics, CTabPageSSL)
	//{{AFX_MSG_MAP(DlgAggroStatistics)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// DlgAggroStatistics message handlers

BOOL DlgAggroStatistics::OnInitDialog()
{
	CTabPageSSL::OnInitDialog();

	UpdateAggroChart();

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

//--------------------------------------------------------
// Author -Alex .C. Punnen
// email - alexcpn@hotmail.com
// Date  - 24/May/2003
//--------------------------------------------------------

int DlgAggroStatistics::UpdateAggroChart()
{
	COleSafeArray saRet;
	SAFEARRAYBOUND sab[2];
	CString csTemp;
	AggroMobs aggro_mobs;
	long index[2] = {0,0}; //a 2D graph needs a 2D array as index array
	BSTR bstr;
	index[0]=1;

	csTemp.Format("%s", "Aggro Mobs");
	aggro_mobs.header = csTemp;

	csTemp.Format("%f", GetAggroGoodPercent());
	aggro_mobs.aggro_evil =csTemp;

	csTemp.Format("%f",GetAggroEvilPercent());
	aggro_mobs.aggro_good =csTemp;

	csTemp.Format("%f",GetAggroNeutPercent());
	aggro_mobs.aggro_neut = csTemp;

	csTemp.Format("%f",GetAggroEvilRacePercent());
	aggro_mobs.aggro_evilrace = csTemp;

	csTemp.Format("%f",GetAggroGoodRacePercent());
	aggro_mobs.aggro_goodrace = csTemp;

	csTemp.Format("%f",GetAggroAllPercent());
	aggro_mobs.aggro_all = csTemp;

	csTemp.Format("%f", GetNonAggroPercent());
	aggro_mobs.not_aggro = csTemp;

	sab[0].cElements =1;// give this exact
	sab[1].cElements = 8; //number of columns + 1 (because the first column is where we put
						// the row labels - ie in 1.1, 2.1, 3.1, 4,1 etc

	sab[0].lLbound = sab[1].lLbound = 1;

	m_ChartControl.SetShowLegend(TRUE);

	saRet.Create(VT_BSTR, 2, sab);

	index[1]=1;
	bstr = aggro_mobs.header.AllocSysString(); // Row label
	saRet.PutElement(index, bstr);

	index[1]=2;

	bstr = aggro_mobs.aggro_evil.AllocSysString(); // Data for column 1
	::SysFreeString(bstr);
	saRet.PutElement(index, bstr);

	index[1]=3;
	bstr = aggro_mobs.aggro_good.AllocSysString(); // Data for column 2
	::SysFreeString(bstr);
	saRet.PutElement(index, bstr);

	index[1]=4;
	bstr = aggro_mobs.aggro_neut.AllocSysString(); // Data for column 3
	::SysFreeString(bstr);
	saRet.PutElement(index, bstr);

	index[1]=5;
	bstr = aggro_mobs.aggro_evilrace.AllocSysString();// Data for column 4
    ::SysFreeString(bstr);
	saRet.PutElement(index, bstr);

	index[1]=6;
	bstr = aggro_mobs.aggro_goodrace.AllocSysString();// Data for column 4
    ::SysFreeString(bstr);
	saRet.PutElement(index, bstr);

	index[1]=7;
	bstr = aggro_mobs.aggro_all.AllocSysString();// Data for column 4
    ::SysFreeString(bstr);
	saRet.PutElement(index, bstr);

	index[1]=8;
	bstr = aggro_mobs.not_aggro.AllocSysString();// Data for column 4
    ::SysFreeString(bstr);
	saRet.PutElement(index, bstr);

    m_ChartControl.SetChartData(saRet.Detach());

	m_ChartControl.SetRowCount(1);
	//m_ChartControl.SetRowLabel("Agressive Mobs");
	m_ChartControl.SetColumnLabelCount(7);
	m_ChartControl.SetColumn(1);
	m_ChartControl.SetColumnLabel("Aggro Evil");
	m_ChartControl.SetColumn(2);
	m_ChartControl.SetColumnLabel("Aggro Good");
	m_ChartControl.SetColumn(3);
	m_ChartControl.SetColumnLabel("Aggro Neutral");
	m_ChartControl.SetColumn(4);
	m_ChartControl.SetColumnLabel("Aggro Evil Race");
	m_ChartControl.SetColumn(5);
	m_ChartControl.SetColumnLabel("Aggro Good Race");
	m_ChartControl.SetColumn(6);
	m_ChartControl.SetColumnLabel("Agressive");
	m_ChartControl.SetColumn(7);
	m_ChartControl.SetColumnLabel("Not Agressive");

	//m_ChartControl.SetAllowSelections(false);

	return 1;

}


text:
using content::BrowserThread;
using content::InterstitialPage;
using content::OpenURLParams;
using content::Referrer;
using content::UserMetricsAction;
using content::WebContents;

// For malware interstitial pages, we link the problematic URL to Google's
// diagnostic page.
#if defined(GOOGLE_CHROME_BUILD)
static const char* const kSbDiagnosticUrl =
    "http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=%s&client=googlechrome";
#else
static const char* const kSbDiagnosticUrl =
    "http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=%s&client=chromium";
#endif

static const char* const kSbReportPhishingErrorUrl =
    "http://www.google.com/safebrowsing/report_error/";

// URL for the "Learn more" link on the multi threat malware blocking page.
static const char* const kLearnMoreMalwareUrl =
    "https://www.google.com/support/bin/answer.py?answer=45449&topic=360"
    "&sa=X&oi=malwarewarninglink&resnum=1&ct=help";

// URL for the "Learn more" link on the phishing blocking page.
static const char* const kLearnMorePhishingUrl =
    "https://www.google.com/support/bin/answer.py?answer=106318";

// URL for the "Safe Browsing Privacy Policies" link on the blocking page.
// Note: this page is not yet localized.
static const char* const kSbPrivacyPolicyUrl =
    "http://www.google.com/intl/en_us/privacy/browsing.html";

static const char* const kSbDiagnosticHtml =
    "%s";

static const char* const kPLinkHtml =
    "%s";

static const char* const kPrivacyLinkHtml =
    "%s";

// After a malware interstitial where the user opted-in to the report
// but clicked "proceed anyway", we delay the call to
// MalwareDetails::FinishCollection() by this much time (in
// milliseconds).
static const int64 kMalwareDetailsProceedDelayMilliSeconds = 3000;

// The commands returned by the page when the user performs an action.
static const char* const kShowDiagnosticCommand = "showDiagnostic";
static const char* const kReportErrorCommand = "reportError";
static const char* const kLearnMoreCommand = "learnMore";
static const char* const kShowPrivacyCommand = "showPrivacy";
static const char* const kProceedCommand = "proceed";
static const char* const kTakeMeBackCommand = "takeMeBack";
static const char* const kDoReportCommand = "doReport";
static const char* const kDontReportCommand = "dontReport";
static const char* const kDisplayCheckBox = "displaycheckbox";
static const char* const kBoxChecked = "boxchecked";
// Special command that we use when the user navigated away from the
// page.  E.g., closed the tab or the window.  This is only used by
// RecordUserReactionTime.
static const char* const kNavigatedAwayMetaCommand = "closed";

// static
SafeBrowsingBlockingPageFactory* SafeBrowsingBlockingPage::factory_ = NULL;

static base::LazyInstance<SafeBrowsingBlockingPage::UnsafeResourceMap>
    g_unsafe_resource_map = LAZY_INSTANCE_INITIALIZER;

// The default SafeBrowsingBlockingPageFactory.  Global, made a singleton so we
// don't leak it.
class SafeBrowsingBlockingPageFactoryImpl
    : public SafeBrowsingBlockingPageFactory {
 public:
  SafeBrowsingBlockingPage* CreateSafeBrowsingPage(
      SafeBrowsingService* service,
      WebContents* web_contents,
      const SafeBrowsingBlockingPage::UnsafeResourceList& unsafe_resources) {
    return new SafeBrowsingBlockingPage(service, web_contents,
                                        unsafe_resources);
  }

 private:
  friend struct base::DefaultLazyInstanceTraits<
      SafeBrowsingBlockingPageFactoryImpl>;

  SafeBrowsingBlockingPageFactoryImpl() { }

  DISALLOW_COPY_AND_ASSIGN(SafeBrowsingBlockingPageFactoryImpl);
};

static base::LazyInstance<SafeBrowsingBlockingPageFactoryImpl>
    g_safe_browsing_blocking_page_factory_impl = LAZY_INSTANCE_INITIALIZER;

SafeBrowsingBlockingPage::SafeBrowsingBlockingPage(
    SafeBrowsingService* sb_service,
    WebContents* web_contents,
    const UnsafeResourceList& unsafe_resources)
    : malware_details_proceed_delay_ms_(
          kMalwareDetailsProceedDelayMilliSeconds),
      sb_service_(sb_service),
      report_loop_(NULL),
      is_main_frame_load_blocked_(IsMainPageLoadBlocked(unsafe_resources)),
      unsafe_resources_(unsafe_resources),
      proceeded_(false),
      web_contents_(web_contents),
      url_(unsafe_resources[0].url) {
  RecordUserAction(SHOW);
  if (!is_main_frame_load_blocked_) {
    navigation_entry_index_to_remove_ =
        web_contents->GetController().GetLastCommittedEntryIndex();
  } else {
    navigation_entry_index_to_remove_ = -1;
  }

  // Start computing malware details. They will be sent only
  // if the user opts-in on the blocking page later.
  // If there's more than one malicious resources, it means the user
  // clicked through the first warning, so we don't prepare additional
  // reports.
  if (unsafe_resources.size() == 1 &&
      unsafe_resources[0].threat_type == SafeBrowsingService::URL_MALWARE &&
      malware_details_ == NULL &&
      CanShowMalwareDetailsOption()) {
    malware_details_ = MalwareDetails::NewMalwareDetails(
        sb_service_, web_contents, unsafe_resources[0]);
  }

  interstitial_page_ = InterstitialPage::Create(
      web_contents, IsMainPageLoadBlocked(unsafe_resources), url_, this);
}

bool SafeBrowsingBlockingPage::CanShowMalwareDetailsOption() {
  return (!web_contents_->GetBrowserContext()->IsOffTheRecord() &&
          web_contents_->GetURL().SchemeIs(chrome::kHttpScheme));
}

SafeBrowsingBlockingPage::~SafeBrowsingBlockingPage() {
}

std::string SafeBrowsingBlockingPage::GetHTMLContents() {
  // Load the HTML page and create the template components.
  DictionaryValue strings;
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  std::string html;

  if (unsafe_resources_.empty()) {
    NOTREACHED();
    return std::string();
  }

  if (unsafe_resources_.size() > 1) {
    PopulateMultipleThreatStringDictionary(&strings);
    html = rb.GetRawDataResource(
        IDR_SAFE_BROWSING_MULTIPLE_THREAT_BLOCK,
        ui::SCALE_FACTOR_NONE).as_string();
    is_malware_interstitial_ = true;
  } else {
    SafeBrowsingService::UrlCheckResult threat_type =
        unsafe_resources_[0].threat_type;
    if (threat_type == SafeBrowsingService::URL_MALWARE) {
      PopulateMalwareStringDictionary(&strings);
      html = rb.GetRawDataResource(
          IDR_SAFE_BROWSING_MALWARE_BLOCK,
          ui::SCALE_FACTOR_NONE).as_string();
      is_malware_interstitial_ = true;
    } else {  // Phishing.
      DCHECK(threat_type == SafeBrowsingService::URL_PHISHING ||
             threat_type == SafeBrowsingService::CLIENT_SIDE_PHISHING_URL);
      PopulatePhishingStringDictionary(&strings);
      html = rb.GetRawDataResource(
          IDR_SAFE_BROWSING_PHISHING_BLOCK,
          ui::SCALE_FACTOR_NONE).as_string();
      is_malware_interstitial_ = false;
    }
  }
  interstitial_show_time_ = base::TimeTicks::Now();
  return jstemplate_builder::GetTemplatesHtml(html, &strings, "template_root");
}

void SafeBrowsingBlockingPage::PopulateStringDictionary(
    DictionaryValue* strings,
    const string16& title,
    const string16& headline,
    const string16& description1,
    const string16& description2,
    const string16& description3) {
  strings->SetString("title", title);
  strings->SetString("headLine", headline);
  strings->SetString("description1", description1);
  strings->SetString("description2", description2);
  strings->SetString("description3", description3);
  strings->SetBoolean("proceedDisabled",
                      IsPrefEnabled(prefs::kSafeBrowsingProceedAnywayDisabled));
}

void SafeBrowsingBlockingPage::PopulateMultipleThreatStringDictionary(
    DictionaryValue* strings) {
  bool malware = false;
  bool phishing = false;

  string16 malware_label =
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_LABEL);
  string16 malware_link =
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_DIAGNOSTIC_PAGE);
  string16 phishing_label =
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_LABEL);
  string16 phishing_link =
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_REPORT_ERROR);

  ListValue* error_strings = new ListValue;
  for (UnsafeResourceList::const_iterator iter = unsafe_resources_.begin();
       iter != unsafe_resources_.end(); ++iter) {
    const SafeBrowsingService::UnsafeResource& resource = *iter;
    SafeBrowsingService::UrlCheckResult threat_type = resource.threat_type;
    DictionaryValue* current_error_strings = new DictionaryValue;
    if (threat_type == SafeBrowsingService::URL_MALWARE) {
      malware = true;
      current_error_strings->SetString("type", "malware");
      current_error_strings->SetString("typeLabel", malware_label);
      current_error_strings->SetString("errorLink", malware_link);
    } else {
      DCHECK(threat_type == SafeBrowsingService::URL_PHISHING ||
             threat_type == SafeBrowsingService::CLIENT_SIDE_PHISHING_URL);
      phishing = true;
      current_error_strings->SetString("type", "phishing");
      current_error_strings->SetString("typeLabel", phishing_label);
      current_error_strings->SetString("errorLink", phishing_link);
    }
    current_error_strings->SetString("url", resource.url.spec());
    error_strings->Append(current_error_strings);
  }
  strings->Set("errors", error_strings);
  DCHECK(phishing || malware);

  if (malware && phishing) {
    PopulateStringDictionary(
        strings,
        // Use the malware headline, it is the scariest one.
        l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MULTI_THREAT_TITLE),
        l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_HEADLINE),
        l10n_util::GetStringFUTF16(IDS_SAFE_BROWSING_MULTI_THREAT_DESCRIPTION1,
                                   UTF8ToUTF16(web_contents_->GetURL().host())),
        l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MULTI_THREAT_DESCRIPTION2),
        string16());
  } else if (malware) {
    // Just malware.
    PopulateStringDictionary(
        strings,
        l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_TITLE),
        l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_HEADLINE),
        l10n_util::GetStringFUTF16(IDS_SAFE_BROWSING_MULTI_MALWARE_DESCRIPTION1,
                                   UTF8ToUTF16(web_contents_->GetURL().host())),
        l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MULTI_MALWARE_DESCRIPTION2),
        l10n_util::GetStringUTF16(
            IDS_SAFE_BROWSING_MULTI_MALWARE_DESCRIPTION3));
  } else {
    // Just phishing.
    PopulateStringDictionary(
        strings,
        l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_TITLE),
        l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_HEADLINE),
        l10n_util::GetStringFUTF16(
            IDS_SAFE_BROWSING_MULTI_PHISHING_DESCRIPTION1,
            UTF8ToUTF16(web_contents_->GetURL().host())),
        string16(),
        string16());
  }

  strings->SetString("confirm_text",
                     l10n_util::GetStringUTF16(
                         IDS_SAFE_BROWSING_MULTI_MALWARE_DESCRIPTION_AGREE));
  strings->SetString("continue_button",
                     l10n_util::GetStringUTF16(
                         IDS_SAFE_BROWSING_MULTI_MALWARE_PROCEED_BUTTON));
  strings->SetString("back_button",
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_BACK_BUTTON));
  strings->SetString("textdirection", base::i18n::IsRTL() ? "rtl" : "ltr");
}

void SafeBrowsingBlockingPage::PopulateMalwareStringDictionary(
    DictionaryValue* strings) {
  std::string diagnostic_link = base::StringPrintf(kSbDiagnosticHtml,
      l10n_util::GetStringUTF8(
        IDS_SAFE_BROWSING_MALWARE_DIAGNOSTIC_PAGE).c_str());

  strings->SetString("badURL", url_.host());
  // Check to see if we're blocking the main page, or a sub-resource on the
  // main page.
  string16 description1, description3, description5;
  if (is_main_frame_load_blocked_) {
    description1 = l10n_util::GetStringFUTF16(
        IDS_SAFE_BROWSING_MALWARE_DESCRIPTION1, UTF8ToUTF16(url_.host()));
  } else {
    description1 = l10n_util::GetStringFUTF16(
        IDS_SAFE_BROWSING_MALWARE_DESCRIPTION4,
        UTF8ToUTF16(web_contents_->GetURL().host()),
        UTF8ToUTF16(url_.host()));
  }

  std::string proceed_link = base::StringPrintf(kPLinkHtml,
      l10n_util::GetStringUTF8(IDS_SAFE_BROWSING_MALWARE_PROCEED_LINK).c_str());
  description3 =
      l10n_util::GetStringFUTF16(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION3,
                                 UTF8ToUTF16(proceed_link));

  PopulateStringDictionary(
      strings,
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_TITLE),
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_HEADLINE),
      description1,
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION2),
      description3);

  description5 =
      l10n_util::GetStringFUTF16(IDS_SAFE_BROWSING_MALWARE_DESCRIPTION5,
                                 UTF8ToUTF16(url_.host()),
                                 UTF8ToUTF16(url_.host()),
                                 UTF8ToUTF16(diagnostic_link));

  strings->SetString("description5", description5);

  strings->SetString("back_button",
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_BACK_BUTTON));
  strings->SetString("proceed_link",
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_PROCEED_LINK));
  strings->SetString("textdirection", base::i18n::IsRTL() ? "rtl" : "ltr");

  if (!CanShowMalwareDetailsOption()) {
    strings->SetBoolean(kDisplayCheckBox, false);
  } else {
    // Show the checkbox for sending malware details.
    strings->SetBoolean(kDisplayCheckBox, true);

    std::string privacy_link = base::StringPrintf(
        kPrivacyLinkHtml,
        l10n_util::GetStringUTF8(
            IDS_SAFE_BROWSING_PRIVACY_POLICY_PAGE).c_str());

    strings->SetString("confirm_text",
                       l10n_util::GetStringFUTF16(
                           IDS_SAFE_BROWSING_MALWARE_REPORTING_AGREE,
                           UTF8ToUTF16(privacy_link)));
    if (IsPrefEnabled(prefs::kSafeBrowsingReportingEnabled))
      strings->SetString(kBoxChecked, "yes");
    else
      strings->SetString(kBoxChecked, "");
  }
}

void SafeBrowsingBlockingPage::PopulatePhishingStringDictionary(
    DictionaryValue* strings) {
  std::string proceed_link = base::StringPrintf(
      kPLinkHtml,
      l10n_util::GetStringUTF8(
          IDS_SAFE_BROWSING_PHISHING_PROCEED_LINK).c_str());
  string16 description3 = l10n_util::GetStringFUTF16(
      IDS_SAFE_BROWSING_PHISHING_DESCRIPTION3,
      UTF8ToUTF16(proceed_link));

  PopulateStringDictionary(
      strings,
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_TITLE),
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_HEADLINE),
      l10n_util::GetStringFUTF16(IDS_SAFE_BROWSING_PHISHING_DESCRIPTION1,
                                 UTF8ToUTF16(url_.host())),
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_DESCRIPTION2),
      description3);

  strings->SetString("back_button",
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_BACK_BUTTON));
  strings->SetString("report_error",
      l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_REPORT_ERROR));
  strings->SetString("textdirection", base::i18n::IsRTL() ? "rtl" : "ltr");
}

void SafeBrowsingBlockingPage::CommandReceived(const std::string& cmd) {
  std::string command(cmd);  // Make a local copy so we can modify it.
  // The Jasonified response has quotes, remove them.
  if (command.length() > 1 && command[0] == '"') {
    command = command.substr(1, command.length() - 2);
  }
  RecordUserReactionTime(command);
  if (command == kDoReportCommand) {
    SetReportingPreference(true);
    return;
  }

  if (command == kDontReportCommand) {
    SetReportingPreference(false);
    return;
  }

  if (command == kLearnMoreCommand) {
    // User pressed "Learn more".
    GURL url;
    SafeBrowsingService::UrlCheckResult threat_type =
        unsafe_resources_[0].threat_type;
    if (threat_type == SafeBrowsingService::URL_MALWARE) {
      url = google_util::AppendGoogleLocaleParam(GURL(kLearnMoreMalwareUrl));
    } else if (threat_type == SafeBrowsingService::URL_PHISHING ||
               threat_type == SafeBrowsingService::CLIENT_SIDE_PHISHING_URL) {
      url = google_util::AppendGoogleLocaleParam(GURL(kLearnMorePhishingUrl));
    } else {
      NOTREACHED();
    }

    OpenURLParams params(
        url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, false);
    web_contents_->OpenURL(params);
    return;
  }

  if (command == kShowPrivacyCommand) {
    // User pressed "Safe Browsing privacy policy".
    GURL url(kSbPrivacyPolicyUrl);
    OpenURLParams params(
        url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK, false);
    web_contents_->OpenURL(params);
    return;
  }

  bool proceed_blocked = false;
  if (command == kProceedCommand) {
    if (IsPrefEnabled(prefs::kSafeBrowsingProceedAnywayDisabled)) {
      proceed_blocked = true;
    } else {
      interstitial_page_->Proceed();
      // |this| has been deleted after Proceed() returns.
      return;
    }
  }

  if (command == kTakeMeBackCommand || proceed_blocked) {
    if (is_main_frame_load_blocked_) {
      // If the load is blocked, we want to close the interstitial and discard
      // the pending entry.
      interstitial_page_->DontProceed();
      // |this| has been deleted after DontProceed() returns.
      return;
    }

    // Otherwise the offending entry has committed, and we need to go back or
    // to a safe page.  We will close the interstitial when that page commits.
    if (web_contents_->GetController().CanGoBack()) {
      web_contents_->GetController().GoBack();
    } else {
      web_contents_->GetController().LoadURL(
          GURL(chrome::kChromeUINewTabURL),
          content::Referrer(),
          content::PAGE_TRANSITION_START_PAGE,
          std::string());
    }
    return;
  }

  // The "report error" and "show diagnostic" commands can have a number
  // appended to them, which is the index of the element they apply to.
  int element_index = 0;
  size_t colon_index = command.find(':');
  if (colon_index != std::string::npos) {
    DCHECK(colon_index < command.size() - 1);
    bool result = base::StringToInt(base::StringPiece(command.begin() +
                                                      colon_index + 1,
                                                      command.end()),
                                    &element_index);
    command = command.substr(0, colon_index);
    DCHECK(result);
  }

  if (element_index >= static_cast<int>(unsafe_resources_.size())) {
    NOTREACHED();
    return;
  }

  std::string bad_url_spec = unsafe_resources_[element_index].url.spec();
  if (command == kReportErrorCommand) {
    // User pressed "Report error" for a phishing site.
    // Note that we cannot just put a link in the interstitial at this point.
    // It is not OK to navigate in the context of an interstitial page.
    SafeBrowsingService::UrlCheckResult threat_type =
        unsafe_resources_[element_index].threat_type;
    DCHECK(threat_type == SafeBrowsingService::URL_PHISHING ||
           threat_type == SafeBrowsingService::CLIENT_SIDE_PHISHING_URL);
    GURL report_url =
        safe_browsing_util::GeneratePhishingReportUrl(
            kSbReportPhishingErrorUrl,
            bad_url_spec,
            threat_type == SafeBrowsingService::CLIENT_SIDE_PHISHING_URL);
    OpenURLParams params(
        report_url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK,
        false);
    web_contents_->OpenURL(params);
    return;
  }

  if (command == kShowDiagnosticCommand) {
    // We're going to take the user to Google's SafeBrowsing diagnostic page.
    std::string diagnostic =
        base::StringPrintf(kSbDiagnosticUrl,
            net::EscapeQueryParamValue(bad_url_spec, true).c_str());
    GURL diagnostic_url(diagnostic);
    diagnostic_url = google_util::AppendGoogleLocaleParam(diagnostic_url);
    DCHECK(unsafe_resources_[element_index].threat_type ==
           SafeBrowsingService::URL_MALWARE);
    OpenURLParams params(
        diagnostic_url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_LINK,
        false);
    web_contents_->OpenURL(params);
    return;
  }

  NOTREACHED() << "Unexpected command: " << command;
}

void SafeBrowsingBlockingPage::OverrideRendererPrefs(
      content::RendererPreferences* prefs) {
  Profile* profile = Profile::FromBrowserContext(
      web_contents_->GetBrowserContext());
  renderer_preferences_util::UpdateFromSystemSettings(prefs, profile);
 }

void SafeBrowsingBlockingPage::SetReportingPreference(bool report) {
  Profile* profile = Profile::FromBrowserContext(
      web_contents_->GetBrowserContext());
  PrefService* pref = profile->GetPrefs();
  pref->SetBoolean(prefs::kSafeBrowsingReportingEnabled, report);
}

void SafeBrowsingBlockingPage::OnProceed() {
  proceeded_ = true;
  RecordUserAction(PROCEED);
  // Send the malware details, if we opted to.
  FinishMalwareDetails(malware_details_proceed_delay_ms_);

  NotifySafeBrowsingService(sb_service_, unsafe_resources_, true);

  // Check to see if some new notifications of unsafe resources have been
  // received while we were showing the interstitial.
  UnsafeResourceMap* unsafe_resource_map = GetUnsafeResourcesMap();
  UnsafeResourceMap::iterator iter = unsafe_resource_map->find(web_contents_);
  SafeBrowsingBlockingPage* blocking_page = NULL;
  if (iter != unsafe_resource_map->end() && !iter->second.empty()) {
    // Build an interstitial for all the unsafe resources notifications.
    // Don't show it now as showing an interstitial while an interstitial is
    // already showing would cause DontProceed() to be invoked.
    blocking_page = factory_->CreateSafeBrowsingPage(sb_service_, web_contents_,
                                                     iter->second);
    unsafe_resource_map->erase(iter);
  }

  // Now that this interstitial is gone, we can show the new one.
  if (blocking_page)
    blocking_page->interstitial_page_->Show();
}

void SafeBrowsingBlockingPage::OnDontProceed() {
  // Calling this method twice will not double-count.
  RecordUserReactionTime(kNavigatedAwayMetaCommand);
  // We could have already called Proceed(), in which case we must not notify
  // the SafeBrowsingService again, as the client has been deleted.
  if (proceeded_)
    return;

  RecordUserAction(DONT_PROCEED);
  // Send the malware details, if we opted to.
  FinishMalwareDetails(0);  // No delay

  NotifySafeBrowsingService(sb_service_, unsafe_resources_, false);

  // The user does not want to proceed, clear the queued unsafe resources
  // notifications we received while the interstitial was showing.
  UnsafeResourceMap* unsafe_resource_map = GetUnsafeResourcesMap();
  UnsafeResourceMap::iterator iter = unsafe_resource_map->find(web_contents_);
  if (iter != unsafe_resource_map->end() && !iter->second.empty()) {
    NotifySafeBrowsingService(sb_service_, iter->second, false);
    unsafe_resource_map->erase(iter);
  }

  // We don't remove the navigation entry if the tab is being destroyed as this
  // would trigger a navigation that would cause trouble as the render view host
  // for the tab has by then already been destroyed.  We also don't delete the
  // current entry if it has been committed again, which is possible on a page
  // that had a subresource warning.
  int last_committed_index =
      web_contents_->GetController().GetLastCommittedEntryIndex();
  if (navigation_entry_index_to_remove_ != -1 &&
      navigation_entry_index_to_remove_ != last_committed_index &&
      !web_contents_->IsBeingDestroyed()) {
    web_contents_->GetController().RemoveEntryAtIndex(
        navigation_entry_index_to_remove_);
    navigation_entry_index_to_remove_ = -1;
  }
}

void SafeBrowsingBlockingPage::RecordUserAction(BlockingPageEvent event) {
  // Determine the interstitial type from the blocked resources.
  // This is the same logic that is used to actually construct the
  // page contents; we can look at the title to see which type of
  // interstitial is being displayed.
  DictionaryValue strings;
  PopulateMultipleThreatStringDictionary(&strings);

  string16 title;
  bool success = strings.GetString("title", &title);
  DCHECK(success);

  std::string action = "SBInterstitial";
  if (title ==
          l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MULTI_THREAT_TITLE)) {
    action.append("Multiple");
  } else if (title ==
                 l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_TITLE)) {
    action.append("Malware");
  } else {
    DCHECK_EQ(title,
              l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_PHISHING_TITLE));
    action.append("Phishing");
  }

  switch (event) {
    case SHOW:
      action.append("Show");
      break;
    case PROCEED:
      action.append("Proceed");
      break;
    case DONT_PROCEED:
      if (IsPrefEnabled(prefs::kSafeBrowsingProceedAnywayDisabled))
        action.append("ForcedDontProceed");
      else
        action.append("DontProceed");
      break;
    default:
      NOTREACHED() << "Unexpected event: " << event;
  }

  content::RecordComputedAction(action);
}

void SafeBrowsingBlockingPage::RecordUserReactionTime(
    const std::string& command) {
  if (interstitial_show_time_.is_null())
    return;  // We already reported the user reaction time.
  base::TimeDelta dt = base::TimeTicks::Now() - interstitial_show_time_;
  DVLOG(1) << "User reaction time for command:" << command
           << " on is_malware:" << is_malware_interstitial_
           << " warning took " << dt.InMilliseconds() << "ms";
  bool recorded = true;
  if (is_malware_interstitial_) {
    // There are six ways in which the malware interstitial can go
    // away.  We handle all of them here but we group two together: closing the
    // tag / browser window and clicking on the back button in the browser (not
    // the big green button) are considered the same action.
    if (command == kProceedCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.MalwareInterstitialTimeProceed", dt);
    } else if (command == kTakeMeBackCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.MalwareInterstitialTimeTakeMeBack", dt);
    } else if (command == kShowDiagnosticCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.MalwareInterstitialTimeDiagnostic", dt);
    } else if (command == kShowPrivacyCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.MalwareInterstitialTimePrivacyPolicy",
                                 dt);
    } else if (command == kNavigatedAwayMetaCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.MalwareInterstitialTimeClosed", dt);
    } else {
      recorded = false;
    }
  } else {
    // Same as above but for phishing warnings.
    if (command == kProceedCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.PhishingInterstitialTimeProceed", dt);
    } else if (command == kTakeMeBackCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.PhishingInterstitialTimeTakeMeBack", dt);
    } else if (command == kShowDiagnosticCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.PhishingInterstitialTimeReportError", dt);
    } else if (command == kShowPrivacyCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.PhishingInterstitialTimeLearnMore", dt);
    } else if (command == kNavigatedAwayMetaCommand) {
      UMA_HISTOGRAM_MEDIUM_TIMES("SB2.PhishingInterstitialTimeClosed", dt);
    } else {
      recorded = false;
    }
  }
  if (recorded)  // Making sure we don't double-count reaction times.
    interstitial_show_time_ = base::TimeTicks();  //  Resets the show time.
}

void SafeBrowsingBlockingPage::FinishMalwareDetails(int64 delay_ms) {
  if (malware_details_ == NULL)
    return;  // Not all interstitials have malware details (eg phishing).

  if (IsPrefEnabled(prefs::kSafeBrowsingReportingEnabled)) {
    // Finish the malware details collection, send it over.
    BrowserThread::PostDelayedTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(&MalwareDetails::FinishCollection, malware_details_.get()),
        base::TimeDelta::FromMilliseconds(delay_ms));
  }
}

bool SafeBrowsingBlockingPage::IsPrefEnabled(const char* pref) {
  Profile* profile =
      Profile::FromBrowserContext(web_contents_->GetBrowserContext());
  return profile->GetPrefs()->GetBoolean(pref);
}

// static
void SafeBrowsingBlockingPage::NotifySafeBrowsingService(
    SafeBrowsingService* sb_service,
    const UnsafeResourceList& unsafe_resources,
    bool proceed) {
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&SafeBrowsingService::OnBlockingPageDone,
                 sb_service, unsafe_resources, proceed));
}

// static
SafeBrowsingBlockingPage::UnsafeResourceMap*
    SafeBrowsingBlockingPage::GetUnsafeResourcesMap() {
  return g_unsafe_resource_map.Pointer();
}

// static
void SafeBrowsingBlockingPage::ShowBlockingPage(
    SafeBrowsingService* sb_service,
    const SafeBrowsingService::UnsafeResource& unsafe_resource) {
  WebContents* web_contents = tab_util::GetWebContentsByID(
      unsafe_resource.render_process_host_id, unsafe_resource.render_view_id);

  InterstitialPage* interstitial =
      InterstitialPage::GetInterstitialPage(web_contents);
  if (interstitial && !unsafe_resource.is_subresource) {
    // There is already an interstitial showing and we are about to display a
    // new one for the main frame. Just hide the current one, it is now
    // irrelevent
    interstitial->DontProceed();
    interstitial = NULL;
  }

  if (!interstitial) {
    // There are no interstitial currently showing in that tab, go ahead and
    // show this interstitial.
    std::vector<SafeBrowsingService::UnsafeResource> resources;
    resources.push_back(unsafe_resource);
    // Set up the factory if this has not been done already (tests do that
    // before this method is called).
    if (!factory_)
      factory_ = g_safe_browsing_blocking_page_factory_impl.Pointer();
    SafeBrowsingBlockingPage* blocking_page =
        factory_->CreateSafeBrowsingPage(sb_service, web_contents, resources);
    blocking_page->interstitial_page_->Show();
    return;
  }

  // This is an interstitial for a page's resource, let's queue it.
  UnsafeResourceMap* unsafe_resource_map = GetUnsafeResourcesMap();
  (*unsafe_resource_map)[web_contents].push_back(unsafe_resource);
}

// static
bool SafeBrowsingBlockingPage::IsMainPageLoadBlocked(
    const UnsafeResourceList& unsafe_resources) {
  // Client-side phishing detection interstitials never block the main frame
  // load, since they happen after the page is finished loading.
  if (unsafe_resources[0].threat_type ==
      SafeBrowsingService::CLIENT_SIDE_PHISHING_URL) {
    return false;
  }

  // Otherwise, check the threat type.
  return unsafe_resources.size() == 1 && !unsafe_resources[0].is_subresource;
}


text:
 * Infected Wars, an open source Garry's Mod game-mode.
 *
 * Infected Wars is the work of multiple authors,
 * a full list can be found in CONTRIBUTORS.md.
 * For more information, visit https://github.com/JarnoVgr/InfectedWars
 *
 * Infected Wars is free software: you can redistribute it and/or modify
 * it under the terms of the MIT License.
 *
 * A full copy of the MIT License can be found in LICENSE.txt.
 -----------------------------------------------------------------------------]]

-- This particular file may contain different code than the live version

AddCSLuaFile("sh_greencoins.lua")
AddCSLuaFile("cl_greencoins.lua")
include("sh_greencoins.lua")

-- Debug setting
local DEBUG = false

-- Deluvas; lol :V
function GM:GetFirstKey(iCode)
	return 0
end

-- Metatable expanding
local meta = FindMetaTable("Player")
if meta then
	function meta:GiveGreenCoins(amount, hash)
	end

	function meta:TakeGreenCoins(amount, hash)
	end

	-- Save GC
	function meta:SaveGreenCoins()
	end
end

function GM:SendCoins(pl, amount)
	if not pl.GCData then
		return
	end

	umsg.Start("SendGC", pl)
	umsg.Long(pl.GCData["amount_current"])
	umsg.End()

	--Coin effect
	if amount then
		umsg.Start("CoinEffect", pl)
		umsg.Short(amount)
		umsg.End()
	end
end


text:
import click
from .services.auth_service import auth
from .services.finder_service import finders
from .services.group_service import groups
from .services.kickstarter_service import kick
from .services.message_service import messages
from .services.shoutout_service import shoutouts
from .services.status_service import statusmanagement
from .services.user_service import usermanagement

@click.group()
def init():
    """Official CLI client for 'Socialize - A social network on the cli'"""
    pass

# AUTHENTICATION

@init.command()
@click.option('--username', prompt=True)
@click.option('--password', prompt=True, hide_input=True,
              confirmation_prompt=True)
@click.option('--email', prompt=True)
def register(username, password, email):
    """Register a new user"""
    auth.register(username, email, password)

@init.command()
@click.option('--username', prompt=True)
@click.option('--password', prompt=True, hide_input=True)
def login(username, password):
    auth.login(username, password)

@init.command()
def logout():
    auth.logout()

# User Management

@init.command()
def me():
    """Shows current user"""
    usermanagement.get_current_user()

@init.command()
@click.option('--slogan', help="Specify a slogan in quotes, e.g. 'this is my slogan'", default=None)
@click.option('--website', help="Specify a website", default=None)
@click.option('--interests', help="Specify some interests in quotes, e.g. 'Python, Stuff, Stuff'", default=None)
@click.option('--skills', help="Specify some skills in quotes, e.g. 'Programming, Eating, Sleeping'", default=None)
def profile(slogan, website, interests, skills):
    """Set profile details"""
    usermanagement.set_attr(slogan, website, interests, skills)

@init.command()
@click.argument('name')
def user(name):
    """Get a specific user by name"""
    usermanagement.get_user(name)

# Followingship

@init.command()
@click.argument('name')
def follow(name):
    """Follow a specific user"""
    usermanagement.follow_user(name)

@init.command()
@click.argument('name')
def unfollow(name):
    """Unfollow a specific user"""
    usermanagement.unfollow_user(name)

# Status

@init.group()
def status():
    """Status management"""
    pass

@status.command()
def feed():
    """Get status feed of the 20 latest statuses"""
    statusmanagement.get_feed()

@status.command()
@click.argument('message')
def post(message):
    """Post a new status (use quotes)"""
    statusmanagement.post_status(message)

# Shoutouts

@init.group()
def shout():
    """Shoutout management"""
    pass

@shout.command()
def feed():
    """Get shout feed of the 20 latest shoutouts"""
    shoutouts.get_feed()

@shout.command()
@click.argument('message')
@click.option('--anon/--public', default=False)
def post(message, anon):
    """Post a new shoutout (use quotes). Use the anon option to post the shoutout anonymously"""
    shoutouts.post_status(message, anon)

# Groups

@init.group()
def group():
    """Group management"""
    pass

@group.command()
@click.argument('name')
@click.option('-p', '--password', default=None, help='Sometimes you have to provide a passphrase to join a group.')
def join(name, password):
    """Join a group with a given name (password might be to be provided"""
    groups.join_group(name, password)

@group.command()
@click.argument('name')
def leave(name):
    """Leave a previously joined group"""
    groups.leave_group(name)

@group.command()
@click.argument('name')
def delete(name):
    """Delete one of your groups (you have to be the creator!)"""
    groups.delete_group(name)

@group.command()
@click.argument('name')
def show(name):
    """Show group info"""
    groups.get_group(name)

@group.command()
@click.argument('name')
@click.option('-d', '--description', default=None, help='Set a short description of your group.')
@click.option('-p', '--password', default=None, help='Set your group to private and set a password.')
def create(name, description, password):
    """Create a new group with a given name You can also provide a short description and/or a password to make the group private"""
    groups.create_group(name, description, password)

# Groupmessages

@group.command()
@click.argument('name')
def feed(name):
    """Groupmessage feed"""
    groups.get_group_messages(name)

@group.command()
@click.argument('name')
@click.argument('message')
def message(name, message):
    """Post a new group message (write in quotes)"""
    groups.post_group_message(name, message)

# Messages

@init.group()
def message():
    """Message management"""
    pass

@message.command()
@click.argument('user')
@click.argument('message')
def send(user, message):
    """Send a new message, providing the user and the message in quotes"""
    messages.send_message(user, message)

@message.command()
def unread():
    """Get a list of all unread messages in the inbox"""
    messages.get_unread_messages()

@message.command()
@click.argument('id')
def read(id):
    """Read a message by ID - You can get the id from the unread command"""
    messages.read_message(id)

@message.command()
@click.argument('user')
def conversation(user):
    """Get a conversation with a specific user"""
    messages.get_conversation(user)

@message.command()
def conversations():
    """Get all conversations with a user"""
    messages.get_conversations()

# Finders

@init.group()
def find():
    """Tool to find users and groups"""
    pass

@find.command()
def friends():
    """Returns up to 25 random people"""
    finders.random_users()

@find.command()
@click.argument('name')
def user(name):
    """Find a user by name"""
    finders.find_users(name)

@find.command()
@click.argument('name')
def group(name):
    """Find a group by name"""
    finders.find_group(name)

# Kickstarters

@init.command()
def kickstarter():
    """Print all supporters"""
    kick.get_supporters()

@init.command()
def wired():
    """Supporter message: Try it out"""
    print("Let's all Love Lain")

@init.command()
def joke():
    """Supporter message: Try it out"""
    print("Just laugh.")

@init.command()
def medicine():
    """Supporter message: Try it out"""
    print("Have a free checkup. Preventative health care is the cheapest sort!")

@init.command()
def hack():
    """Supporter message: Try it out"""
    print("Find a teacher. Then kill your buddha.")

@init.command()
def nicolaialex():
    print("pursue happiness , and program")


text:
package main

import (
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/dustin/go-humanize"
	"github.com/gosuri/uiprogress"
	"github.com/gosuri/uiprogress/util/strutil"

	"gopkg.in/kothar/go-backblaze.v0"
)

// TODO support directories
// TODO support replacing all previous versions

// Put is a command
type Put struct {
	Threads int               `short:"j" long:"threads" default:"5" description:"Maximum simultaneous uploads to process"`
	Meta    map[string]string `long:"meta" description:"Assign metadata to uploaded files"`
}

func init() {
	parser.AddCommand("put", "Store a file",
		"Uploads one or more files. Specify the bucket with -b, and the filenames to upload as extra arguments.",
		&Put{})
}

// Execute the put command
func (o *Put) Execute(args []string) error {
	client, err := Client()
	if err != nil {
		return err
	}

	bucket, err := client.Bucket(opts.Bucket)
	if err != nil {
		return err
	}
	if bucket == nil {
		return errors.New("Bucket not found: " + opts.Bucket)
	}

	uiprogress.Start()
	tasks := make(chan string, o.Threads)
	group := sync.WaitGroup{}

	// Create workers
	for i := 0; i < o.Threads; i++ {
		group.Add(1)
		go func() {
			for file := range tasks {
				_, err := upload(bucket, file, o.Meta)
				if err != nil {
					fmt.Println(err)
				}

				// TODO handle termination on error
			}
			group.Done()
		}()
	}

	for _, file := range args {
		tasks <- file
	}
	close(tasks)

	group.Wait()

	return nil
}

type progressReader struct {
	bar *uiprogress.Bar
	r   io.ReadSeeker
}

func (p *progressReader) Read(b []byte) (int, error) {
	read, err := p.r.Read(b)
	p.bar.Set(p.bar.Current() + read)
	return read, err
}

func (p *progressReader) Seek(offset int64, whence int) (int64, error) {
	switch whence {
	case 0:
		p.bar.Set(int(offset))
	case 1:
		p.bar.Set(p.bar.Current() + int(offset))
	case 2:
		p.bar.Set(p.bar.Total - int(offset))
	}
	return p.r.Seek(offset, whence)
}

func upload(bucket *backblaze.Bucket, file string, meta map[string]string) (*backblaze.File, error) {

	stat, err := os.Stat(file)
	if err != nil {
		return nil, err
	}

	reader, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	defer reader.Close()

	var r io.Reader = reader
	if opts.Verbose {
		bar := uiprogress.AddBar(int(stat.Size()))
		// TODO Stop bar refresh when complete

		if stat.Size() > 1024*100 {
			start := time.Now()
			elapsed := time.Duration(1)
			count := 0
			bar.AppendFunc(func(b *uiprogress.Bar) string {
				count++
				if count < 2 {
					return ""
				}

				// elapsed := b.TimeElapsed()
				if b.Current() < b.Total {
					elapsed = time.Now().Sub(start)
				}
				speed := uint64(float64(b.Current()) / elapsed.Seconds())
				return humanize.IBytes(speed) + "/sec"
			})
		}
		bar.AppendCompleted()
		bar.PrependFunc(func(b *uiprogress.Bar) string { return fmt.Sprintf("%10s", humanize.IBytes(uint64(b.Total))) })
		bar.PrependFunc(func(b *uiprogress.Bar) string { return strutil.Resize(file, 50) })
		bar.Width = 20

		r = &progressReader{bar, reader}
	}

	return bucket.UploadFile(filepath.Base(file), meta, r)
}