/**
  * Test a lookup to Google's public DNS and make sure that it returns appropriate information.
  */
 public function testGoogleLookup()
 {
     $request = new PageRequest('/phpwhois/lookup?q=8.8.8.8');
     // I need to spoof the GET request to add the necessary parameters.
     //$request->parameters['q'] = '8.8.8.8';
     $request->execute();
     $view = $request->getView();
     // The page should be a 200 status
     $this->assertEquals(200, $view->error);
     // Make sure this page is an ajax page.
     $this->assertEquals(View::MODE_AJAX, $view->mode);
     // And is a JSON page
     $this->assertEquals(View::CTYPE_JSON, $view->contenttype);
     // JSON Data needs to be set.
     $this->assertNotNull($view->jsondata);
     $this->assertNotEmpty($view->jsondata);
     // Make sure the JSON data is correct.
     $this->assertEquals('8.8.8.8', $view->jsondata['query']);
     $this->assertEquals('8.8.8.8', $view->jsondata['ip']);
     $this->assertEquals('8.8.8.0/24', $view->jsondata['network']);
     $this->assertEquals('Google Inc.', $view->jsondata['organization']);
     $this->assertEquals('US', $view->jsondata['country']);
     // @todo For whatever reason country_name isn't working... whatever, fix it soon.
     //$this->assertEquals('United States', $view->jsondata['country_name']);
 }
Example #2
0
	public function testBug(){
		$testcomponent = new Component_2_1(ROOT_PDIR . 'core/tests/testcomponent.xml');
		$this->assertInstanceOf('Component_2_1', $testcomponent);

		// Loading the component will read in the contents and get it setup.
		$testcomponent->load();
		$this->assertEquals('1.0.0', $testcomponent->getVersion());

		if($testcomponent->isInstalled()){
			// It's already installed?.... ok!
			$testcomponent->enable();
			$this->assertTrue($testcomponent->isEnabled());
		}
		else{
			// "Installing" a component should make it immediately enabled.
			$testcomponent->install();
			$this->assertTrue($testcomponent->isEnabled());
		}

		// So let's disable it!
		$testcomponent->disable();
		$this->assertFalse($testcomponent->isEnabled());

		// Now I can load it into core.
		// I couldn't do this before because the issue was that disabled components were being ignored completely.
		// This way when Core hits the component, it'll already be disabled.
		Core::Singleton()->_registerComponent($testcomponent);

		// And load up the page to make sure it's visible, (and enableable)
		// Update the current user so it has admin access.
		\Core\user()->set('admin', true);

		$request = new PageRequest('/updater');
		$request->execute();
		$view = $request->getView();
		$this->assertEquals(200, $view->error);
		// Obviously if the title gets changed, change it here to keep the bug from breaking!
		$this->assertEquals('t:STRING_SYSTEM_UPDATER', $view->title);

		// Get the body of this page and make sure that it's there.
		$html = $view->fetchBody();
		$matchtitle = 'Test Component';
		$matchmarkup = 'data-name="test-component" data-type="components"';


		$this->assertContains($matchtitle, $html, 'Failed to find the string "' . $matchtitle . '" on the updater page!');
		$this->assertContains($matchmarkup, $html, 'Failed to find the string "' . $matchmarkup . '" on the updater page!');


		// Lastly, cleanup this component!
		// Oh yeah.... uninstalling a component is needed!
		//$testcomponent->
		$this->markTestIncomplete('@todo Component uninstalling is not possible currently!');
	}
Example #3
0
 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.
	}
