public function testTimeGetCurrent(){
		$ref = new DateTime(null, new DateTimeZone(date_default_timezone_get()));

		$this->assertEquals($ref->format('U'), \Time::GetCurrent(\Core\Date\Timezone::TIMEZONE_DEFAULT, 'U'));

		$this->assertEquals($ref->format('Y-m-d'), \Time::GetCurrent(\Core\Date\Timezone::TIMEZONE_DEFAULT, 'Y-m-d'));
	}
Example #2
0
	/**
	 * Mark this CHANGELOG section as released by the requested user and email, optionally on a given timestamp.
	 *
	 * @param string      $packager_name  Packager's name
	 * @param string      $packager_email Packager's email
	 * @param string|null $date           Date (in RFC-2822 format), or null for now
	 *
	 * @throws \Exception
	 */
	public function markReleased($packager_name, $packager_email, $date = null) {
		if($this->getReleasedDate()){
			throw new \Exception('CHANGELOG section has already been marked as released.');
		}

		if(!$date){
			$date = \Time::GetCurrent(\Time::TIMEZONE_DEFAULT, \Time::FORMAT_RFC2822);
		}
		$this->parseLine("--$packager_name <$packager_email>  " . $date);
	}
	public function historical(){
		$request = $this->getPageRequest();
		$view = $this->getView();

		if(!$request->isJSON()) return View::ERROR_BADREQUEST;
		$view->contenttype = View::CTYPE_JSON;
		$view->mode = View::MODE_AJAX;
		$view->record = false;

		$profiler = new \Core\Utilities\Profiler\Profiler('useractivity');

		$limit  = $this->_getQueryLimit();
		$dstart = $request->getParameter('dstart');
		$dend   = $request->getParameter('dend');

		if(!$dend){
			$dend = Time::GetCurrent();
		}
		else{
			$dend = strtotime($dend);
		}
		if(!$dstart){
			$dstart = $dend - (3600 * 24 * 30);
		}
		else{
			$dstart = strtotime($dstart);
		}
		// Use FindRaw because it's faster than using full Models for everything, especially when dealing with 20k + records.
		$listings = UserActivityModel::FindRaw(array('datetime >= ' . $dstart, 'datetime <= ' . $dend), $limit, 'datetime DESC');
		$profiler->record('Found raw models');

		$data = array(
			'performance' => array('get' => 0, 'post' => 0),
			'requests'    => array('get' => 0, 'post' => 0),
			'counts'      => array('bots' => 0, 'users' => 0, 'visitors' => 0),
			'browsers'    => array(),
			'referrers'   => array(),
			'ips'         => array(),
			'os'          => array(),
			'notfounds'   => array(),
			'pages'       => array(),
		);

		$sessions = array();
		$x = 0;

		foreach($listings as $log){
			++$x;

			if($log['type'] == 'GET'){
				$data['performance']['get'] += $log['processing_time'];
				$data['requests']['get']++;
			}
			elseif($log['type'] == 'POST'){
				$data['performance']['post'] += $log['processing_time'];
				$data['requests']['post']++;
			}

			$ua = \Core\UserAgent::Construct($log['useragent']);

			if($ua->isBot()){
				$data['counts']['bots']++;
			}
			else{
				$data['counts']['users']++;

				if(!isset($sessions[ $log['session_id'] ])) $sessions[ $log['session_id'] ] = true;
			}

			$browser = $ua->browser . ' ' . $ua->version;

			if(!isset($data['browsers'][ $browser ])) $data['browsers'][ $browser ] = 1;
			else $data['browsers'][ $browser ]++;

			if($log['referrer'] == ''){
				$referrer = 'none';
			}
			elseif(strpos($log['referrer'], 'http://' . HOST) === 0){
				$referrer = 'internal';
			}
			elseif(strpos($log['referrer'], 'https://' . HOST) === 0){
				$referrer = 'internal-ssl';
			}
			else{
				// I want to trim the referrer a bit so I don't end up with a bunch of one-offs.
				if(($qpos = strpos($log['referrer'], '?')) !== false) $referrer = substr($log['referrer'], 0, $qpos);
				else $referrer = $log['referrer'];
			}

			if(!isset($data['referrers'][ $referrer ])) $data['referrers'][ $referrer ] = 1;
			else $data['referrers'][ $referrer ]++;

			if(!isset($data['ips'][ $log['ip_addr'] ])) $data['ips'][ $log['ip_addr'] ] = 1;
			else $data['ips'][ $log['ip_addr'] ]++;

			if(!isset($data['os'][ $ua->platform ])) $data['os'][ $ua->platform ] = 1;
			else $data['os'][ $ua->platform ]++;

			if($log['status'] == 404){
				if(!isset($data['notfounds'][ $log['request'] ])) $data['notfounds'][ $log['request'] ] = 1;
				else $data['notfounds'][ $log['request'] ]++;
			}

			if($log['status'] == 200){
				if(!isset($data['pages'][ $log['baseurl'] ])) $data['pages'][ $log['baseurl'] ] = 1;
				else $data['pages'][ $log['baseurl'] ]++;
			}

			$profiler->record('Parsed record #' . $x);
		}
//UserAgent::Test(); die();
		if($data['requests']['get'] > 0) $data['performance']['get'] = round($data['performance']['get'] /  $data['requests']['get'], 2);
		if($data['requests']['post'] > 0) $data['performance']['post'] = $data['performance']['post'] /  $data['requests']['post'];

		$data['counts']['visitors'] = sizeof($sessions);

		// Do some sorting on a few of the arrays.
		arsort($data['browsers']);
		arsort($data['referrers']);
		arsort($data['ips']);
		arsort($data['os']);
		arsort($data['notfounds']);
		arsort($data['pages']);

		$profiler->record('Sorted all data');

		// DEBUG!
		//echo '<pre>';
		//echo $profiler->getEventTimesFormatted();
		//die();

		//var_dump($data, $users, $listings); die();
		$view->jsondata = $data;
	}
	/**
	 * Set the packager aka packager author.
	 *
	 * (packager is a bit too ambigious in this context).
	 *
	 * @param string $name
	 * @param string $email
	 */
	public function setPackageMaintainer($name, $email) {
		$this->getElement('/changelog[@version="' . $this->_version . '"]/packagemeta/date')->nodeValue = Time::GetCurrent(Time::TIMEZONE_GMT, 'r');
		$this->getElement('/changelog[@version="' . $this->_version . '"]/packagemeta/maintainer[@name="' . $name . '"][@email="' . $email . '"]');
		$this->getElement('/changelog[@version="' . $this->_version . '"]/packagemeta/packager')->nodeValue = 'CAE2 ' . ComponentHandler::GetComponent('core')->getVersion();
	}
