public function view()
 {
     $page = PageRequest::GetSystemRequest();
     $pageview = $page->getView();
     $pagemetas = $pageview->meta;
     $view = $this->getView();
     // The main identifier for livefyre, retrieved from within the livefyre "install" section.
     // Transposed to siteId
     $siteid = ConfigHandler::Get('/livefyre/siteid');
     if (!$siteid) {
         $msg = 'Livefyre is not configured yet.';
         if (\Core\user()->checkAccess('g:admin')) {
             $msg .= '  Please <a href="' . \Core\resolve_link('/livefyre') . '">configure it now</a>';
         }
         return $msg;
     }
     // The "article" is the base url.  This doesn't change despite changing URLs.
     // Transposed to articleId
     $article = $page->getBaseURL();
     // The title, used in the collectionMeta.
     // Transposed to title
     $title = $pageview->title;
     // The canonical URL, used in the collectionMeta.
     $url = $pageview->canonicalurl;
     $view->assign('siteId', $siteid);
     $view->assign('articleId', $article);
     $view->assign('title', $title);
     $view->assign('url', $url);
 }
	public static function Catch404Hook(View $view){

		$request = PageRequest::GetSystemRequest();

		// All the exact matches, in the order of precedence.
		$exactmatches = [];

		// The first search I want do is for the full URL exactly as submitted.
		// This is because the user can submit URLs with GET parameters attached to them.
		// It needs to act in a google-esque manner, where if the user requested x=1&y=2... then give them x=1 and y=2!
		$exactmatches[] = '/' . substr($request->uri, strlen(ROOT_WDIR));

		// This one is the resolved URL, without any GET parameters.  It's still a very common and very specific rewrite choice.
		$exactmatches[] = $request->uriresolved;

		// Now, look for them!
		foreach($exactmatches as $incomingurl){
			// Look for it!
			$maps = RewriteMapModel::Find(array('rewriteurl' => $incomingurl));

			// Did I get one did I get one did I get one?
			if(sizeof($maps)){
				// Grab the first one, that'll be the latest, (should multiple exist.... somehow :/ )
				$match = $maps[0]->get('baseurl');

				// Resolve that to the new rewriteurl and redirect!
				$newpage = PageModel::Construct($match);
				\core\redirect($newpage->get('rewriteurl'), 301);
			}
		}


		// Else, no match was found... maybe it's a fuzzy page!
		// Since this page will have no longer existed, I can't just use the builtin logic :(
		$fuzzy = $request->uriresolved;
		do{
			$fuzzy = substr($fuzzy, 0, strrpos($fuzzy, '/'));

			$fuzzymaps = RewriteMapModel::Find(array('rewriteurl' => $fuzzy, 'fuzzy' => '1'));
			if(sizeof($fuzzymaps)){
				// Yay!
				// Don't forget to throw on the rest of the url.
				$match = $fuzzymaps[0]->get('baseurl');
				$newpage = PageModel::Construct($match);
				$url = $newpage->get('rewriteurl');
				if($newpage->get('fuzzy')){
					// Only if the new page is fuzzy too.
					$url .= substr($incomingurl, strlen($fuzzy));
				}
				\core\redirect($url, 301);
			}
		}
		while($fuzzy);

		// Sigh, guess this page didn't make the cut.
		// There is no return necessary, this hook will simply silently continue to the next.
	}
	/**
	 * Widget to display a simple site search box
	 */
	public function execute(){
		$view = $this->getView();

		$urlbase = '/page/search';
		$url = \Core\resolve_link($urlbase);

		if(PageRequest::GetSystemRequest()->getBaseURL() == $urlbase && PageRequest::GetSystemRequest()->getParameter('q')){
			$query = PageRequest::GetSystemRequest()->getParameter('q');
		}
		else{
			$query = null;
		}

		$view->assign('title', $this->getSetting('title'));
		$view->assign('url', $url);
		$view->assign('query', $query);
	}
