Exemplo n.º 1
0
 public function execute()
 {
     $view = $this->getView();
     $fac = new ModelFactory('PageModel');
     $fac->where('baseurl LIKE /blog/view/%');
     $fac->where('published_status = published');
     $fac->where('published <= ' . \Core\Date\DateTime::NowGMT());
     $fac->limit($this->getSetting('count'));
     switch ($this->getSetting('sort')) {
         case 'newest':
             $fac->order('published DESC');
             break;
         case 'popular':
             $fac->order('popularity DESC');
             break;
         case 'random':
             $fac->order('RAND()');
             break;
     }
     if (!$fac->count()) {
         // If there are no results found, then do not display the widget.
         return '';
     }
     $view->assign('sort', $this->getSetting('sort'));
     $view->assign('title', $this->getSetting('title'));
     $view->assign('links', $fac->get());
 }
Exemplo n.º 2
0
 public function execute()
 {
     $view = $this->getView();
     $fac = new ModelFactory('PageModel');
     if ($this->getSetting('blog')) {
         $fac->where('parenturl = /blog/view/' . $this->getSetting('blog'));
     }
     $fac->where('parenturl LIKE /blog/view/%');
     $fac->where('published_status = published');
     $fac->where('published <= ' . \Core\Date\DateTime::NowGMT());
     $fac->limit($this->getSetting('count'));
     switch ($this->getSetting('sort')) {
         case 'newest':
             $fac->order('published DESC');
             break;
         case 'popular':
             $fac->order('popularity DESC');
             break;
         case 'random':
             $fac->order('RAND()');
             break;
     }
     if (!$fac->count()) {
         // If there are no results found, then do not display the widget.
         return '';
     }
     $view->assign('count', $this->getSetting('count'));
     $view->assign('sort', $this->getSetting('sort'));
     $view->assign('title', $this->getSetting('title'));
     // The template is expecting an array, if count is 1, only a single Model is returned from the factory.
     $view->assign('links', $this->getSetting('count') == 1 ? [$fac->get()] : $fac->get());
 }
Exemplo n.º 3
0
/**
 * Take a GMT date and return the formatted string.
 *
 * @todo Finish documentation of smarty_function_date
 *
 * #### Smarty Parameters
 *
 * * date (or unnamed variable)
 * * format
 * * assign
 *
 * #### Example Usage
 *
 * <pre>
 * {date 1234567890}
 * </pre>
 *
 * @param array  $params  Associative (and/or indexed) array of smarty parameters passed in from the template
 * @param Smarty $smarty  Parent Smarty template object
 *
 * @throws SmartyException
 *
 * @return string
 */
function smarty_function_date($params, $smarty){

	if(array_key_exists('date', $params)){
		$date = $params['date'];
	}
	elseif(isset($params[0])){
		$date = $params[0];
	}
	else{
		// Use "now" as the time.
		$date = \Core\Date\DateTime::Now(Time::FORMAT_RFC2822);
	}

	if(!$date){
		if(DEVELOPMENT_MODE){
			return 'Parameter [date] was empty, cowardly refusing to format an empty string.';
		}
		else{
			return '';
		}
	}


	$format = isset($params['format']) ? $params['format'] : \Core\Date\DateTime::RELATIVE;
	//$timezone = isset($params['timezone']) ? $params['timezone'] : Time::TIMEZONE_GMT;

	$coredate = new \Core\Date\DateTime($date);

	if(isset($params['assign']) && $params['assign']){
		$smarty->assign($params['assign'], $coredate->format($format));
	}
	else{
		return $coredate->format($format);
	}
}
	/**
	 * Get the value appropriate for INSERT statements.
	 *
	 * @return string
	 */
	public function getInsertValue(){
		// CREATED is an auto flag for the timestamp NOW on saves (inserts).
		if(!$this->value){
			$this->setValueFromApp(DateTime::NowGMT());
		}
		
		return $this->value;
	}
	/**
	 * Get the value appropriate for UPDATE statements.
	 *
	 * @return string
	 */
	public function getUpdateValue(){
		$this->setValueFromApp(DateTime::NowGMT());

		return $this->value;
	}