Example #5
0
 /**
  * Test that I can load the ATOM page and that it returns valid XML.
  * The XMLLoader will take care of the validation, since it should be a valid document anyway.
  */
 public function testATOMPage()
 {
     // Get the RSS feed and download it to a local file.
     $rewriteurl = $this->blog->get('rewriteurl');
     $this->assertNotEmpty($rewriteurl);
     // Go to the page and make sure that it loads up!
     $request = new PageRequest($rewriteurl . '.atom');
     $request->execute();
     $view = $request->getView();
     $this->assertEquals(200, $view->error);
     $markup = $view->fetch();
     $this->assertNotEmpty($markup);
     // DEVELOPMENT DEBUG
     //echo $markup; // DEBUG //
     $xml = new XMLLoader();
     $xml->setRootName('feed');
     // If it's invalid markup, this load will throw an error, causing phpunit to return an error :)
     // If the bug is fixed, this will not throw any errors.
     $xml->loadFromString($markup);
     $parsedmarkup = $xml->asMinifiedXML();
     $this->assertNotEmpty($parsedmarkup);
 }
	/**
	 * 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);
	}
Example #7
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);
		}
	}
	/**
	 * Load the values from either the page request or the session data.
	 *
	 * @param PageRequest $request
	 */
	public function load(PageRequest $request){
		// First, load everything from the session.
		$this->loadSession();

		$a = array();
		$s = array();
		$p = array();

		// Check the sort keys?
		if($this->hassort){
			if($request->getParameter('sortkey')){
				$this->setSortKey($request->getParameter('sortkey'));
				$s['sortkey'] = $this->_sortkey;
			}
			if($request->getParameter('sortdir')){
				$this->setSortDirection($request->getParameter('sortdir'));
				$s['sortdir'] = $this->_sortdir;
			}
		}

		// Did the user change a filter?
		// If a filter was changed, reset back to page 1!
		if($request->getParameter('filter')){
			$filters = $request->getParameter('filter');

			foreach($filters as $f => $v){
				if(!isset($this->_elementindexes['filter[' . $f . ']'])) continue;
				/** @var $el FormElement */
				$el = $this->_elementindexes['filter[' . $f . ']'];
				$el->setValue($v);

				// Remember this for the session data.
				$a[$f] = $v;
				$this->setPage(1);
				$p['page'] = 1;
			}
		}
		// How 'bout the pagination?
		elseif($this->haspagination){
			if($request->getParameter('page')){
				$this->setPage($request->getParameter('page'));
				$p['page'] = $this->_currentpage;
			}
			elseif($request->getParameter('limit')){
				$this->setPage(1);
				$p['page'] = 1;
				
				$this->setLimit($request->getParameter('limit'));
				$p['limit'] = $this->_limit;
			}
			// Don't change the filter sets, those have been cached and are fine as-is.
		}
		else{
			// No pagination or filters were modified... don't do anything.
		}


		if(sizeof($a)){
			\Core\Session::Set('filters/' . $this->_name, $a);
		}
		if(sizeof($s)){
			\Core\Session::Set('filtersort/' . $this->_name, $s);
		}
		if(sizeof($p)){
			\Core\Session::Set('filterpage/' . $this->_name, $p);
		}
	}
Example #9
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);
	}
}
/**
 * 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;
	}
}
Example #11
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.
	}
 public function moderate_request($data, $object_id, $dataset)
 {
     $request = new PageRequest();
     $user_id = (int) $this->getCurrentUser('id');
     if (!$user_id) {
         return false;
     }
     $form = array();
     $form_fields = array('firstname', 'lastname', 'position', 'organization', 'email', 'phone');
     foreach ($form_fields as $field) {
         if (isset($data[$field])) {
             $form[$field] = $data[$field];
         }
     }
     App::uses('CakeEmail', 'Network/Email');
     $Email = new CakeEmail('noreply');
     if (defined('MODERATE_REQUEST_test_email')) {
         $to_email = MODERATE_REQUEST_test_email;
         $to_name = MODERATE_REQUEST_test_name;
     } else {
         $to_email = $data['email'];
         $to_name = $data['firstname'] . ' ' . $data['lastname'];
     }
     $status = $Email->template('Dane.moderate_request_begin')->addHeaders(array('X-Mailer' => 'mojePaństwo'))->emailFormat('html')->subject('Cześć! Fajnie, że jesteś!')->to($to_email, $to_name)->from('*****@*****.**', 'Asia Przybylska')->replyTo('*****@*****.**', 'Asia Przybylska')->send();
     return $request->save(array('PageRequest' => array_merge($form, array('dataset' => $dataset, 'object_id' => $object_id, 'user_id' => $user_id))));
 }
	/**
	 * Get the page request for the current page.
	 *
	 * @return PageRequest
	 */
	protected function getPageRequest() {
		if ($this->_request === null) {
			$this->_request = PageRequest::GetSystemRequest();
		}
		return $this->_request;
	}