Beispiel #4
0
	/**
	 * Function to record activity, ie: a page view.
	 *
	 * @static
	 *
	 */
	public static function RecordActivity(){

		$request = \PageRequest::GetSystemRequest();
		$view = $request->getView();

		if(!$view->record) return true;

		try{

			$processingtime = (round(Profiler::GetDefaultProfiler()->getTime(), 3) * 1000);

			$log = new \UserActivityModel();
			$log->setFromArray(
				[
					'datetime' => microtime(true),
					'session_id' => session_id(),
					'user_id' => \Core\user()->get('id'),
					'ip_addr' => REMOTE_IP,
					'useragent' => $request->useragent,
					'referrer' => $request->referrer,
					'type' => $_SERVER['REQUEST_METHOD'],
					'request' => $_SERVER['REQUEST_URI'],
					'baseurl' => $request->getBaseURL(),
					'status' => $view->error,
					'db_reads' => DatamodelProfiler::GetDefaultProfiler()->readCount(),
					'db_writes' => (DatamodelProfiler::GetDefaultProfiler()->writeCount() + 1),
					'processing_time' => $processingtime,
				]
			);

			if(defined('XHPROF_RUN') && defined('XHPROF_SOURCE')){
				$log->set('xhprof_run', XHPROF_RUN);
				$log->set('xhprof_source', XHPROF_SOURCE);
			}

			$log->save();
		}
		catch(\Exception $e){
			// I don't actually care if it couldn't save.
			// This could happen if the user refreshes the page twice with in a second.
			// (and with a system that responds in about 100ms, it's very possible).
			\Core\ErrorManagement\exception_handler($e);
		}
	}
	/**
	 * Get the page request for the current page.
	 *
	 * @return PageRequest
	 */
	protected function getPageRequest() {
		if ($this->_request === null) {
			$this->_request = PageRequest::GetSystemRequest();
		}
		return $this->_request;
	}
Beispiel #6
0
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/agpl-3.0.txt.
 */

/**
 * Include the system bootstrap.
 * This basically does everything.....
 */

// When working on the core, it's best to switch this back to core/bootstrap.php!
// Set this to true to skip checking for the compiled version.
$skipcompiled = true;