Exemplo n.º 6
0
	/**
	 * Get an associative array of all metadata associated to the requested file.
	 *
	 * @param string $file
	 *
	 * @return array
	 * @throws \Exception
	 */
	public function getMetas($file){
		$allkeys = ['filename', 'hash', 'modified', 'size'];

		if($this->_contents === null){

			$this->_contents = [];

			$remotefile = $this->_dir . '.ftpmetas';
			$f = md5($remotefile);

			$this->_local = Factory::File('tmp/remotefile-cache/' . $f);

			if(
				(!$this->_local->exists()) ||
				($this->_local->exists() && $this->_local->getMTime() + 1800 < DateTime::NowGMT())
			){
				// Only try to open the remote file if it exists.
				if(ftp_size($this->_ftp->getConn(), $remotefile) != -1){
					// The file doesn't exist OR the file does but it hasn't been modified in the past 30 minutes.
					$this->_local->putContents('');
					ftp_get($this->_ftp->getConn(), $this->_local->getFilename(), $remotefile, FTP_BINARY);
				}
			}


			if(!$this->_local->exists()){
				// The remote file doesn't exist, so nothing was downloaded.
				// Just return a blank array.
				return array_merge($allkeys, ['filename' => $file]);
			}

			// Read this CSV file into the contents array.
			$fh = fopen($this->_local->getFilename(), 'r');
			if(!$fh){
				throw new \Exception('Unable to open ' . $this->_local->getFilename() . ' for reading.');
			}
			$line    = 0;
			$map     = [];
			$headers = [];
			do{
				$data = fgetcsv($fh, 2048);

				// Meh.  Could do this inside a standard while statement, but same diff.
				if($data === null) break;
				if($data === false) break;

				$line++;
				if($line == 1){
					// This is the header.
					$map = $data;
					foreach($data as $k => $v){
						$headers[$v] = $k;
					}

					foreach($allkeys as $key){
						if(!isset($headers[$key])){
							$map[] = $key;
							$headers[$key] = -1;
						}
					}
				}
				else{
					$assoc = [];
					foreach($map as $k => $v){
						$assoc[$v] = isset($data[$k]) ? $data[$k] : '';
					}
					if(!isset($assoc['filename'])){
						// Invalid CSV input.
						fclose($fh);
						return array_merge($allkeys, ['filename' => $file]);
					}

					$this->_contents[ $assoc['filename'] ] = $assoc;
				}
			}
			while(true);
		}

		return isset($this->_contents[$file]) ? $this->_contents[$file] : array_merge($allkeys, ['filename' => $file]);
	}
Exemplo n.º 7
0
 /**
  * This will check and see how many 404 requests there have been recently.
  *
  * @return bool
  */
 public static function Check404Pages()
 {
     // How long back do I want to check the logs?
     $time = new DateTime();
     $time->modify('-30 seconds');
     $ds = Dataset::Init()->table('user_activity')->where(['status = 404', 'ip_addr = ' . REMOTE_IP, 'datetime > ' . $time->format('U')])->count()->execute();
     if ($ds->num_rows > 30) {
         // CHILL THAR F****R!
         $time->modify('+6 minutes');
         $blacklist = new \IpBlacklistModel();
         $blacklist->setFromArray(['ip_addr' => REMOTE_IP . '/24', 'expires' => $time->format('U'), 'message' => 'You have requested too many "404" pages recently, please go get some coffee and wait for a short bit.  If you are a bot and/or spammer, please bugger off.', 'comment' => '5-minute auto-ban for too many 404 requests in 30 seconds']);
         $blacklist->save();
         \SystemLogModel::LogSecurityEvent('/security/blocked', 'Blocking IP due to too many 404 requests in 30 seconds.');
         die($blacklist->get('message'));
     }
 }
Exemplo n.º 8
0
	private function _syncMetas(){
		if($this->lastSave + 25 >= DateTime::NowGMT()){
			return;
		}

		$this->lastSave = DateTime::NowGMT();
		foreach($this->metaFiles as $file){
			/** @var FTPMetaFile $file */
			$file->saveMetas();
		}
	}
Exemplo n.º 9
0
	/**
	 * Shortcut function for formatting a timestamp or date string into another format and timezone.
	 *
	 * @param     $datetime
	 * @param     $format
	 * @param int $timezone
	 *
	 * @return string
	 */
	public static function FormatString($datetime, $format, $timezone = Timezone::TIMEZONE_DEFAULT){
		$d = new DateTime($datetime);
		return $d->format($format, $timezone);
	}
