Example #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());
 }
 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());
 }
	/**
	 * 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;
	}
Example #5
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]);
	}
 /**
  * Check the user's IP and see if it's blacklisted.
  */
 public static function CheckIP()
 {
     $factory = new \ModelFactory('IpBlacklistModel');
     /*$factory->whereGroup(
     			'OR',
     			[
     				'expires > ' . \CoreDateTime::Now('U', \Time::TIMEZONE_GMT),
     				'expires = 0'
     			]
     		);*/
     $where = new \Core\Datamodel\DatasetWhereClause();
     $ips = [];
     $longip = ip2long(REMOTE_IP);
     for ($i = 32; $i > 0; $i--) {
         if ($i < 16) {
             // Skip anything smaller than a /16.
             break;
         }
         $mask = ~((1 << 32 - $i) - 1);
         $ips[] = long2ip($longip & $mask) . '/' . $i;
         //$where->addWhere('ip_addr = ' . long2ip($longip & $mask) . '/' . $i);
     }
     $factory->where('ip_addr IN ' . implode(',', $ips));
     $factory->limit(1);
     $ban = $factory->get();
     if (!$ban) {
         // Ok, you may pass.
         return;
     }
     // Check the date
     if ($ban->get('expires') != 0 && $ban->get('expires') < DateTime::NowGMT()) {
         // Well it has one, but it's already expired.
         // Go ahead and clean it up.
         $ban->delete();
         return;
     }
     // else... hehehe, happy happy fun time for you!
     \SystemLogModel::LogSecurityEvent('/security/blocked', 'Blacklisted IP tried to access the site (' . REMOTE_IP . ')', 'Blacklisted IP tried to access the site!<br/>Remote IP: ' . REMOTE_IP . '<br/>Matching Range: ' . $ban->get('ip_addr') . '<br/>Requested URL: ' . CUR_CALL);
     header('HTTP/1.0 420 Enhance Your Calm');
     die($ban->get('message'));
 }
Example #7
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();
		}
	}
Example #8
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;
	}
	/**
	 * 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');
	}