/**
  * Form Handler to save a content quick create.
  *
  * @param Form $form
  *
  * @return string|bool
  */
 public static function QuickDraftSave(Form $form)
 {
     if (!$form->getElementValue('title')) {
         \Core\set_message('All pages must have titles.', 'error');
         return false;
     }
     /** @var $model ContentModel */
     $model = new ContentModel();
     /** @var $page PageModel Page object for this model, already linked up! */
     $page = $model->getLink('Page');
     // The content nickname is derived from the page title.
     $model->set('nickname', $form->getElementValue('title'));
     $model->save();
     $ins = new InsertableModel();
     $ins->set('site', $page->get('site'));
     $ins->set('baseurl', '/content/view/' . $model->get('id'));
     $ins->set('name', 'body');
     $ins->set('value', '<p>' . nl2br($form->getElementValue('content')) . '</p>');
     $ins->save();
     $page->set('title', $form->getElementValue('title'));
     $page->set('published_status', 'draft');
     $page->set('editurl', '/content/edit/' . $model->get('id'));
     $page->set('deleteurl', '/content/delete/' . $model->get('id'));
     $page->set('component', 'content');
     $page->save();
     return true;
 }
 public function index()
 {
     $view = $this->getView();
     $request = $this->getPageRequest();
     if (!\Core\user()->checkAccess('g:admin')) {
         return View::ERROR_ACCESSDENIED;
     }
     if ($request->isPost()) {
         // Update/save the site id.
         ConfigHandler::Set('/livefyre/siteid', $_POST['siteid']);
         \Core\set_message('Set Site ID Successfully!', 'success');
         \Core\reload();
     }
     // Pull the configuration options to see if livefyre is currently setup.
     $siteid = ConfigHandler::Get('/livefyre/siteid');
     // Generate the form to either set or update the siteid.
     $form = new Form();
     $form->set('method', 'POST');
     $form->addElement('text', ['name' => 'siteid', 'title' => 'Site ID', 'value' => $siteid]);
     $view->assign('siteid', $siteid);
     $view->assign('url', ROOT_URL_NOSSL);
     $view->assign('form', $form);
     // Setup instructions:
     // http://www.livefyre.com/install/
 }
 public function rebuild()
 {
     $request = $this->getPageRequest();
     $view = $this->getView();
     if (!\Core\user()->checkAccess('g:admin')) {
         return View::ERROR_ACCESSDENIED;
     }
     $changes = PackageRepositoryPackageModel::RebuildPackages();
     $msgs = [];
     if ($changes['updated']) {
         $msgs[] = 'Updated ' . $changes['updated'] . ' packages.';
     }
     if ($changes['skipped']) {
         $msgs[] = 'Skipped ' . $changes['skipped'] . ' packages.';
     }
     if ($changes['failed']) {
         $msgs[] = 'Ignored ' . $changes['failed'] . ' corrupt packages.';
     }
     \Core\set_message(implode(' ', $msgs), 'success');
     \Core\go_back();
 }