Exemplo n.º 10
0
	/**
	 * Set the user's password using the necessary hashing
	 *
	 * @param $password
	 *
	 * @return bool|string True/False on success or failure, a string if on error.
	 */
	public function setPassword($password) {
		$isvalid = $this->validatePassword($password);

		if($isvalid !== true){
			// Core validation returned a string.... it's INVALID!
			return $isvalid;
		}

		// hash the password.
		$hasher = new \PasswordHash(datastore::HASH_ITERATIONS);
		$password = $hasher->hashPassword($password);

		// Still here?  Then try to set it.
		$this->_usermodel->set('password', $password);
		$this->_usermodel->set('last_password', DateTime::NowGMT());
		return true;
	}
Exemplo n.º 11
0
	/**
	 * Render the View to the browser.
	 */
	public function render(){
		\Core\Utilities\Profiler\Profiler::GetDefaultProfiler()->record('Starting PageRequest->render()');

		$view = $this->getView();
		$page = $this->getPageModel();

		// Dispatch the hooks here if it's a 404 or 403.
		if ($view->error == View::ERROR_ACCESSDENIED || $view->error == View::ERROR_NOTFOUND) {
			// Let other things chew through it... (optionally)
			HookHandler::DispatchHook('/core/page/error-' . $view->error, $view);
		}

		try {
			// This will pre-fetch the contents of the entire page and store it into memory.
			// If it is cacheable, then it will be cached and used for the next execution.

			// If the user has the view user activity permission, add the link to that page!
			if(\Core\user()->checkAccess('p:user_activity_list') && $page && $page->exists()){
				$view->addControl(
					'User Activity Details',
					'/useractivity/details?filter[baseurl]=' . $page->get('baseurl'),
					'eye'
				);
			}

			$view->fetch();
		}
		catch (Exception $e) {
			// If something happens in the rendering of the template... consider it a server error.
			$view->error   = View::ERROR_SERVERERROR;
			$view->baseurl = '/error/error/500';
			$view->setParameters(array());
			$view->templatename   = '/pages/error/error500.tpl';
			$view->mastertemplate = ConfigHandler::Get('/theme/default_template');
			$view->assignVariable('exception', $e);
			\Core\ErrorManagement\exception_handler($e);

			$view->fetch();
		}


		if($this->isCacheable()){
			$uakey = \Core\UserAgent::Construct()->getPseudoIdentifier();
			$urlkey = $this->host . $this->uri;
			$expires = $page->get('expires'); // Number of seconds.
			$key = 'page-cache-' . md5($urlkey . '-' . $uakey);

			$d = new \Core\Date\DateTime();
			$d->modify('+' . $expires . ' seconds');

			$view->headers['Cache-Control'] = 'max-age=' . $expires;
			$view->headers['Expires'] = $d->format('r', \Core\Date\Timezone::TIMEZONE_GMT);
			$view->headers['Vary'] = 'Accept-Encoding,User-Agent,Cookie';
			$view->headers['X-Core-Cached-Date'] = \Core\Date\DateTime::NowGMT('r');
			$view->headers['X-Core-Cached-Server'] = 1; // @todo Implement multi-server support.
			$view->headers['X-Core-Cached-Render-Time'] = \Core\Utilities\Profiler\Profiler::GetDefaultProfiler()->getTimeFormatted();

			// Record the actual View into cache.
			\Core\Cache::Set($key, $view, $expires);

			// And record the key onto an index cache record so there's a record of what to delete on updates.
			$indexkey = $page->getIndexCacheKey();
			$index = \Core\Cache::Get($indexkey, SECONDS_ONE_DAY);
			if(!$index){
				$index = [];
			}
			$index[] = $key;
			\Core\Cache::Set($indexkey, $index, SECONDS_ONE_DAY);
		}
		elseif(($reason = $this->isNotCacheableReason()) !== null){
			$view->headers['X-Core-NotCached-Reason'] = $reason;
		}
		$view->headers['X-Core-Render-Time'] = \Core\Utilities\Profiler\Profiler::GetDefaultProfiler()->getTimeFormatted();

		$view->render();

		// Make sure I update any existing page now that the controller has ran.
		if ($page && $page->exists() && $view->error == View::ERROR_NOERROR) {

			// Only increase the pageview count if the visitor is not a bot.
			// UA detection isn't very accurate, but this isn't for precision accuracy, merely a rough estimate.
			if(!\Core\UserAgent::Construct()->isBot()){
				$page->set('pageviews', $page->get('pageviews') + 1);
			}

			$page->set('last_template', $view->templatename);
			$page->set('body', $view->fetchBody());

			$page->save();
		}

		// Just before the page stops execution...
		HookHandler::DispatchHook('/core/page/postrender');
	}