try{
	if(!$skipcompiled && file_exists('core/bootstrap.compiled.php')) require_once('core/bootstrap.compiled.php');
	else require_once('core/bootstrap.php');

	$request   = PageRequest::GetSystemRequest();
	$request->execute();
	$request->render();	
}
catch(Exception $e){
	if(function_exists('\\Core\\ErrorManagement\\exception_handler')){
		\Core\ErrorManagement\exception_handler($e, true);
	}
}
Beispiel #7
0
	public static function Init(){

		if(self::$IsLoaded){
			return;
		}

		self::$DefaultLanguage = \ConfigHandler::Get('/core/language/site_default');

		// What locales are currently available on the system?
		$localesAvailable = self::GetLocalesAvailable();
		// The first value is all I want, as that is the user's preference.
		$preferred = \PageRequest::GetSystemRequest()->getPreferredLocale();

		// If this language is not available on the local system, then revert back to the system default!
		if(!isset($localesAvailable[$preferred])){
			$preferred = self::$DefaultLanguage;
		}

		$preferredAlt = $preferred . '.utf-8'; // Try to allow for variations of the different charsets.
		                                       // We don't actually care too much about which charset is used.
		// With this preferred value, set PHP's preference so its internal functions have the correct language.
		$res1 = setlocale(LC_COLLATE, $preferred, $preferredAlt);
		$res2 = setlocale(LC_CTYPE, $preferred, $preferredAlt);
		$res3 = setlocale(LC_NUMERIC, $preferred, $preferredAlt);
		$res4 = setlocale(LC_TIME, $preferred, $preferredAlt);
		$res5 = setlocale(LC_MESSAGES, $preferred, $preferredAlt);

		// DEBUG var_dump($preferred, $localesAvailable, $res1, $res2, $res3, $res4, $res5); die();
		// Currency does not get set to follow the user's preference, as the site admin determines what format to save and display currencies in.

		// Remember what the user's preferred language is so that I don't have to query the systemRequest again
		self::$UserLanguage = $preferred;

		// Cache this so number_format and money_format have the data available.
		self::$LocaleConv = localeconv();

		self::$IsLoaded = true;

		$cachekey = 'core-i18n-strings';
		$cached = Cache::Get($cachekey, 604800); // Cache here is good for one week.
		if(!DEVELOPMENT_MODE && $cached){
			// If the site is NOT in development mode and there is a valid cache, return the cached version!
			// The development mode check is to allow devs to update i18n strings without purging cache every two minutes.
			self::$Strings = $cached;
			return;
		}

		$files = [];
		$dirChecks = [];

		foreach(\Core::GetComponents() as $c){
			/** @var \Component_2_1 $c */
			if($c->getName() == 'core'){
				$dir = ROOT_PDIR . 'core/i18n/';
			}
			else{
				$dir = $c->getBaseDir() . 'i18n/';
			}

			$dirChecks[] = $dir;
		}

		// Include the active theme and custom overrides
		$t = \ConfigHandler::Get('/theme/selected');
		$dirChecks[] = ROOT_PDIR . 'themes/' . $t . '/i18n/';
		$dirChecks[] = ROOT_PDIR . 'themes/custom/i18n/';

		foreach($dirChecks as $dir){
			if(!is_dir($dir)){
				// No i18n directory defined in this component, simply skip over.
				continue;
			}

			$dh = opendir($dir);
			if(!$dh){
				// Couldn't open directory, skip.
				continue;
			}

			while (($file = readdir($dh)) !== false) {

				// I only want ini files here.
				if(substr($file, -4) != '.ini'){
					continue;
				}
				$files[] = $dir . $file;
			}
			closedir($dh);
		}




		self::$Strings = [];

		foreach($files as $f){
			$ini = parse_ini_file($f, true);

			foreach($ini as $lang => $dat){
				if(!isset(self::$Strings[$lang])){
					self::$Strings[$lang] = $dat;
				}
				else{
					self::$Strings[$lang] = array_merge(self::$Strings[$lang], $dat);
				}
			}
		}

		// Make sure that each language set has all base directives set too!
		/*foreach(self::$Strings as $k => $dat){
			//if(strpos($k, '_') === false){
				// Skip the root language setting itself.
			//	continue;
			//}

			$base = substr($k, 0, strpos($k, '_'));
			if(!isset(self::$Strings[$base])){
				self::$Strings[$base] = [];
			}
			foreach($dat as $s => $t){
				if(!isset(self::$Strings[$base][$s])){
					self::$Strings[$base][$s] = $t;
				}
			}
		}*/

		Cache::Set($cachekey, self::$Strings, 604800); // Cache here is good for one week.
	}
/**
 * @todo Finish documentation of smarty_function_widgetarea
 * @param array  $params  Associative (and/or indexed) array of smarty parameters passed in from the template
 * @param Smarty_Internal_Template $smarty  Parent Smarty template object
 *
 * @return string|void
 */