Exemple #4
0
 /**
  * The hook catch for the "/core/admin/view" hook.
  */
 public static function AdminHook()
 {
     // If this user doesn't have access to manage crons, just continue.
     if (!\Core\user()->checkAccess('p:/cron/viewlog')) {
         return;
     }
     $suffixtext = 'This could be a problem if you have scripts relying on it!  <a href="' . \Core\resolve_link('/cron/howto') . '">Read how to resolve this issue</a>.';
     // Lookup and make sure that the cron hooks have ran recently enough!
     $checks = [['cron' => 'hourly', 'modify' => '-1 hour', 'label' => 'hour'], ['cron' => 'daily', 'modify' => '-1 day', 'label' => 'day'], ['cron' => 'weekly', 'modify' => '-1 week', 'label' => 'week'], ['cron' => 'monthly', 'modify' => '-1 month', 'label' => 'month']];
     foreach ($checks as $check) {
         $time = new CoreDateTime();
         $cronfac = new ModelFactory('CronLogModel');
         $cronfac->where('cron = ' . $check['cron']);
         $time->modify($check['modify']);
         $cronfac->where('created >= ' . $time->getFormatted('U', Time::TIMEZONE_GMT));
         $count = $cronfac->count();
         if ($count == 0) {
             \Core\set_message('Your ' . $check['cron'] . ' cron has not run in the last ' . $check['label'] . '!  ' . $suffixtext, 'error');
             // Only complain to the admin once per view.
             return;
         }
     }
 }
 public function configure()
 {
     $view = $this->getView();
     $request = $this->getPageRequest();
     if (!\Core\user()->checkAccess('g:admin')) {
         return View::ERROR_ACCESSDENIED;
     }
     if ($request->isPost()) {
         \ConfigHandler::Set('/piwik/server/host', $_POST['server_host']);
         \ConfigHandler::Set('/piwik/siteid', $_POST['site_id']);
         \ConfigHandler::Set('/piwik/tracking/all_subdomains', $_POST['all_domains']);
         \ConfigHandler::Set('/piwik/tracking/domain_title', $_POST['domain_title']);
         \Core\set_message('Updated Piwik settings successfully', 'success');
         \Core\reload();
     }
     $form = new Form();
     $form->addElement('text', ['name' => 'server_host', 'title' => 'Server Host', 'required' => false, 'value' => \ConfigHandler::Get('/piwik/server/host'), 'description' => 'Enter the hostname of your Piwik server without the protocol']);
     $form->addElement('text', ['name' => 'site_id', 'title' => 'Site ID', 'required' => false, 'value' => \ConfigHandler::Get('/piwik/siteid'), 'description' => 'Enter the Site ID of this installation']);
     $form->addElement('checkbox', ['name' => 'all_domains', 'title' => 'Track visitors across all subdomains of your site', 'description' => 'So if one visitor visits x.corepl.us and y.corepl.us, they will be counted as a single unique visitor.', 'value' => '1', 'checked' => \ConfigHandler::Get('/piwik/tracking/all_subdomains')]);
     $form->addElement('checkbox', ['name' => 'domain_title', 'title' => 'Prepend the site domain to the page title when tracking', 'description' => 'So if someone visits the "About" page on blog.corepl.us it will be recorded as "blog / About". This is the easiest way to get an overview of your traffic by sub-domain. ', 'value' => '1', 'checked' => \ConfigHandler::Get('/piwik/tracking/domain_title')]);
     $form->addElement('submit', ['name' => 'submit', 'value' => 'Update']);
     $view->title = 'Piwik Analytics';
     $view->assign('form', $form);
 }
	public static function _UpdateFormHandler(Form $form){

		try{
			/** @var UserGroupModel $model */
			$model = $form->getModel();

			if(\Core\user()->checkAccess('p:/user/permissions/manage')){
				// hehe... this is kind of a hack that works.
				// it's a hack because "getElement" returns only 1 element, but it works
				// because all those elements share the same POST name.
				// As such, the value from all permission[] checkboxes actually get transposed to all
				// form elements with that same base name.
				$model->setPermissions($form->getElement('permissions[]')->get('value'));
			}

			if($model->get('context') != ''){
				// Non-global context groups can never be default!
				$model->set('default', 0);
			}

			$model->save();
		}
		catch(ModelValidationException $e){
			\Core\set_message($e->getMessage(), 'error');
			return false;
		}
		catch(Exception $e){
			\Core\set_message($e->getMessage(), 'error');
			return false;
		}

		return '/usergroupadmin';
	}
	/**
	 * There has been a file selected; check that file for headers and what not to display something useful to the user.
	 */
	private function _import2(){
		$view = $this->getView();
		$request = $this->getPageRequest();

		$filename = \Core\Session::Get('user-import/file');
		$file = \Core\Filestore\Factory::File($filename);
		$contents = $file->getContentsObject();

		if(!$contents instanceof \Core\Filestore\Contents\ContentCSV){
			\Core\set_message($file->getBaseFilename() . ' does not appear to be a valid CSV file!', 'error');
			\Core\Session::UnsetKey('user-import/file');
			\Core\reload();
		}

		$hasheader = $contents->hasHeader();
		$data = $contents->parse();
		$total = sizeof($data);

		// Since I don't want to display the entire dataset in the preview...
		if($hasheader){
			$header = $contents->getHeader();
		}
		else{
			$header = array();
			$i=0;
			foreach($data[0] as $k => $v){
				$header[$i] = 'Column ' . ($i+1);
				$i++;
			}
		}
		$colcount = sizeof($header);

		if($total > 11){
			$preview = array_splice($data, 0, 10);
		}
		else{
			$preview = $data;
		}

		$form = new Form();
		$form->set('callsmethod', 'User\\ImportHelper::FormHandler2');
		$form->addElement('system', ['name' => 'key', 'value' => \Core\Session::Get('user-import/key')]);
		$form->addElement(
			'checkbox',
			[
				'name' => 'has_header',
				'title' => 'Has Header',
				'value' => 1,
				'checked' => $hasheader,
				'description' => 'If this CSV has a header record on line 1, (as illustrated below), check this to ignore that line.'
			]
		);

		$form->addElement(
			'checkbox',
			[
				'name' => 'merge_duplicates',
				'title' => 'Merge Duplicate Records',
				'value' => 1,
				'checked' => true,
				'description' => 'Merge duplicate records that may be found in the import.'
			]
		);

		// Only display the user groups if the current user has access to manage user groups.
		$usergroups = UserGroupModel::Find(['context = ']);
		if(sizeof($usergroups) && \Core\user()->checkAccess('p:/user/groups/manage')){
			$usergroupopts = array();
			foreach($usergroups as $ug){
				$usergroupopts[$ug->get('id')] = $ug->get('name');
			}
			$form->addElement(
				'checkboxes',
				[
					'name' => 'groups[]',
					'title' => 'User Groups to Assign',
					'options' => $usergroupopts,
					'description' => 'Check which groups to set the imported users to.  If merge duplicate records is selected, any found users will be set to the checked groups, (and consequently unset from any unchecked groups).',
				]
			);
		}
		else{
			$form->addElement('hidden', ['name' => 'groups[]', 'value' => '']);
		}

		// Get the map-to options.
		$maptos = ['' => '-- Do Not Map --', 'email' => 'Email', 'password' => 'Password'];

		$configs = UserConfigModel::Find([], null, 'weight asc, name desc');
		foreach($configs as $c){
			$maptos[ $c->get('key') ] = $c->get('name');
		}

		$maptoselects = [];
		foreach($header as $key => $title){
			$value = '';
			if(isset($maptos[$key])) $value = $key;
			if(array_search($title, $maptos)) $value = array_search($title, $maptos);

			$form->addElement(
				'select',
				[
					'name' => 'mapto[' . $key . ']',
					'title' => $title,
					'options' => $maptos,
					'value' => $value
				]
			);
		}


		$view->templatename = 'pages/user/import2.tpl';
		$view->assign('has_header', $hasheader);
		$view->assign('header', $header);
		$view->assign('preview', $preview);
		$view->assign('form', $form);
		$view->assign('total', $total);
		$view->assign('col_count', $colcount);
	}
	/**
	 * Form Handler for logging in.
	 *
	 * @static
	 *
	 * @param \Form $form
	 *
	 * @return bool|null|string
	 */
	public static function LoginHandler(\Form $form){
		/** @var \FormElement $e */
		$e = $form->getElement('email');
		/** @var \FormElement $p */
		$p = $form->getElement('pass');


		/** @var \UserModel $u */
		$u = \UserModel::Find(array('email' => $e->get('value')), 1);

		if(!$u){
			// Log this as a login attempt!
			$logmsg = 'Failed Login. Email not registered' . "\n" . 'Email: ' . $e->get('value') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login', $logmsg);
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_EMAIL_NOT_FOUND');
			return false;
		}

		if($u->get('active') == 0){
			// The model provides a quick cut-off for active/inactive users.
			// This is the control managed with in the admin.
			$logmsg = 'Failed Login. User tried to login before account activation' . "\n" . 'User: '******'email') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login', $logmsg, null, $u->get('id'));
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_ACCOUNT_NOT_ACTIVE');
			return false;
		}
		elseif($u->get('active') == -1){
			// The model provides a quick cut-off for active/inactive users.
			// This is the control managed with in the admin.
			$logmsg = 'Failed Login. User tried to login after account deactivation.' . "\n" . 'User: '******'email') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login', $logmsg, null, $u->get('id'));
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_ACCOUNT_DEACTIVATED');
			return false;
		}

		try{
			/** @var \Core\User\AuthDrivers\datastore $auth */
			$auth = $u->getAuthDriver('datastore');
		}
		catch(Exception $e){
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_PASSWORD_AUTH_DISABLED');
			return false;
		}


		// This is a special case if the password isn't set yet.
		// It can happen with imported users or if a password is invalidated.
		if($u->get('password') == ''){
			// Use the Nonce system to generate a one-time key with this user's data.
			$nonce = \NonceModel::Generate(
				'20 minutes',
				['type' => 'password-reset', 'user' => $u->get('id')]
			);

			$link = '/datastoreauth/forgotpassword?e=' . urlencode($u->get('email')) . '&n=' . $nonce;

			$email = new \Email();
			$email->setSubject('Initial Password Request');
			$email->to($u->get('email'));
			$email->assign('link', \Core\resolve_link($link));
			$email->assign('ip', REMOTE_IP);
			$email->templatename = 'emails/user/initialpassword.tpl';
			try{
				$email->send();
				\SystemLogModel::LogSecurityEvent('/user/initialpassword/send', 'Initial password request sent successfully', null, $u->get('id'));

				\Core\set_message('t:MESSAGE_INFO_USER_LOGIN_MUST_SET_NEW_PASSWORD_INSTRUCTIONS_HAVE_BEEN_EMAILED');
				return true;
			}
			catch(\Exception $e){
				\Core\ErrorManagement\exception_handler($e);
				\Core\set_message('t:MESSAGE_ERROR_USER_LOGIN_MUST_SET_NEW_PASSWORD_UNABLE_TO_SEND_EMAIL');
				return false;
			}
		}


		if(!$auth->checkPassword($p->get('value'))){

			// Log this as a login attempt!
			$logmsg = 'Failed Login. Invalid password' . "\n" . 'Email: ' . $e->get('value') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login/failed_password', $logmsg, null, $u->get('id'));

			// Also, I want to look up and see how many login attempts there have been in the past couple minutes.
			// If there are too many, I need to start slowing the attempts.
			$time = new \CoreDateTime();
			$time->modify('-5 minutes');

			$securityfactory = new \ModelFactory('SystemLogModel');
			$securityfactory->where('code = /user/login/failed_password');
			$securityfactory->where('datetime > ' . $time->getFormatted(\Time::FORMAT_EPOCH, \Time::TIMEZONE_GMT));
			$securityfactory->where('ip_addr = ' . REMOTE_IP);

			$attempts = $securityfactory->count();
			if($attempts > 4){
				// Start slowing down the response.  This should help deter brute force attempts.
				// (x+((x-7)/4)^3)-4
				sleep( ($attempts+(($attempts-7)/4)^3)-4 );
				// This makes a nice little curve with the following delays:
				// 5th  attempt: 0.85
				// 6th  attempt: 2.05
				// 7th  attempt: 3.02
				// 8th  attempt: 4.05
				// 9th  attempt: 5.15
				// 10th attempt: 6.52
				// 11th attempt: 8.10
				// 12th attempt: 10.05
			}

			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_INCORRECT_PASSWORD');
			$p->set('value', '');
			return false;
		}


		if($form->getElementValue('redirect')){
			// The page was set via client-side javascript on the login page.
			// This is the most reliable option.
			$url = $form->getElementValue('redirect');
		}
		elseif(REL_REQUEST_PATH == '/user/login'){
			// If the user came from the registration page, get the page before that.
			$url = $form->referrer;
		}
		else{
			// else the registration link is now on the same page as the 403 handler.
			$url = REL_REQUEST_PATH;
		}

		// Well, record this too!
		\SystemLogModel::LogSecurityEvent('/user/login', 'Login successful (via password)', null, $u->get('id'));

		// yay...
		$u->set('last_login', \CoreDateTime::Now('U', \Time::TIMEZONE_GMT));
		$u->save();
		\Core\Session::SetUser($u);

		// Allow an external script to override the redirecting URL.
		$overrideurl = \HookHandler::DispatchHook('/user/postlogin/getredirecturl');
		if($overrideurl){
			$url = $overrideurl;
		}

		return $url;
	}
 /**
  * Administrative page for configuring the Captcha settings.
  */
 public function admin()
 {
     $view = $this->getView();
     $request = $this->getPageRequest();
     // This is an admin-only page.
     if (!\Core\user()->checkAccess('g:admin')) {
         return View::ERROR_ACCESSDENIED;
     }
     // width, height
     // colors
     $presets = ['simple' => ['name' => 'I trust and like my visitors', 'alt' => 'Simple and easy', 'configs' => ['/captcha/minlength' => 4, '/captcha/maxlength' => 5, '/captcha/linethrough' => 0, '/captcha/yperiod' => 12, '/captcha/yamplitude' => 14, '/captcha/xperiod' => 11, '/captcha/xamplitude' => 2, '/captcha/maxrotation' => 4, '/captcha/blur' => false]], 'med' => ['name' => 'Meh...', 'alt' => 'Moderate level of difficulty', 'configs' => ['/captcha/minlength' => 5, '/captcha/maxlength' => 7, '/captcha/linethrough' => 1, '/captcha/yperiod' => 12, '/captcha/yamplitude' => 14, '/captcha/xperiod' => 11, '/captcha/xamplitude' => 2, '/captcha/maxrotation' => 8, '/captcha/blur' => true]], 'hard' => ['name' => 'All visitors deserve to be punished!', 'alt' => 'Hieroglyphics are easier', 'configs' => ['/captcha/minlength' => 6, '/captcha/maxlength' => 9, '/captcha/linethrough' => 4, '/captcha/yperiod' => 12, '/captcha/yamplitude' => 20, '/captcha/xperiod' => 11, '/captcha/xamplitude' => 6, '/captcha/maxrotation' => 12, '/captcha/blur' => true]]];
     // See if there's a preset option selected.
     $current = null;
     foreach ($presets as $key => $preset) {
         // This will skim through each preset and if all the options are set to this preset, then it must be the current.
         foreach ($preset['configs'] as $k => $v) {
             if (ConfigHandler::Get($k) != $v) {
                 continue 2;
             }
         }
         // Did it not continue?  Must be the current preset.
         //$current = $preset;
         $current = $key;
         break;
     }
     // This page uses a traditional form post.
     if ($request->isPost()) {
         // See if there's a preset
         $postpreset = $request->getPost('preset');
         if ($postpreset && $postpreset != $current && isset($presets[$postpreset])) {
             foreach ($presets[$postpreset]['configs'] as $k => $v) {
                 ConfigHandler::Set($k, $v);
             }
             \Core\set_message('Switched to ' . $presets[$postpreset]['name'] . ' preset.', 'success');
         }
         // And the blah post options.
         $postwidth = $request->getPost('width');
         $postheight = $request->getPost('height');
         $posttext = $request->getPost('formtext');
         if ($postwidth <= 0) {
             $postwidth = 100;
         }
         if ($postwidth > 400) {
             $postwidth = 400;
         }
         if ($postheight <= 0) {
             $postheight = 100;
         }
         if ($postheight > 200) {
             $postheight = 200;
         }
         if (!$posttext) {
             $posttext = 'Are you a Human?';
         }
         ConfigHandler::Set('/captcha/width', $postwidth);
         ConfigHandler::Set('/captcha/height', $postheight);
         ConfigHandler::Set('/captcha/formtext', $posttext);
         \Core\reload();
     }
     // Build the form.  This will be pretty simple :p
     $form = new Form();
     $presetoptions = array();
     if (!$current) {
         // Add the custom settings option.
         $presetoptions[''] = '-- Custom Settings --';
     }
     foreach ($presets as $key => $preset) {
         $presetoptions[$key] = $preset['name'] . ' (' . $preset['alt'] . ')';
     }
     $form->addElement('select', ['name' => 'preset', 'title' => 'Difficulty Level', 'options' => $presetoptions, 'value' => $current ? $current : '']);
     $form->addElement('text', ['name' => 'width', 'title' => 'Image Width', 'value' => ConfigHandler::Get('/captcha/width')]);
     $form->addElement('text', ['name' => 'height', 'title' => 'Image Height', 'value' => ConfigHandler::Get('/captcha/height')]);
     $form->addElement('text', ['name' => 'formtext', 'title' => 'Form Text', 'value' => ConfigHandler::Get('/captcha/formtext')]);
     // @todo Colors for foreground and background.
     $form->addElement('submit', ['name' => 'submit', 'value' => 'Save Settings']);
     $view->mastertemplate = 'admin';
     $view->title = 'Captcha Tweaks';
     $view->assign('form', $form);
 }
 /**
  * POST-only view to disable a user's Facebook login ability.
  * @return int
  */
 public function disable()
 {
     $view = $this->getView();
     $request = $this->getPageRequest();
     $userid = $request->getParameter(0);
     $isadmin = \Core\user()->checkAccess('p:/user/users/manage');
     // Current user an admin?
     $isself = \Core\user()->get('id') == $userid;
     if (!($isadmin || $isself)) {
         return View::ERROR_ACCESSDENIED;
     }
     if (!$request->isPost()) {
         return View::ERROR_BADREQUEST;
     }
     /** @var UserModel $user */
     $user = UserModel::Construct($userid);
     if (!$user->exists()) {
         return View::ERROR_NOTFOUND;
     }
     if (sizeof($user->getEnabledAuthDrivers()) == 1) {
         return View::ERROR_OTHER;
     }
     $user->disableAuthDriver('facebook');
     $user->save();
     \Core\set_message('Disabled Facebook logins!', 'success');
     \Core\go_back();
 }
 public static function _SaveEditorHandler(Form $form)
 {
     $newmodel = $form->getModel();
     $file = $form->getElement('file')->get('value');
     $activefile = $form->getElement('filetype')->get('value');
     // The inbound file types depends on how to read the file.
     switch ($activefile) {
         case 'template':
             $filename = \Core\Templates\Template::ResolveFile($file);
             $customfilename = ROOT_PDIR . 'themes/custom/' . $file;
             break;
         case 'file':
             $filename = $file;
             // It'll get transposed.
             $customfilename = ROOT_PDIR . 'themes/custom/' . $file;
             break;
         default:
             \Core\set_message('Unsupported file type: ' . $activefile, 'error');
             return false;
     }
     $customfh = \Core\Filestore\Factory::File($customfilename);
     if ($customfh->exists()) {
         // If the custom one exists... this will be the source file too!
         $sourcefh = $customfh;
     } else {
         $sourcefh = \Core\Filestore\Factory::File($filename);
     }
     // Check and see if they're the same, ie: no change.  I don't want to create a bunch of moot revisions.
     if ($newmodel->get('content') == $sourcefh->getContents()) {
         \Core\set_message('No changes performed.', 'info');
         return '/theme';
     }
     // Before I overwrite this file, check and see if the original has been snapshot first!
     $c = ThemeTemplateChangeModel::Count(['filename = ' . $file]);
     if (!$c) {
         $original = new ThemeTemplateChangeModel();
         $original->setFromArray(['comment' => 'Original File', 'filename' => $file, 'content' => $sourcefh->getContents(), 'content_md5' => $sourcefh->getHash(), 'updated' => $sourcefh->getMTime()]);
         $original->save();
     }
     // All destination files get written to the custom directory!
     $customfh->putContents($newmodel->get('content'));
     $hash = $customfh->getHash();
     /*
     		// What happens now is based on the type of the inbound file.
     		switch($activefile){
     			case 'skin':
     				// Just replace the contents of that file.
     				$fh->putContents($newmodel->get('content'));
     				$hash = $fh->getHash();
     				break;
     			case 'template':
     				// This gets written into the current theme directory.
     				$themefh = \Core\Filestore\Factory::File(ROOT_PDIR . 'themes/' . ConfigHandler::Get('/theme/selected') . '/' . $file);
     				$themefh->putContents($newmodel->get('content'));
     				$hash = $themefh->getHash();
     				break;
     			case 'style':
     			case 'file':
     				// This gets written into the current theme directory.
     				$themefh = \Core\Filestore\Factory::File(ROOT_PDIR . 'themes/' . ConfigHandler::Get('/theme/selected') . '/' . $file);
     				$themefh->putContents($newmodel->get('content'));
     				$hash = $themefh->getHash();
     
     				// This is required to get assets updated to the CDN correctly.
     				$theme = ThemeHandler::GetTheme();
     				$hash = $themefh->getHash();
     				$theme->addAssetFile(array('file' => $file, 'md5' => $hash));
     				$theme->save();
     				$theme->reinstall();
     			default:
     		}
     */
     // Make a record of this change too!
     $change = new ThemeTemplateChangeModel();
     $change->setFromArray(['comment' => $newmodel->get('comment'), 'filename' => $file, 'content' => $newmodel->get('content'), 'content_md5' => $hash]);
     $change->save();
     if ($activefile == 'file') {
         // Reinstall all assets too!
         foreach (Core::GetComponents() as $component) {
             $component->reinstall();
         }
         // And the current theme.
         ThemeHandler::GetTheme(ConfigHandler::Get('/theme/selected'))->reinstall();
     }
     \Core\set_message('Updated file successfully', 'success');
     return '/theme';
 }