Example #5
0
	}
	else{
		echo "Found $codenumber lines!";
	}

	return $contents;
}

if($onlyCore && $compilePHP){
	$globalnamespace = new CompilerNamespace();
	// Start the namespace.
	$contents = $globalnamespace->getOpeningTag();
	$contents .= compile_file(ROOT_PDIR . 'core/bootstrap.php', 0, $globalnamespace);

	// The compiled file will have a header stating some useful information.
	$date = Time::GetCurrent(Time::TIMEZONE_DEFAULT, Time::FORMAT_RFC2822);
	$header = <<<EOD
/**
 * Core bootstrap (COMPILED) file that kicks off the entire application
 *
 * This file is the core of the application; it's responsible for setting up
 *  all the necessary paths, settings and includes.
 *
 * In addition, it has been compiled to include the source from the many included files automatically.
 * To manage some code here, please see which file the code is being included from, (as stated in the comment above
 * the respective code), edit there and re-run utilities/compiler.php
 *
 * @package Core\Core
 * @since 2.1.5
 * @author Charlie Powell <*****@*****.**>
 * @copyright Copyright (C) 2009-2016  Charlie Powell
Example #6
0
	/**
	 * Write/Append a message to this log.
	 *
	 * @param string      $message The message to append
	 * @param string|null $code    Code or error type to prefix the log with
	 *
	 * @throws \Exception
	 */
	public function write($message, $code = null){

		if($this->isArchived()){
			throw new \Exception('Refusing to write to an already-archived log!');
		}

		$logpath = $this->getDirectoryName();
		$outfile = $this->getFilename();

		if(!is_dir($logpath)){
			// Enable auto-creation of the directory and .htaccess file.
			if(!is_writable(ROOT_PDIR)){
				// Not writable, no log!
				throw new \Exception('Unable to open ' . $logpath . ' for writing, access denied on parent directory!');
			}

			if(!mkdir($logpath)){
				// Can't create log directory, no log!
				throw new \Exception('Unable to create directory ' . $logpath . ', access denied on parent directory!');
			}

			$htaccessfh = fopen($logpath . '.htaccess', 'w');
			if(!$htaccessfh){
				// Couldn't open the htaccess for writing!
				throw new \Exception('Unable to create protective .htaccess file in ' . $logpath . '!');
			}

			$htaccesscontents = <<<EOD
<Files *>
	Order deny,allow
	Deny from All
</Files>
EOD;

			fwrite($htaccessfh, $htaccesscontents);
			fclose($htaccessfh);
		}
		elseif(!is_writable($logpath)){
			throw new \Exception('Unable to write to log directory ' . $logpath . '!');
		}
		// No else needed, else is everything dandy!


		// Generate a nice line header to prepend on the line.
		$header = '[' . \Time::GetCurrent(\Time::TIMEZONE_DEFAULT, 'r') . '] ';
		if(EXEC_MODE == 'WEB'){
			$header .= '[client: ' . REMOTE_IP . '] ';
		}
		else{
			$header .= '[client: CLI] ';
		}

		if($code) $header .= '[' . $code . '] ';

		$logfh = fopen($outfile, 'a');
		if(!$logfh){
			throw new \Exception('Unable to open ' . $outfile . ' for appending!');
		}
		foreach(explode("\n", $message) as $line){
			fwrite($logfh, $header . $line . "\n");
		}
		fclose($logfh);
	}
Example #7
0
	/**
	 *  Load the data from the files
	 */
	private static function _LoadData() {

		// The key for this data, must be unique on the system.
		$cachekey = 'useragent-browsecap-data';
		// The number of seconds to have Core cache the records.
		$cachetime = SECONDS_ONE_WEEK;

		$cache = Cache::Get($cachekey, $cachetime);

		if($cache === false){
			$file   = \Core\Filestore\Factory::File('tmp/php_browscap.ini');
			$remote = \Core\Filestore\Factory::File(self::$_ini_url);

			$rcontents = $remote->getContentsObject();
			if($rcontents instanceof ContentGZ){
				// yay...
				// Core handles all the remote file caching automatically, so no worries about anything here.
				$rcontents->uncompress($file);
			}
			else {
				// Ok, it may be a standard text file then... try the conventional logic.
				// Doesn't exist? download it!
				if(!$file->exists()){
					$remote->copyTo($file);
				}

				// Too old? download it!
				if($file->getMTime() < (\Time::GetCurrent() - self::$updateInterval)){
					$remote->copyTo($file);
				}
			}

			$_browsers = parse_ini_file($file->getFilename(), true, INI_SCANNER_RAW);
			$patterns = [];
			$browsers = [];

			// Trim the header off the file.
			array_shift($_browsers);


			// Grab all the property keys for browsers.
			$properties = array_keys($_browsers['DefaultProperties']);
			array_unshift(
				$properties,
				'browser_name',
				'browser_name_regex',
				'browser_name_pattern',
				'Parent'
			);

			// This creates a sorted set of user agents... used by the internal logic.
			$uas = array_keys($_browsers);
			usort(
				$uas,
				create_function(self::ORDER_FUNC_ARGS, self::ORDER_FUNC_LOGIC)
			);


			$user_agents_keys = array_flip($uas);
			$properties_keys = array_flip($properties);

			$search = ['\*', '\?'];
			$replace = ['.*', '.'];

			foreach ($uas as $user_agent) {
				$browser = [];
				$pattern = preg_quote($user_agent, self::REGEX_DELIMITER);
				$patterns[] = self::REGEX_DELIMITER
					. '^'
					. str_replace($search, $replace, $pattern)
					. '$'
					. self::REGEX_DELIMITER;

				if (!empty($_browsers[$user_agent]['Parent'])) {
					$parent = $_browsers[$user_agent]['Parent'];
					$_browsers[$user_agent]['Parent'] = $user_agents_keys[$parent];
				}

				foreach ($_browsers[$user_agent] as $key => $value) {
					//$key = $properties_keys[$key] . ".0";
					$key = $properties_keys[$key];
					$browser[$key] = $value;
				}

				$browsers[] = $browser;
				unset($browser);
			}
			unset($user_agents_keys, $properties_keys, $_browsers);

			Cache::Set(
				$cachekey,
				[
					'browsers'   => $browsers,
					'useragents' => $uas,
					'patterns'   => $patterns,
					'properties' => $properties,
				],
				$cachetime
			);
		}

		return Cache::Get($cachekey, $cachetime);
	}
Example #8
0
	/**
	 * Function that is fired off on page load.
	 * This checks if a form was submitted and that form was present in the SESSION.
	 *
	 * @return null
	 */
	public static function CheckSavedSessionData() {
		// This needs to ignore the /form/savetemporary.ajax page!
		// This is a custom page that's meant to intercept all POST submissions.
		if(preg_match('#^/form/(.*)\.ajax$#', REL_REQUEST_PATH)) return;

		// There has to be data in the session.
		$forms = \Core\Session::Get('FormData/*');

		$formid = (isset($_REQUEST['___formid'])) ? $_REQUEST['___formid'] : false;
		$form   = false;

		foreach ($forms as $k => $v) {
			// If the object isn't a valid object after unserializing...
			if (!($el = unserialize($v))) {
				\Core\Session::UnsetKey('FormData/' . $k);
				continue;
			}

			// Check the expires time
			if ($el->get('expires') <= Time::GetCurrent()) {
				\Core\Session::UnsetKey('FormData/' . $k);
				continue;
			}

			if ($k == $formid) {
				// Remember this for after all the checks have finished.
				$form = $el;
			}
		}

		// No form found... simple enough
		if (!$form) return;

		// Otherwise
		/** @var $form Form */

		// Ensure the submission types match up.
		if (strtoupper($form->get('method')) != $_SERVER['REQUEST_METHOD']) {
			\Core\set_message('t:MESSAGE_ERROR_FORM_SUBMISSION_TYPE_DOES_NOT_MATCH');
			return;
		}

		// Ensure the REFERRER and original URL match up.
		if($_SERVER['HTTP_REFERER'] != $form->originalurl){
			// @todo This is reported to be causing issues with production sites.
			//       If found true, this check may need to be removed / refactored.
			//\Core\set_message('Form submission referrer does not match, please try your submission again.', 'error');
			SystemLogModel::LogInfoEvent(
				'Form Referrer Mismatch',
				'Form referrer does not match!  Submitted: [' . $_SERVER['HTTP_REFERER'] . '] Expected: [' . $form->originalurl . ']'
			);
			//return;
		}

		// Run though each element submitted and try to validate it.
		if (strtoupper($form->get('method')) == 'POST') $src =& $_POST;
		else $src =& $_GET;

		$form->loadFrom($src);

		// Try to load the form from that form.  That will call all of the model's validation logic
		// and will throw exceptions if it doesn't.
		try{
			$form->getModel();

			// Still good?
			if (!$form->hasError()){
				$status = call_user_func($form->get('callsmethod'), $form);
			}
			else{
				$status = false;
			}
		}
		catch(ModelValidationException $e){
			\Core\set_message($e->getMessage(), 'error');
			$status = false;
		}
		catch(GeneralValidationException $e){
			\Core\set_message($e->getMessage(), 'error');
			$status = false;
		}
		catch(Exception $e){
			if(DEVELOPMENT_MODE){
				// Developers get the full message
				\Core\set_message($e->getMessage(), 'error');
			}
			else{
				// While users of production-enabled sites get a friendlier message.
				\Core\set_message('t:MESSAGE_ERROR_FORM_SUBMISSION_UNHANDLED_EXCEPTION');
			}
			Core\ErrorManagement\exception_handler($e);
			$status = false;
		}

		// The form was submitted.  Set its persistent flag to true so that whatever may be listening for it can retrieve the user's values.
		$form->persistent = true;

		// Regardless, bundle this form back into the session so the controller can use it if needed.
		\Core\Session::Set('FormData/' . $formid, serialize($form));

		// Fail statuses.
		if ($status === false) return;
		if ($status === null) return;

		// Guess it's not false and not null... must be good then.

		// @todo Handle an internal save procedure for "special" groups such as pageinsertables and what not.

		// Cleanup
		\Core\Session::UnsetKey('FormData/' . $formid);


		if ($status === 'die'){
			// If it's set to die, simply exit the script without outputting anything.
			exit;
		}
		elseif($status === 'back'){
			if($form->referrer && $form->referrer != REL_REQUEST_PATH){
				// Go back to the original form's referrer.
				\Core\redirect($form->referrer);
			}
			else{
				// Use Core to guess which page to redirect back to, (not as reliable).
				\Core\go_back();
			}
		}
		elseif ($status === true){
			// If the return code is boolean true, it's a reload.
			\Core\reload();
		}
		elseif($status === REL_REQUEST_PATH || $status === CUR_CALL){
			// If the page returned the same page as the current url, force a reload, (as redirect will ignore it)
			\Core\reload();
		}
		else{
			// Anything else gets sent to the redirect system.
			\core\redirect($status);
		}
	}
Example #9
0
	/**
	 * Get a string to represent the relative time from right now.
	 * Will return something similar to 'Yesterday at 5:40p' or 'Today at 4:20a', etc...
	 *
	 * @param $time int The time, (in GMT), to get the relative from now.
	 * @param $timezone int The timezone to display the result as.
	 * @param $accuracy int The level of accuracy,
	 *                      2 will return today|yesterday|tomorrow,
	 *                      3 will return up to a week, ie: Monday at 4:40pm
	 * @param $timeformat string The formatting to use for times.
	 * @param $dateformat string The formatting to use for dates.
	 *
	 * @return string
	 */
	public static function GetRelativeAsString($time, $timezone = Time::TIMEZONE_GMT, $accuracy = 3, $timeformat = 'g:ia', $dateformat = 'M j, Y') {
		// First, get the day of now and the time that's being compared.
		// They will form an int in the format of YYYYMMDD.
		$nowStamp = Time::GetCurrent($timezone, 'Ymd');
		$cStamp   = Time::FormatGMT($time, $timezone, 'Ymd');

		// The first couple days will always be converted, today and tomorrow/yesterday.
		if ($nowStamp - $cStamp == 0) return 'Today at ' . Time::FormatGMT($time, $timezone, $timeformat);
		elseif ($nowStamp - $cStamp == 1) return 'Yesterday at ' . Time::FormatGMT($time, $timezone, $timeformat);
		elseif ($nowStamp - $cStamp == -1) return 'Tomorrow at ' . Time::FormatGMT($time, $timezone, $timeformat);

		// If accuracy is the minimum and neither today/tomorrow/yesterday, simply return the date.
		if ($accuracy <= 2) return Time::FormatGMT($time, $timezone, $dateformat);

		// If it's too high/low from a week, just return the date.
		if (abs($nowStamp - $cStamp) > 6) return Time::FormatGMT($time, $timezone, $dateformat);

		// Else, return the day of the week, followed by the time.
		return Time::FormatGMT($time, $timezone, 'l \a\t ' . $timeformat);
	}