function smarty_function_widgetarea($params, $smarty) {
	// Get all widgets set to load in this area.

	$body     = '';
	$baseurl  = PageRequest::GetSystemRequest()->getBaseURL();
	$template = $smarty->template_resource;
	$tmpl     = $smarty->getTemplateVars('__core_template');
	$topview  = ($tmpl instanceof \Core\Templates\TemplateInterface) ? $tmpl->getView() : \Core\view();

	$parameters  = [];
	$name        = null;
	$installable = null;
	$assign      = null;
	foreach($params as $k => $v){
		switch($k){
			case 'name':
				$name = $v;
				break;
			case 'installable':
				$installable = $v;
				break;
			case 'assign':
				$assign = $v;
				break;
			default:
				$parameters[$k] = $v;
				break;
		}
	}

	// I need to resolve the page template down to the base version in order for the lookup to work.
	foreach(Core\Templates\Template::GetPaths() as $base){
		if(strpos($template, $base) === 0){
			$template = substr($template, strlen($base));
			break;
		}
	}

	// Given support for page-level widgets, this logic gets slightly more difficult...
	$factory = new ModelFactory('WidgetInstanceModel');
	$factory->order('weight');
	if(Core::IsComponentAvailable('multisite') && MultiSiteHelper::IsEnabled()){
		$factory->whereGroup('or', ['site = -1', 'site = ' . MultiSiteHelper::GetCurrentSiteID()]);
	}

	$subwhere = new Core\Datamodel\DatasetWhereClause();
	$subwhere->setSeparator('OR');

	// First, the skin-level where clause.
	$skinwhere = new Core\Datamodel\DatasetWhereClause();
	$skinwhere->setSeparator('AND');
	$skinwhere->addWhere('template = ' . $template);
	$skinwhere->addWhere('widgetarea = ' . $name);
	$subwhere->addWhere($skinwhere);

	// And second, the page-level where clause.
	if($baseurl){
		$pagewhere = new Core\Datamodel\DatasetWhereClause();
		$pagewhere->setSeparator('AND');
		$pagewhere->addWhere('page_baseurl = ' . $baseurl);
		$pagewhere->addWhere('widgetarea = ' . $name);
		$subwhere->addWhere($pagewhere);
	}

	$factory->where($subwhere);


	$widgetcount = 0;
	try{
		$widgets = $factory->get();
	}
	catch(Exception $e){
		if(DEVELOPMENT_MODE){
			$body .= '<p class="message-error">Exception while trying to load widget area ' . $name . '!</p>';
			$body .= '<pre class="xdebug-var-dump">' . $e->getMessage() . '</pre>';
		}
		else{
			\Core\ErrorManagement\exception_handler($e, false);
		}
		$widgets = [];
		++$widgetcount;
	}


	foreach ($widgets as $wi) {
		/** @var $wi WidgetInstanceModel */
		// User cannot access this widget? Don't display it...
		if(!\Core\user()){
			continue;
		}
		if (!\Core\user()->checkAccess($wi->get('access'))){
			continue;
		}

		if($installable){
			$wi->set('installable', $installable);
		}
		$view = $wi->execute($parameters);

		// Some widgets may return simply a blank string.  Those should just be ignored.
		if ($view == ''){
			continue;
		}

		// If it's just a string, return that.
		if (is_string($view)) {
			$contents = $view;
		}
		elseif($view->error == View::ERROR_NOERROR){
			// Ensure that the widget's View knows it's linked to a parent!
			$view->parent = $topview;

			$contents = $view->fetch();
		}
		else{
			$contents = 'Error displaying widget [' . $wi->get('baseurl') . '], returned error [' . $view->error . ']';
		}
		++$widgetcount;
		
		// Does this widget have controls attached to it?
		$widget = $wi->getWidget();
		if($widget->controls instanceof ViewControls && $widget->controls->hasLinks()){
			$contents = '<div class="widget-controls-wrapper">' .
				'<menu id="widget-controls-' . $wi->get('id') . '">' . 
				$widget->controls->fetch() . 
				'</menu>' . 
				'</div>' .
				$contents;
		}

		$body .= '<div class="widget">' . $contents . '</div>';
	}

	// Do some sanitizing for the css data
	$class = 'widgetarea-' . strtolower(str_replace(' ', '', $name));

	$html = '<div class="widgetarea ' . $class . '" widgetarea="' . $name . '">' . $body . '</div>';

	// No widgets, no inner content!
	if($widgetcount == 0){
		$html = '';
	}

	if($assign){
		$smarty->assign($assign, $html);
	}
	else{
		return $html;
	}
}
 /**
  * This is a widget to display children of the current page
  *
  * The page is dynamic based on the currently viewed page.
  *
  * @return int
  */
 public function children()
 {
     $view = $this->getView();
     $current = PageRequest::GetSystemRequest();
     $model = $current->getPageModel();
     if (!$model) {
         return '';
     }
     $baseurl = $model->get('baseurl');
     // Give me all the siblings of that baseurl.
     $pages = PageModel::Find(['parenturl' => $baseurl, 'selectable' => 1], null, 'title');
     $entries = [];
     foreach ($pages as $page) {
         $subpages = PageModel::Find(['parenturl' => $page->get('baseurl'), 'selectable' => 1], null, 'title');
         $subentries = [];
         foreach ($subpages as $subpage) {
             $subentries[] = ['obj' => $subpage, 'children' => [], 'class' => ''];
         }
         $entries[] = ['obj' => $page, 'children' => $subentries, 'class' => 'active'];
     }
     $view->assign('entries', $entries);
 }