Exemple #12
0
	public static function UpdateHandler(\Form $form){

		/** @var \UserModel $user */
		$user        = $form->getElement('user')->get('value');
		$userid      = $user->get('id');
		$usermanager = \Core\user()->checkAccess('p:/user/users/manage');

		// Only allow this if the user is either the same user or has the user manage permission.
		if(!($userid == \Core\user()->get('id') || $usermanager)){
			\Core\set_message('t:MESSAGE_ERROR_INSUFFICIENT_ACCESS_PERMISSIONS');
			return false;
		}

		if(!$user->exists()){
			\Core\set_message('t:MESSAGE_ERROR_REQUESTED_RESOURCE_NOT_FOUND');
			return false;
		}

		$userisactive = $user->get('active');

		$user->setFromForm($form);

		if($userisactive == 1 && $user->get('active') == 0){
			// User was set from active to inactive.
			// Instead of setting to a new account, set to deactivated.
			$user->set('active', '-1');
		}
		elseif($userisactive == -1 && $user->get('active') == 0){
			// User was deactivated before, reset back to that.
			// This is because the active form element is simply an on/off checkbox.
			$user->set('active', '-1');
		}

		$user->save();


		if($userisactive == 0 && $user->get('active') == 1){
			// If the user wasn't active before, but is now....
			// Send an activation notice email to the user.
			try{
				$email = new \Email();
				$email->templatename = 'emails/user/activation.tpl';
				$email->assign('user', $user);
				$email->assign('sitename', SITENAME);
				$email->assign('rooturl', ROOT_URL);
				$email->assign('loginurl', \Core\resolve_link('/user/login'));
				$email->setSubject('Welcome to ' . SITENAME);
				$email->to($user->get('email'));

				// TESTING
				//error_log($email->renderBody());
				$email->send();
			}
			catch(\Exception $e){
				\Core\ErrorManagement\exception_handler($e);
			}
		}


		// If this was the current user, update the session data too!
		if($user->get('id') == \core\user()->get('id')){
			Session::SetUser($user);

			if(\ConfigHandler::Get('/user/profileedits/requireapproval') && \Core::IsComponentAvailable('model-audit')){
				\Core\set_message('t:MESSAGE_SUCCESS_UPDATED_OWN_USER_ACCOUNT_PENDING_APPROVAL');
			}
			else{
				\Core\set_message('t:MESSAGE_SUCCESS_UPDATED_OWN_USER_ACCOUNT');
			}
		}
		else{
			\Core\set_message('t:MESSAGE_SUCCESS_UPDATED_USER_ACCOUNT');
		}


		return true;
	}
 public static function _SaveHandler(Form $form)
 {
     // Save the model
     $m = $form->getModel();
     $m->save();
     // Save the widget too
     $widget = $m->getLink('Widget');
     $widget->set('title', $m->get('name'));
     $widget->set('editurl', '/navigation/edit/' . $m->get('id'));
     $widget->set('deleteurl', '/navigation/delete/' . $m->get('id'));
     $widget->save();
     // Save all the entries
     $counter = 0;
     if (!isset($_POST['entries'])) {
         $_POST['entries'] = array();
     }
     foreach ($_POST['entries'] as $id => $dat) {
         // New entries get an incremented counter and a new model.
         if (strpos($id, 'new') !== false) {
             ++$counter;
             $entry = new NavigationEntryModel();
         } elseif (strpos($id, 'del-') !== false) {
             $entry = new NavigationEntryModel(substr($id, 4));
             $entry->delete();
             continue;
         } else {
             ++$counter;
             $entry = new NavigationEntryModel($id);
         }
         // Set the weight, based on the counter...
         $entry->set('weight', $counter);
         // Make sure it links up to the right navigation...
         $entry->set('navigationid', $m->get('id'));
         // Set the correct parent...
         $entry->set('parentid', $dat['parent']);
         // And the data from the regular form...
         $entry->set('type', $dat['type']);
         $entry->set('baseurl', $dat['url']);
         $entry->set('title', $dat['title']);
         $entry->set('target', $dat['target']);
         $entry->save();
         // I need to update the link of any other element with this as the parent.
         if (strpos($id, 'new') !== false) {
             foreach ($_POST['entries'] as $sk => $sdat) {
                 if ($sdat['parent'] == $id) {
                     $_POST['entries'][$sk]['parent'] = $entry->get('id');
                 }
             }
         }
     }
     \Core\set_message('Updated/Created navigation successfully!', 'success');
     return '/widget/admin';
 }
	/**
	 * The main configuration for any user option on the site.
	 *
	 * Displayed under the "Configure" menu.
	 *
	 * @return int
	 */
	public function admin() {
		$view    = $this->getView();
		$request = $this->getPageRequest();

		// This is a super-admin-only page!
		if(!\Core\user()->checkAccess('g:admin')){
			return View::ERROR_ACCESSDENIED;
		}
		
		$userConfigs = [];
		$userSchema = UserModel::GetSchema();
		foreach($userSchema as $k => $dat){
			if(
				$dat['type'] == Model::ATT_TYPE_UUID ||
				$dat['type'] == Model::ATT_TYPE_UUID_FK ||
				$dat['type'] == Model::ATT_TYPE_ID ||
				$dat['type'] == Model::ATT_TYPE_ID_FK ||
				(isset($dat['formtype']) && $dat['formtype'] == 'disabled') ||
				(isset($dat['form']) && isset($dat['form']['type']) && $dat['form']['type'] == 'disabled')
			){
				// Skip these columns.
				continue;
			}
			
			$title = t('STRING_MODEL_USERMODEL_' . strtoupper($k));
			
			$userConfigs[$k] = $title;
		}
		
		// Pull a list of options currently enabled for both registration and edit.
		$onReg = [];
		$onEdits = [];
		
		$curReg = explode('|', ConfigHandler::Get('/user/register/form_elements'));
		$curEdits = explode('|', ConfigHandler::Get('/user/edit/form_elements'));
		
		foreach($curReg as $k){
			if(isset($userConfigs[$k])){
				// It's a valid key in the current application!
				$onReg[] = [
					'key' => $k,
					'checked' => true,
					'title' => $userConfigs[$k],
				];
			}
		}
		foreach($curEdits as $k){
			if(isset($userConfigs[$k])){
				// It's a valid key in the current application!
				$onEdits[] = [
					'key' => $k,
					'checked' => true,
					'title' => $userConfigs[$k],
				];
			}
		}
		
		foreach($userConfigs as $k => $title) {
			// If any key isn't in either curReg and curEdit, tack it to the end of the respective array.
			if(!in_array($k, $curReg)) {
				$onReg[] = [
					'key'     => $k,
					'checked' => false,
					'title'   => $title,
				];
			}
			if(!in_array($k, $curEdits)) {
				$onEdits[] = [
					'key'     => $k,
					'checked' => false,
					'title'   => $title,
				];
			}
		}

		// Build a form to handle the config options themselves.
		// These will include password strength, whether or not captcha is enabled, etc.
		$configs = [
			'/user/displayas', '/user/displayname/anonymous', '/user/email/allowchanging', '/user/enableavatar',
			'/user/password/minlength',
			'/user/password/requirecapitals', '/user/password/requiresymbols', '/user/password/requirenumbers',
			'/user/profileedits/requireapproval',
			'/user/register/allowpublic', '/user/register/requireapproval', '/user/register/requirecaptcha',
		];
		$configform = new Form();

		foreach($configs as $key){
			$el = ConfigHandler::GetConfig($key)->getAsFormElement();
			// I don't need this, (Everything from this group will be on the root-level form).
			$el->set('group', null);
			$configform->addElement($el);
		}

		$authbackends = ConfigHandler::Get('/user/authdrivers');
		if(!$authbackends){
			$authbackendsenabled = [];
		}
		else{
			$authbackendsenabled = explode('|', $authbackends);
		}

		$authbackends = [];
		$available = [];
		foreach(Core::GetComponents() as $c){
			/** @var Component_2_1 $c */
			$available = array_merge($available, $c->getUserAuthDrivers());
		}

		foreach($authbackendsenabled as $k){
			if(!isset($available[$k])){
				continue;
			}

			$classname = $available[$k];

			if(!class_exists($classname)){
				continue;
			}
			try{
				/** @var \Core\User\AuthDriverInterface $class */
				$class = new $classname();
			}
			catch(Exception $e){
				continue;
			}

			$authbackends[] = [
				'name' => $k,
				'class' => $classname,
				'title' => $class->getAuthTitle(),
				'enabled' => true,
			];

			unset($available[$k]);
		}


		foreach($available as $k => $classname){
			if(!class_exists($classname)){
				continue;
			}

			try{
				/** @var \Core\User\AuthDriverInterface $class */
				$class = new $classname();
			}
			catch(Exception $e){
				continue;
			}

			$authbackends[] = [
				'name' => $k,
				'class' => $classname,
				'title' => $class->getAuthTitle(),
				'enabled' => false,
			];
		}


		if($request->isPost()){
			$onEditSelected = (isset($_POST['onedit'])) ? implode('|', $_POST['onedit']) : '';
			$onRegSelected  = (isset($_POST['onregister'])) ? implode('|', $_POST['onregister']) : '';
			$authSelected   = (isset($_POST['authbackend'])) ? implode('|', $_POST['authbackend']) : '';

			if($authSelected == ''){
				\Core\set_message('At least one auth backend is required, re-enabling datastore.', 'info');
				$authSelected = 'datastore';
			}
			
			ConfigHandler::Set('/user/register/form_elements', $onRegSelected);
			ConfigHandler::Set('/user/edit/form_elements', $onEditSelected);
			ConfigHandler::Set('/user/authdrivers', $authSelected);

			// Handle the actual config options too!
			foreach($configs as $key){
				ConfigHandler::Set($key, $_POST['config'][$key]);
			}

			\Core\set_message('Saved configuration options successfully', 'success');
			\Core\reload();
		}

		$view->mastertemplate = 'admin';
		$view->title = 'User Options';
		$view->assign('configform', $configform);
		$view->assign('auth_backends', $authbackends);
		$view->assign('on_register_elements', $onReg);
		$view->assign('on_edit_elements', $onEdits);
	}
 /**
  * Main view for the navigator.
  *
  * Handle both list and thumbnail views.
  *
  * @return int
  */
 public function image()
 {
     $view = $this->getView();
     $request = $this->getPageRequest();
     $navigator = new \MediaManager\Navigator();
     $navigator->setView($view);
     $navigator->setMode($request->getParameter('mode'));
     $navigator->setAccept('image');
     if ($request->getParameter('ajax')) {
         $navigator->setBaseURL('/mediamanagernavigator/image?ajax=1');
         $view->mastertemplate = false;
         $view->record = false;
         $view->mode = View::MODE_AJAX;
     } elseif ($request->getParameter('iframe')) {
         $navigator->setBaseURL('/mediamanagernavigator/image?iframe=1');
         $view->mastertemplate = 'blank.tpl';
         $view->record = false;
     } else {
         $navigator->setBaseURL('/mediamanagernavigator/image');
         $view->mastertemplate = 'admin';
         //$view->mode = View::MODE_PAGE;
     }
     try {
         $navigator->cd($request->getParameter('dir'));
         if ($request->getParameter('controls') !== null) {
             $navigator->usecontrols = $request->getParameter('controls') == 1;
         }
         if ($request->getParameter('uploader') !== null) {
             $navigator->useuploader = $request->getParameter('uploader') == 1;
         }
     } catch (Exception $e) {
         \Core\set_message($e->getMessage(), 'error');
     }
     $view->title = 'Images';
     $navigator->render();
     //var_dump($navigator, $navigator->render()); die();
 }
	/**
	 * This is the form handler for a password protected page.
	 *
	 * @return bool
	 */
	public static function PasswordProtectHandler(Form $form){
		/** @var PageModel $page */
		$page = $form->getElementValue('page');
		$val  = $form->getElementValue('passinput');
		if( $val !== $page->get('password_protected') ){
			\Core\set_message('t:MESSAGE_ERROR_INCORRECT_PASSWORD');
			return false;
		}
		else {
			\Core\Session::Set('page-password-protected/' . $page->get('baseurl'), $val);
			return true;
		}


	}