/**
 * @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;
	}
}
 /**
  * Internal shortcut function to setup ajax requests
  *
  * @param View        $view
  * @param PageRequest $request
  *
  * @return int
  */
 private function _setupAjaxRequest(View $view, PageRequest $request)
 {
     $view->mode = View::MODE_AJAX;
     $view->contenttype = View::CTYPE_JSON;
     if (!\Core\user()->checkAccess('p:/tinymce/imagebrowser/access')) {
         return View::ERROR_ACCESSDENIED;
     }
     if (!\Core\user()->checkAccess('p:/tinymce/imagebrowser/upload')) {
         return View::ERROR_ACCESSDENIED;
     }
     // Meant to be an AJAX POST page only.
     if (!$request->isPost()) {
         return View::ERROR_BADREQUEST;
     }
     if (!$request->isAjax()) {
         return View::ERROR_BADREQUEST;
     }
     // Otherwise, it goes through.
     return View::ERROR_NOERROR;
 }
Example #16
0
 /**
  * Test the creation of a blog article based off the newly created blog
  *
  * @depends testCreateBlog
  */
 public function testCreateBlogArticle()
 {
     // Update the current user so it has admin access.
     \Core\user()->set('admin', true);
     // Setup some variables that will be used throughout this method.
     $title = 'New Test Blog Article';
     $randomsnippet = 'Random-Snippet-' . Core::RandomHex(10);
     $lorem = new BaconIpsumGenerator();
     $body = $lorem->getParagraph(1);
     // Tack on the random snipped I'll be looking for.
     $body .= $lorem->getParagraphsAsMarkup(8, $randomsnippet);
     $blog = new BlogModel(self::$TestBlogID);
     $request = new PageRequest('/blog/article/create/' . self::$TestBlogID);
     $request->execute();
     $view = $request->getView();
     $this->assertEquals(200, $view->error, 'Checking that article creation returns a valid page');
     // The returned data should have a "form" available.  This is the actual creation form.
     /** @var $form Form */
     $form = $view->getVariable('form');
     $this->assertInstanceOf('Form', $form, 'Checking that the form is set from the blog article create controller');
     // Set some variables on the form
     $form->getElement('page[title]')->set('value', $title);
     $form->getElement('page[rewriteurl]')->set('value', $blog->get('rewriteurl') . '/' . \Core\str_to_url($title));
     $form->getElement('model[image]')->set('value', 'public/blog/blog-test-image.png');
     $form->getElement('model[body]')->set('value', $body);
     // Copy in the image
     $src = \Core\Filestore\Factory::File(ROOT_PDIR . 'components/blog/tests/blog-test-image.png');
     /** @var $dest \Core\Filestore\File */
     $dest = \Core\Filestore\Factory::File('public/blog/blog-test-image.png');
     $src->copyTo($dest, true);
     // make sure that it exists
     $this->assertTrue($dest->exists(), 'Checking that files can be copied into the public filestore');
     // And submit this form to the handler.
     // On a successful submission, it should be simply the URL of the blog.
     $formsubmission = call_user_func_array($form->get('callsmethod'), array($form));
     if ($formsubmission === false) {
         throw new Exception(implode("\n", $form->getErrors()));
     }
     // Go to the parent listing page and find this entry.
     $request = new PageRequest($blog->get('rewriteurl'));
     $request->execute();
     $view = $request->getView();
     $this->assertEquals(200, $view->error);
     $html = $view->fetch();
     $this->assertContains($title, $html);
     $this->assertContains('itemtype="http://schema.org/BlogPosting"', $html);
     preg_match_all('#<div[^>]*itemtype="http://schema.org/BlogPosting"[^>]*>.*<a[^>]*href="(.*)"[^>]*>(.*)</a>#msU', $html, $matches);
     // Title should now have three keys, with at least one value each.
     $this->assertNotEmpty($matches[1]);
     $this->assertNotEmpty($matches[2]);
     // This node contains the URL.
     $foundurl = $matches[1][0];
     $foundtitle = trim($matches[2][0]);
     // Make sure the url contains the site url.
     $this->assertStringStartsWith(ROOT_URL, $foundurl);
     // And trim it off.  This is because PageRequest expects that the url is already trimmed.
     $foundurl = '/' . substr($foundurl, strlen(ROOT_URL));
     $this->assertEquals($title, $foundtitle);
     //$this->assertStringStartsWith('/blog/article/view/', $formsubmission, 'Checking that blog article creation was successful');
     // Go to the page and make sure that it loads up!
     $request = new PageRequest($foundurl);
     $request->execute();
     $view = $request->getView();
     $this->assertEquals(200, $view->error, 'Checking that public blog article exists');
     $html = $view->fetch();
     $this->assertContains($title, $html, 'Checking that the public blog article page contains the correct title');
     $this->assertContains($randomsnippet, $html, 'Checking that the public blog article page contains the correct body');
     $this->assertContains('blog-test-image', $html, 'Checking that the public blog article page contains the correct image');
 }
 /**
  * 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);
 }
function bootstrap()
{
    global $CONFIG, $SYSTEM_INFO, $output_started, $body_started, $console, $profiler, $ALLOWED_MGMT_FUNCS;
    header("Content-type: application/xhtml+xml\r");
    $console = new SystemConsole();
    DEBUG("<strong>This is 29o3 " . $SYSTEM_INFO['SystemVersion'] . " Codename " . $SYSTEM_INFO['SystemCodename'] . "</strong>");
    DEBUG("SYS: Bootstrapping started...");
    $connector = new DatabaseConnector();
    $connector->setupConnection($CONFIG['DatabaseHost'], $CONFIG['DatabaseUser'], $CONFIG['DatabasePassword'], $CONFIG['DatabaseName'], $CONFIG['DatabasePort']);
    DEBUG("DB: Connected to database.");
    $request = new PageRequest($connector);
    $request->parseRequest();
    // instanciate new cache object
    $co = new cacheObject($connector, $request->getRequestedSite(), $request->getRequestedPage());
    // check if we have content for current page cached
    $cacheContent = $co->getCached();
    if ($cacheContent === false) {
        // construct header and body objects
        $header = new XHTMLHeader();
        $body = new XHTMLBody();
        $pdo = new pageDescriptionObject($header, $body, $connector, $request->getWantAdmin(), $request->getAdminFuncParam());
        $connector->executeQuery("SELECT * FROM " . mktablename("pages") . " WHERE name='" . $request->getRequestedPage() . "'");
        /* lets see what the admin wants */
        if ($request->getWantAdmin()) {
            if ($request->getRequestedPage() == "overview") {
            }
        }
        $pageInfo = $connector->fetchArray();
        $pdo->setPageDescriptionA($pageInfo, $request->getRequestedSite());
        $header->setTitle($pdo->getContent("title"));
        if ($pdo->getContent("description") != "") {
            $header->addMetaDCDescription($pdo->getContent('description'));
        }
        if ($pdo->getContent("subject") != "") {
            $header->addMetaDCSubject($pdo->getContent("subject"));
        }
        if ($pdo->getContent("date") != 0) {
            $header->addMetaDCDate(strftime("%Y-%m-%d", $pdo->getContent('date')));
        }
        if ($pdo->getContent("creator") != "") {
            $header->addMetaDCCreator($pdo->getContent("creator"));
        }
        if ($pdo->getContent("contributors") != "") {
            $c_arr = explode(";", $pdo->getContent('contributors'));
            for ($i = 0; $i <= count($c_arr) - 1; $i++) {
                $header->addMetaDCContributor($c_arr[$i]);
            }
        }
        if ($pdo->getContent("type") != "") {
            $header->addMetaDCType($pdo->getContent("type"));
        }
        if ($pdo->getContent("sources") != "") {
            $sources_array = explode(";", $pdo->getContent('sources'));
            for ($i = 0; $i <= count($sources_array) - 1; $i++) {
                $header->addMetaDCSource($sources_array[$i]);
            }
        }
        /*
        !!!	FIXME: 	THE FOLLOWING CODE CAUSES A RACE CONDITION ON BOTH APACHE2/PHP
        !!!		AND PHP-CLI. 
        !!!	SEV:   	(5) - Causes server process to fill RAM and swap -> kill
        !!!	RES:	Currently no resolution, commented out because of this.
        !!!		I'd say it has got something to do with the database for
        !!!		I cannot find an error elsewhere.
        >!<	*** FIXED ***
        >!<	F**K YOU F**K YOU DAMN CODER!!!! F**K YOU!!!
        */
        if ($pdo->getContent("language") != "") {
            $header->addMetaDCLanguage($pdo->getContent('language'));
        }
        if ($pdo->getContent('copyright') != "") {
            $header->addMetaDCRights($pdo->getContent("copyright"));
        }
        // this is the r0x0r1ng stylesheet which controls how system messages (errors, etc.) appear
        $pdo->scheduleInsertion_ExternalStylesheet("n_style.css");
        if ($pdo->getContent('no_cache') == 1) {
            $co->setScheduleCaching(false);
            DEBUG("CACHE: Caching deactivated on request.");
        }
        // now, get the page's stylesheet; it might be empty, but we'll add it if not :)
        if ($request->getWantAdmin() <= 1) {
            if ($request->getWantAdmin() == 1) {
                $co->setScheduleCaching(false);
                DEBUG("CACHE: Admin wanted, caching deactivated.");
            }
            $layoutManager = new LayoutManager($pdo);
            $pdo->getAvailableBoxes();
            $connector->executeQuery("SELECT * FROM " . mktablename("layouts") . " WHERE lname='" . $pageInfo['layout'] . "'");
            if ($connector->getNumRows() != 0) {
                $currentLayout = $connector->fetchArray();
                $layoutManager->setLayoutFile($currentLayout['file']);
                $layoutManager->parseLayout();
            } else {
                throw new GeneralException("No layout found. 29o3 cannot continue.");
            }
            if ($request->getWantAdmin()) {
                require_once $CONFIG['LibDir'] . 'admin/adminFuncs.php';
                $af = new adminFuncs($pdo, $request);
                $pdo->scheduleInsertion_ExternalStylesheet($af->getAdminStylesheet());
            }
            DEBUG("DB: " . $connector->getExecutedQueries() . " queries executed.");
            $connector->closeConnection();
            DEBUG("DB: Connection closed.");
            $profiler->addBreakpoint();
            DEBUG("SYS: Resource usage,  sys:" . $profiler->getBreakpointGrandSysDifference() . "&micro;s usr:"******"&micro;s");
            DEBUG("SYS: Exiting normally.");
            // print the buffer of the header since we're done with it :)
            $pdo->doInsertions();
            // we have everything at this point... start caching procedure
            $co->doCache($pdo->getBuffers());
            if ($CONFIG['Developer_Debug'] == true) {
                if ($body) {
                    $body->eyecandyConsole($console);
                } else {
                    $console->printBuffer();
                }
            }
            if ($pdo->getBrandingState() == true) {
                $pdo->insertBodyDiv("Powered by <a href=\"http://twonineothree.berlios.de\">29o3</a> " . $SYSTEM_INFO["SystemVersion"] . " Codename " . $SYSTEM_INFO["SystemCodename"], "poweredBy", "poweredBy_Banner", "Powered by 29o3");
            }
            printf('<?xml version="1.0" encoding="UTF-8"?>');
            printf('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">%s', "\n");
            printf('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">%s', "\n");
            $pdo->printHeaderBuffer();
            $header_started = true;
            // destruct the header object
            $pdo->destroyHeaderObject();
            $body_started = true;
            // print out the body buffer
            $pdo->printBodyBuffer();
            printf('</html>');
            // exit normally.
            exit(0);
        } else {
            $co->setScheduleCaching(false);
            $pdo->setOmitBranding(true);
            DEBUG("CACHE: Admin wanted, caching deactivated.");
            require_once $CONFIG['LibDir'] . 'admin/adminFuncs.php';
            $co->setScheduleCaching(false);
            $af = new adminFuncs($pdo, $request);
            $pdo->scheduleInsertion_ExternalStylesheet($af->getAdminStylesheet());
            //			$pdo->insertBodyDiv("<img src=\"lib/images/adminlogotop.png\" style=\"vertical-align: top; text-align: left; border: 0; padding: 0; margin: 0;\" /><span class=\"adminMenu\" style=\"width: 100%;\">" . $af->getAdminMenu() . "</span>", "adminStripe", "2mc_menu", "29o3 management console");
            // this part is for the admin scripts which require
            // are not fetched from database
            DEBUG("SYS: Skipping normal layout and box fetching procedures");
            $header->setTitle("29o3 management console");
            $ao = NULL;
            $func = $request->getWantedAdminFunc();
            if (!array_search($func, $ALLOWED_MGMT_FUNCS)) {
                $func = "Overview";
            }
            // administration needs admin logged in
            $sm = new sessionManager($connector);
            if ($sm->checkSession() == false) {
                DEBUG("MGMT: Admin not logged in.");
                $func = "Login";
            }
            if ($func == "Logout") {
                $sm->invalidateSession();
                header("Location: " . mksyslink("?"));
            }
            require_once $CONFIG["LibDir"] . 'admin/admin' . $func . '.php';
            $name = "Admin" . $func;
            $ao = new $name($connector, $pdo, $sm);
            $ao->doPreBodyJobs();
            $pdo->insertIntoBodyBuffer($af->getAdminMenu());
            $ao->doBodyJobs();
            DEBUG("DB: " . $connector->getExecutedQueries() . " queries executed.");
            $profiler->addBreakpoint();
            DEBUG("SYS: Resource usage,  sys:" . $profiler->getBreakpointGrandSysDifference() . "&micro;s usr:"******"&micro;s");
            $connector->closeConnection();
            DEBUG("DB: Connection closed.");
            DEBUG("SYS: Exiting normally.");
            if ($CONFIG['Developer_Debug'] == true) {
                if ($body) {
                    $body->eyecandyConsole($console);
                } else {
                    $console->printBuffer();
                }
            }
            //			$pdo->insertBodyDiv("Powered by <a href=\"http://twonineothree.berlios.de\">29o3</a> " . $SYSTEM_INFO["SystemVersion"] . " Codename " . $SYSTEM_INFO["SystemCodename"], "poweredBy", "poweredBy_Banner", "Powered by 29o3");
            // print the buffer of the header since we're done with it :)
            printf('<?xml version="1.0" encoding="UTF-8"?>');
            printf('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">%s', "\n");
            printf('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">%s', "\n");
            $pdo->doInsertions();
            $pdo->printHeaderBuffer();
            $header_started = true;
            // destruct the header object
            $pdo->destroyHeaderObject();
            $body_started = true;
            // print out the body buffer
            $pdo->printBodyBuffer();
            printf('</html>');
            // exit normally
            exit(0);
        }
    } else {
        echo $co->getCacheContent();
        DEBUG("DB: " . $connector->getExecutedQueries() . " queries executed.");
        $profiler->addBreakpoint();
        DEBUG("SYS: Resource usage,  sys:" . $profiler->getBreakpointGrandSysDifference() . "&micro;s usr:"******"&micro;s");
        $connector->closeConnection();
        DEBUG("DB: Connection closed.");
        DEBUG("SYS: Exiting normally.");
        if ($CONFIG['Developer_Debug'] == true) {
            echo '<center><div class="eyecandyConsole">' . $console->getBuffer() . '</div></center>';
        }
        echo "\n</body>\n</html>";
        // exit normally
        exit(0);
    }
    // never reached
}
Example #19
0
        print htmlentities($key) . "=[" . htmlentities($value) . "]<br />\n";
    }
}
?>
        <h1>Dump of $_GET data</h1>
        <?php 
print '<pre>';
print_r($_GET);
print '</pre>';
?>
        <h1>Raw POST data</h1>
        <?php 
print "[" . $HTTP_RAW_POST_DATA . "]";
?>
        <pre><?php 
print_r(PageRequest::post());
?>
</pre>
        <h1>POST data</h1>
        <?php 
function show_array_value($array)
{
    $html = "";
    foreach ($array as $key => $value) {
        $html .= htmlentities($key) . "=[";
        if (is_array($value)) {
            $html .= show_array_value($value);
        } else {
            $html .= htmlentities($value);
        }
        $html .= "]";
Example #20
0
 static function post()
 {
     $request = new PageRequest(file_get_contents("php://input"));
     // HTTP_RAW_POST_DATA -- http://us.php.net/manual/en/wrappers.php.php
     return $request->getAll();
 }
 function post()
 {
     global $HTTP_RAW_POST_DATA;
     $request = new PageRequest($HTTP_RAW_POST_DATA);
     return $request->getAll();
 }
Example #22
0
/**
 * Get the system page request
 *
 * @return \PageRequest
 */
function page_request(){
	return \PageRequest::GetSystemRequest();
}