/**
 * Primary method for a block of user-customizable content inside a template.
 *
 * Insertables are the core method of injecting blocks of user-customizable content into a template.
 *
 * An insertable must be on a template that has a registered page URL, as the baseurl is what is tracked as one of the main primary keys.
 * The other PK is the insertable's name, which must be unique on that one template.
 *
 * #### Smarty Parameters
 *
 *  * name
 *    * The key name of this input value, must be present and unique on this template.
 *  * assign
 *    * Assign the value instead of outputting to the screen.
 *  * title
 *    * When editing the insertable, the title displayed along side the input field.
 *  * type
 *
 * #### Example Usage
 *
 * <pre>
 * {insertable name="body" title="Body Content"}
 * <p>
 * This is some example content!
 * </p>
 * {/insertable}
 * </pre>
 *
 * <pre>
 * {insertable name="img1" title="Large Image" assign="img1"}
 * {img src="`$img1`" placeholder="generic" dimensions="800x400"}
 * {/insertable}
 * </pre>
 *
 * @param array       $params  Associative (and/or indexed) array of smarty parameters passed in from the template
 * @param string|null $content Null on opening pass, rendered source of the contents inside the block on closing pass
 * @param Smarty      $smarty  Parent Smarty template object
 * @param boolean     $repeat  True at the first call of the block-function (the opening tag) and
 * false on all subsequent calls to the block function (the block's closing tag).
 * Each time the function implementation returns with $repeat being TRUE,
 * the contents between {func}...{/func} are evaluated and the function implementation
 * is called again with the new block contents in the parameter $content.
 *
 * @return string
 */
function smarty_block_insertable($params, $content, $smarty, &$repeat){

	$assign = (isset($params['assign']))? $params['assign'] : false;

	// This only needs to be called once.
	// If a value is being assigned, then it's on the first pass so the value will be assigned by the time the content is hit.
	if($assign){
		if($repeat){
			// Running the first time with an assign variable, OK!
		}
		else{
			return $content;
		}
	}
	else{
		// No assign requested, run on the second only.
		if($repeat){
			return '';
		}
		else{
			// Continue!
		}
	}

	$page = PageRequest::GetSystemRequest()->getPageModel();

	// I need to use the parent to lookup the current base url.
	$baseurl = PageRequest::GetSystemRequest()->getBaseURL();

	if(!isset($params['name'])) return '';

	$i = InsertableModel::Construct($page->get('site'), $baseurl, $params['name']);

	if($i->exists()){
		$value = $i->get('value');
	}
	else{
		$value = $content;
	}

	if(isset($params['type']) && $params['type'] == 'markdown'){
		// Convert this markdown code to HTML via the built-in Michielf library.
		$value = Core\MarkdownProcessor::defaultTransform($value);
		//$value = Michelf\MarkdownExtra::defaultTransform($value);
	}
	else{
		// Coreify the string
		$value = \Core\parse_html($value);
	}

	if($assign){
		$smarty->assign($assign, $value);
	}
	else{
		return $value;
	}
}
/**
 * Get the system page request
 *
 * @return \PageRequest
 */
function page_request(){
	return \PageRequest::GetSystemRequest();
}