Exemple #17
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);
		}
	}
	/**
	 * Controller view to update any instance-specific options for a given template.
	 *
	 * Usually consists of just access permissions and display template, but more options could come in the future.
	 */
	public function instance_movedown(){
		$view = $this->getView();
		$request = $this->getPageRequest();

		if(!\Core\user()->checkAccess('p:/core/widgets/manage')){
			return View::ERROR_ACCESSDENIED;
		}

		$instance = WidgetInstanceModel::Construct($request->getParameter(0));
		if(!$instance->exists()){
			return View::ERROR_NOTFOUND;
		}

		if(!$request->isPost()){
			return View::ERROR_BADREQUEST;
		}

		// Figure out which instance is this one -1.
		$otherCriteria = [
			'site = ' . $instance->get('site'),
			'template = ' . ($instance->get('template') === null ? 'NULL' : $instance->get('template')),
			'page_baseurl = ' . ($instance->get('page_baseurl') === null ? 'NULL' : $instance->get('page_baseurl')),
			'widgetarea = ' . $instance->get('widgetarea'),
			'weight = ' . ($instance->get('weight') + 1),
		];
		$other = WidgetInstanceModel::Find($otherCriteria, 1);

		if(!$other){
			\Core\set_message('Widget is already in the bottom position!', 'error');
		}
		else{
			$other->set('weight', $other->get('weight') - 1);
			$instance->set('weight', $instance->get('weight') + 1);

			$other->save();
			$instance->save();
		}

		\Core\go_back();
	}
 public static function ConfigureSave(Form $form)
 {
     foreach ($form->getElements() as $el) {
         /** @var $el FormElement */
         $n = $el->get('name');
         // I only want config options here.
         if (strpos($n, 'config[') !== 0) {
             continue;
         }
         // Trim off the "config[]" wrapper.
         $k = substr($n, 7, -1);
         ConfigHandler::Set($k, $el->get('value'));
     }
     \Core\set_message('Saved configuration options', 'success');
     return true;
 }
 /**
  * @param Form $form
  * @return false|string
  */
 public static function SaveBlacklistIp(Form $form)
 {
     try {
         $ban = $form->getModel('model');
         // First thing... check and make sure that this directive won't block out the current user!
         $longip = ip2long(REMOTE_IP);
         for ($i = 32; $i > 0; $i--) {
             $mask = ~((1 << 32 - $i) - 1);
             $join = long2ip($longip & $mask) . '/' . $i;
             if ($join == $ban->get('ip_addr')) {
                 \Core\set_message('Corwardly refusing to ban an IP range that will blacklist your current connection!', 'error');
                 return false;
             }
         }
         // The expires value will probably come in as a date string :/
         if ($ban->get('expires')) {
             $date = new CoreDateTime($ban->get('expires'));
             $ban->set('expires', $date->getFormatted('U', Time::TIMEZONE_GMT));
         }
         $ban->save();
         \Core\set_message('Banned IP range ' . $ban->get('ip_addr'), 'success');
         return 'back';
     } catch (Exception $e) {
         \Core\set_message($e->getMessage());
         return false;
     }
 }
	public static function _UploadHandler(Form $form) {
		$localfile = \Core\Filestore\Factory::File($form->getElement('upload')->get('value'));
		$localobj = $localfile->getContentsObject();
		if(!$localobj instanceof Core\Filestore\Contents\ContentTGZ){
			$localfile->delete();
			\Core\set_message('Invalid file uploaded', 'error');
			return false;
		}
		
		$tmpdir = $localobj->extract('tmp/installer-' . Core::RandomHex(4));
		
		// There should now be a package.xml metafile inside that temporary directory.
		// Parse it to get the necessary information for this package.
		$metafile = \Core\Filestore\Factory::File($tmpdir->getPath() . 'package.xml');
		if(!$metafile->exists()){
			$localfile->delete();
			$tmpdir->delete();
			\Core\set_message('Invalid package, package does not contain a "package.xml" file.');
			return false;
		}
		
		$pkg     = new PackageXML($metafile->getFilename());
		$key     = str_replace(' ', '-', strtolower($pkg->getName()));
		$name    = $pkg->getName();
		$type    = $pkg->getType();
		$version = $pkg->getVersion();
		
		// Validate the contents of the package.
		if(!(
			$type == 'component' ||
			$type == 'theme' ||
			$type == 'core'
		)){
			$localfile->delete();
			$tmpdir->delete();
			\Core\set_message('Invalid package, package does not appear to be a valid Core package.');
			return false;
		}

		// Now that the data is extracted in a temporary directory, extract every file in the destination.
		/** @var $datadir \Core\Filestore\Directory */
		$datadir = $tmpdir->get('data/');
		if(!$datadir){
			\Core\set_message('Invalid package, package does not contain a "data" directory.');
			return false;
		}
		
		if($type == 'component'){
			$destdir = ROOT_PDIR . 'components/' . $key . '/';
		}
		elseif($type == 'theme'){
			$destdir = ROOT_PDIR . 'themes/' . $key . '/';
		}
		else{
			$destdir = ROOT_PDIR . '/';
		}

		try{
			// Will give me an array of Files in the data directory.
			$files = $datadir->ls(null, true);
			// Used to get the relative path for each contained file.
			$datalen = strlen($datadir->getPath());
			foreach($files as $file){
				if(!$file instanceof \Core\Filestore\Backends\FileLocal) continue;

				// It's a file, copy it over.
				// To do so, resolve the directory path inside the temp data dir.
				$dest = \Core\Filestore\Factory::File($destdir . substr($file->getFilename(), $datalen));
				/** @var $dest \Core\Filestore\Backends\FileLocal */
				$dest->copyFrom($file, true);
			}
		}
		catch(Exception $e){
			// OH NOES!
			$localfile->delete();
			$tmpdir->delete();
			\Core\set_message($e->getMessage(), 'error');
			return false;
		}
		
		
		// Cleanup everything
		$localfile->delete();
		$tmpdir->delete();

		// Clear the cache so the next pageload will pick up on the new components and goodies.
		\Core\Cache::Flush();
		\Core\Templates\Backends\Smarty::FlushCache();
		
		// Print a nice message to the user that it completed.
		\Core\set_message('Successfully installed ' . $name . ' ' . $version, 'success');
		return '/updater';
	}
 /**
  * Save new and existing listings.
  *
  * @static
  *
  * @param Form $form
  *
  * @return mixed
  */
 public static function _SaveHandler(Form $form)
 {
     $model = $form->getModel('page');
     $exists = $model->exists();
     $model->save();
     \Core\set_message('t:MESSAGE_SUCCESS_' . ($exists ? 'UPDATED_MARKDOWNBROWSER_PAGE' : 'REGISTERED_MARKDOWNBROWSER_PAGE'));
     // w00t
     return $model->getResolvedURL();
 }
	public static function _i18nSaveHandler(Form $form) {
		
		// NEW IDEA!
		// Instead of setting the override for keys, (possibly useful, just somewhere else)...
		// Set the enabled languages for this site.
		// This allows site administrators to NOT have every language under the sun appear if they're running SuSE.
		$selected = $form->getElement('languages[]')->get('value');
		
		// Implode them into a single string.
		$enabled = implode('|', $selected);
		// Strip out any invalid character.
		$enabled = preg_replace('/[^a-zA-Z_|]/', '', $enabled);
		
		// And save!
		ConfigHandler::Set('/core/language/languages_enabled', $enabled);
		return true;
		
		// Create a custom ini for just these options.
		// This will allow the site admin to change a string without worrying about it getting overridden from an update.

		$lang = $form->getElementValue('lang');
		$ini = "[$lang]\n; Custom locale strings set by the site manager!\n\n";

		foreach($form->getElements() as $el){
			/** @var FormElement $el */

			$name = $el->get('name');
			$val  = $el->get('value');

			if(strpos($name, 'MESSAGE') === 0 || strpos($name, 'FORMAT') === 0 || strpos($name, 'STRING') === 0){
				$ini .= $name . ' = "' . str_replace('"', '\\"', $val) . '";' . "\n";
			}
		}

		// Save this ini out to a custom i18n file.
		$fileout = \Core\Filestore\Factory::File(ROOT_PDIR . 'themes/custom/i18n/' . $lang . '.ini');
		$fileout->putContents($ini);

		\Core\set_message('t:MESSAGE_SUCCESS_UPDATED_TRANSLATION_STRINGS');
		return true;
	}
 public function delete()
 {
     $view = $this->getView();
     $request = $this->getPageRequest();
     // This is a POST-only page.
     if (!$request->isPost()) {
         return View::ERROR_BADREQUEST;
     }
     if (!$this->setAccess('p:/content/manage_all')) {
         return View::ERROR_ACCESSDENIED;
     }
     $m = new ContentModel($request->getParameter(0));
     $link = \Core\resolve_link($m->get('baseurl'));
     if (!$m->exists()) {
         return View::ERROR_NOTFOUND;
     }
     $m->delete();
     \Core\set_message('Removed ' . $m->get('nickname') . ' successfully!', 'success');
     $hist = $request->getReferrer();
     if ($hist == $link) {
         \Core\redirect('/admin/pages');
     } else {
         \Core\go_back();
     }
 }
	/**
	 * Page to test the UI of form elements.
	 *
	 * This will generate a form with every registered form element.
	 */
	public function testui(){
		$view = $this->getView();
		$request = $this->getPageRequest();

		if(!\Core\user()->checkAccess('g:admin')){
			// This test page is an admin-only utility.
			return View::ERROR_ACCESSDENIED;
		}

		$form = new Form();

		// What type of orientation do you want to see?
		$orientation = $request->getParameter('orientation');
		if(!$orientation){
			$orientation = 'horizontal';
		}
		$required = ($request->getParameter('required'));
		$error    = ($request->getParameter('error'));


		$form->set('orientation', $orientation);

		$mappings = Form::$Mappings;
		// Make them alphabetical.
		ksort($mappings);

		foreach($mappings as $k => $v){
			try{
				$atts = [
					'name' => $k,
					'title' => $v,
					'description' => 'This form element is a ' . $v . ', registered to the key ' . $k . '.',
				];

				if($required) $atts['required'] = true;

				// Some form elements have particular requirements.
				switch($v){
					case 'FormFileInput':
					case 'MultiFileInput':
						$atts['basedir'] = 'tmp/form/testui';
						break;
					case 'FormPagePageSelectInput':
						$atts['templatename'] = 'foo';
						break;
					case 'FormPageInsertables':
						$atts['baseurl'] = '/';
						break;
					case 'FormPageMeta':
						$atts['name'] = 'test';
						break;
					case 'FormCheckboxesInput':
					case 'FormRadioInput':
						$atts['options'] = ['key1' => 'Key 1', 'key2' => 'Key 2'];
						break;
				}
				$el = FormElement::Factory($k, $atts);

				if($error && $el instanceof FormElement){
					$el->setError('Something bad happened', false);
				}
				$form->addElement( $el );
			}
			catch(Exception $e){
				\Core\set_message('Form element ' . $v . ' failed to load due to ' . $e->getMessage(), 'error');
			}
		}

		$view->title = 'Test Form Element UI/UX';
		$view->assign('form', $form);
		$view->assign('orientation', $orientation);
		$view->assign('required', $required);
		$view->assign('error', $error);
	}
Exemple #26
0
	static public function AddMessage($messageText, $messageType = 'info') {
		\Core\set_message($messageText, $messageType);
	}
	/**
	 * Set a JSON error message and optionally redirect if the page is not an ajax request.
	 *
	 * @param $code
	 * @param $message
	 * @param $redirect
	 *
	 * @return int
	 */
	public function sendJSONError($code, $message, $redirect){
		$view    = $this->getView();
		$request = $this->getPageRequest();

		if($request->isAjax()){
			$view->mode = View::MODE_PAGEORAJAX;
			$view->jsondata = ['status' => $code, 'message' => $message];
			$view->error = $code;
		}
		else{
			\Core\set_message($message, 'error');
			if($redirect){
				\Core\redirect($redirect);
			}
			else{
				\Core\go_back();
			}
		}
	}
Exemple #28
0
 public static function Include_cookie()
 {
     if (Core::IsLibraryAvailable('js.cookie')) {
         // No longer maintained, superseded by JS Cookie
         if (DEVELOPMENT_MODE) {
             \Core\set_message('Please use js.cookie instead, as jquery.cookie is no longer maintained!');
         }
         //return \JSCookie\JSCookie::IncludeJS();
     }
     // I need jquery first.
     self::IncludeJQuery();
     \Core\view()->addScript('js/jquery/jquery.cookie.js');
     // IMPORTANT!  Tells the script that the include succeeded!
     return true;
 }