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); }
/** * Get a valid \DateTimeZone from its name. Useful for caching timezone objects. * * @param string|null|\DateTimeZone $timezone * * @return \DateTimeZone */ public static function GetTimezone($timezone) { static $timezones = array(); if($timezone instanceof \DateTimeZone){ // No conversion required! return $timezone; } elseif ($timezone == Timezone::TIMEZONE_USER) { // Convert this to the user's timezone. $timezone = \Core\user()->get('timezone'); // Users must have valid timezone strings too! if($timezone === null){ $timezone = date_default_timezone_get(); } elseif(is_numeric($timezone)){ $timezone = date_default_timezone_get(); } } elseif($timezone === Timezone::TIMEZONE_GMT || $timezone === 'GMT' || $timezone === null){ $timezone = 'UTC'; } elseif($timezone == Timezone::TIMEZONE_DEFAULT){ $timezone = date_default_timezone_get(); } if (!isset($timezones[$timezone])) { $timezones[$timezone] = new \DateTimeZone($timezone); } return $timezones[$timezone]; }
public function set($k, $v) { switch ($k) { case 'file': $ret = parent::set($k, $v); // Clear out the cache $this->_file = null; // File was updated... load the exif data too! // Note, only do this if it was an image! $file = $this->getOriginalFile(); if ($file->isImage() && $file->getExtension() == 'jpg') { $this->_data['exifdata'] = json_encode(exif_read_data($file->getFilename())); } else { $this->_data['exifdata'] = null; } // Also if the file is new and it didn't exist... set the uploader id. if (!$this->_exists) { $this->_data['uploaderid'] = \Core\user()->get('id'); } return $ret; case 'exifdata': // exif data cannot be changed externally! return false; default: return parent::set($k, $v); } }
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/ }
/** * A block to only render the inside content if the access string passes. * * #### Smarty Parameters * * The only parameter required is the one access string, (wrapped in quotes), to check for. * This parameter does not require any key prefix. * * #### Example Usage * * Have a paragraph only visible to super admins. * * <pre> * {access "g:admin"} * <p>This snippet is only visible to administrators.</p> * {/access} * </pre> * * Have a paragraph only visible to the user groups "group1" or "group2". * * <pre> * {access 'g:group1;g:group2'} * <p>While this snippet is visible to everyone except admins.</p> * {/access} * </pre> * * Have a paragraph only visible to users who are in user groups that have the "/something/blah" permission. * * <pre> * {access 'p:/something/blah'} * <p>Content only for people with the /something/blah permission.</p> * {/access} * </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_access($params, $content, $smarty, &$repeat){ // This only needs to be called once. if($repeat) return ''; $str = $params[0]; $result = \Core\user()->checkAccess($str); return $result ? $content : null; }
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!'); }
public function admin() { $view = $this->getView(); $request = $this->getPageRequest(); if (!\Core\user()->checkAccess('g:admin')) { return View::ERROR_ACCESSDENIED; } $image = ConfigHandler::Get('/favicon/image'); $form = new Form(); $form->set('callsmethod', 'AdminController::_ConfigSubmit'); $form->addElement(ConfigHandler::GetConfig('/favicon/image')->getAsFormElement()); $form->addElement('submit', ['value' => t('STRING_SAVE')]); $view->title = 'Site Favicon'; $view->assign('current', $image); $view->assign('form', $form); }
/** * Get a valid DateTimeZone from the intiger of it. * * Note, these will all be the generic GMT-5 timezones. * * @param string $timezone * * @return DateTimeZone */ private function _getTimezone($timezone) { if ($timezone == Time::TIMEZONE_USER) { // Convert this to the user's timezone. $timezone = \Core\user()->get('timezone'); if($timezone === null) $timezone = date_default_timezone_get(); // Users must have valid timezone strings too! if (is_numeric($timezone)) $timezone = Time::TIMEZONE_DEFAULT; } if (!isset($this->timezones[$timezone])) { $this->timezones[$timezone] = new DateTimeZone($timezone); } return $this->timezones[$timezone]; }
/** * Widget to display some of the newest registrations, (if any). */ public function newestSignups(){ if(!\Core\user()->checkAccess('p:/user/users/manage')){ return ''; } // How far back do I want to search for? // 1 month sounds good! $date = new CoreDateTime(); $date->modify('-1 month'); $searches = UserModel::Find(['created > ' . $date->getFormatted('U')], 10, 'created DESC'); // No results? No problem :) if(!sizeof($searches)) return ''; $view = $this->getView(); $view->assign('enableavatar', (\ConfigHandler::Get('/user/enableavatar'))); $view->assign('users', $searches); }
public function register() { $view = $this->getView(); $user = \Core\user(); // Set the access permissions for this page as anonymous-only. if(!$user->checkAccess('g:anonymous;g:!admin')){ return ''; } // Also disallow access to this page if the configuration option is disabled. if(!ConfigHandler::Get('/user/register/allowpublic')){ return ''; } $auths = \Core\User\Helper::GetEnabledAuthDrivers(); $view->assign('drivers', $auths); }
/** * Widget to quickly create a new Content page as a draft. */ public function quickdraft() { $view = $this->getView(); if (!\Core\user()->checkAccess('p:/content/manage_all')) { // Users who do not have access to manage page content do not get this. return ''; } $form = new Form(); $form->set('orientation', 'vertical'); $form->set('callsmethod', 'ContentAdminWidget::QuickDraftSave'); $form->addElement('text', ['name' => 'title', 'placeholder' => 'Page or Post Title']); $form->addElement('textarea', ['name' => 'content', 'placeholder' => "What's up?", 'cols' => 50]); $form->addElement('submit', ['value' => 'Save Draft']); // Load in all the pages on the site that are currently set as draft too, why not? ;) $drafts = PageModel::Find(['published_status = draft'], 10, 'updated DESC'); $view->assign('form', $form); $view->assign('drafts', $drafts); }
public function __construct() { $admin = \Core\user()->checkAccess('g:admin'); $this->canupload = $admin || \Core\user()->checkAccess('p:/mediamanager/upload'); $this->canaccess = $this->canupload || \Core\user()->checkAccess('p:/mediamanager/browse'); switch (\ConfigHandler::Get('/mediamanager/sandbox')) { case 'user-sandboxed': $this->_basedir = 'public/media/' . \Core\user()->get('id') . '/'; break; case 'shared-user-sandbox': $this->_basedir = 'public/media/'; break; case 'completely-open': $this->_basedir = 'public/'; break; default: $this->_basedir = 'public/media/'; break; } }
/** * View a user's public profile */ public function view() { $view = $this->getView(); $request = $this->getPageRequest(); $manager = \Core\user()->checkAccess('p:/user/users/manage'); // Current user an admin? // First argument here will either be the username or user id. $arg1 = $request->getParameter(0); $user = UserModel::Construct($arg1); if (!($user && $user->exists())) { // Try by username instead. $match = UserUserConfigModel::Find(array('key' => 'username', 'value' => $arg1), 1); if (!$match) { return View::ERROR_NOTFOUND; } $user = UserModel::Construct($match->get('user_id')); } if (!$user) { return View::ERROR_NOTFOUND; } // If the UA requested the user by ID but the user has a username set, return a 404 as well. // This should help cut down on scanning attempts for userdata. if (is_numeric($arg1) && $user->get('username')) { return View::ERROR_NOTFOUND; } // Now see why username needs to not begin with a number? :p /** @var $user UserModel */ // Only allow this if the user is either the same user or has the user manage permission. if ($user->get('id') == \Core\user()->get('id') || $manager) { $editor = true; } else { $editor = false; } $view->controls = ViewControls::DispatchModel($user); $view->title = $user->getDisplayName(); $view->assign('user', $user); $view->assign('profiles', $user->get('external_profiles')); }
/** * 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); }
/** * The view for the admin dashboard. Gets the last executed crons and displays that to the admin. */ public function dashboard() { // This dashboard has no effect if the user can't view crons. if (!\Core\user()->checkAccess('p:/cron/viewlog')) { return ''; } $view = $this->getView(); // Get the latest cron and its execution information and display that to the dashboard. $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']]; $crons = array(); foreach ($checks as $k => $check) { $time = new CoreDateTime(); $cronfac = new ModelFactory('CronLogModel'); $cronfac->limit(1); $cronfac->where('cron = ' . $check['cron']); $cronfac->order('created desc'); $c = $cronfac->get(); if ($c) { $crons[] = $c; } } $view->title = 't:STRING_LATEST_CRON_RESULTS'; $view->assign('crons', $crons); }
public function edit() { $view = $this->getView(); $request = $this->getPageRequest(); $model = new ContentModel($request->getParameter(0)); if (!$model->exists()) { return View::ERROR_NOTFOUND; } $editor = \Core\user()->checkAccess($model->get('editpermissions')) || \Core\user()->checkAccess('p:/content/manage_all'); $manager = \Core\user()->checkAccess('p:/content/manage_all'); if (!($editor || $manager)) { return View::ERROR_ACCESSDENIED; } $page = $model->getLink('Page'); $form = new Form(); $form->set('callsmethod', 'ContentController::_SaveHandler'); $form->addModel($page, 'page'); $form->addModel($model, 'model'); // Tack on a submit button $form->addElement('submit', array('value' => 'Update')); // Editors have certain permissions here, namely limited. if ($editor && !$manager) { $form->removeElement('model[nickname]'); $form->removeElement('model[editpermissions]'); $form->removeElement('page[rewriteurl]'); $form->removeElement('page[parenturl]'); } $view->mastertemplate = 'admin'; $view->templatename = '/pages/content/edit.tpl'; $view->title = 'Edit ' . $model->get('title'); $view->assignVariable('model', $model); $view->assignVariable('form', $form); //if ($manager) $view->addControl('Add Page', '/content/create', 'add'); $view->addControl('View Page', '/content/view/' . $model->get('id'), 'view'); //if ($manager) $view->addControl('Delete Page', '/content/delete/' . $model->get('id'), 'delete'); }
/** * Called from the /user/postsave hook with the one argument of the UserModel. * * @param \UserModel $user * @return bool */ public static function ForceSessionSync(\UserModel $user){ // BEFORE I do this, cleanup any old sessions! Session::CleanupExpired(); $me = (\Core\user() && \Core\user()->get('id') == $user->get('id')); foreach(\SessionModel::Find(['user_id = ' . $user->get('id')]) as $sess){ /** @var \SessionModel $sess */ if($me && $sess->get('session_id') == session_id()){ // It's this current session! // Reload this user object :) // Remember, the external data cannot be set from within the same session! Session::SetUser($user); continue; } $dat = $sess->getExternalData(); $dat['user_forcesync'] = true; $sess->setExternalData($dat); $sess->save(); } return true; }
/** * Set the access string for this view and do the access checks against the * currently logged in user. * * Will also set the access string on the PageModel, since it needs to be reflected in the database. * * @since 2012.01 * @version 2.1 * * @param string $accessstring * * @return boolean True or false based on access for current user. */ protected function setAccess($accessstring) { // Update the model $this->getPageModel()->set('access', $accessstring); return (\Core\user()->checkAccess($accessstring)); }
/** * Interface to "train" the system to learn spam keywords. * * A block of content can be submitted to this page, where the user has the options to score phrases and words. */ public function spam_train() { $view = $this->getView(); $request = $this->getPageRequest(); if (!\Core\user()->checkAccess('g:admin')) { return View::ERROR_ACCESSDENIED; } $view->title = 'Spam Training'; $view->mastertemplate = 'admin'; if ($request->isPost() && $request->getPost('keywords')) { foreach ($_POST['keywords'] as $w => $s) { if ($s == 0) { // Populating the database with a bunch of neutral scores is pointless. continue; } $k = SpamHamKeywordModel::Construct($w); $k->set('score', $s); $k->save(); } \Core\set_message('Trained keywords successfully!', 'success'); \Core\redirect('/security/spam/keywords'); } elseif (!$request->isPost() || !$request->getPost('content')) { // Step 1 for training with content, provide a text area to submit content! $view->templatename = 'pages/security/spam_train_1.tpl'; $form = new Form(); $form->addElement('textarea', ['name' => 'content', 'value' => '', 'title' => t('STRING_CONTENT'), 'description' => 'Paste in the content to parse for keywords. You will have the ability to fine-tune specific keywords on the next page.', 'rows' => 6]); $form->addElement('submit', ['value' => 'Next']); $view->assign('form', $form); } else { // Step 2, $view->templatename = 'pages/security/spam_train_2.tpl'; $check = new \SecuritySuite\SpamCan\SpamCheck($request->getPost('content')); $keywords = $check->getKeywords(); $form = new Form(); $form->set('orientation', 'grid'); foreach ($keywords as $dat) { if ($dat['score'] != 0) { // Skip keywords that are already weighted. continue; } if (preg_match_all('# #', $dat['keyword']) == 1) { // Skip keywords that only contain one space. // Here, we only want single words and 3-word phrases. continue; } $form->addElement('text', ['name' => 'keywords[' . $dat['keyword'] . ']', 'title' => $dat['keyword'], 'value' => 0]); } $form->addElement('submit', ['value' => 'Train!']); $view->assign('form', $form); } }
/** * Hook receiver for /core/controllinks/user/view * * @param int $userid * * @return array */ public static function GetUserControlLinks($userid){ $enabled = \Core\User\Helper::GetEnabledAuthDrivers(); if(!isset($enabled['datastore'])){ // GPG isn't enabled at all, disable any control links from the system. return []; } if($userid instanceof UserModel){ $user = $userid; } else{ /** @var UserModel $user */ $user = UserModel::Construct($userid); } if(!$user->exists()){ // Invalid user. return []; } $isself = (\Core\user()->get('id') == $user->get('id')); $isadmin = \Core\user()->checkAccess('p:/user/users/manage'); if(!($isself || $isadmin)){ // Current user does not have access to manage the provided user's data. return []; } try{ // If this throws an exception, then it's not enabled! $user->getAuthDriver('datastore'); } catch(Exception $e){ if($isself){ return [ [ 'link' => '/datastoreauth/forgotpassword', 'title' => t('STRING_ENABLE_PASSWORD_LOGIN'), 'icon' => 'key', ] ]; } } $ret = []; $ret[] = [ 'link' => '/datastoreauth/password/' . $user->get('id'), 'title' => t('STRING_CHANGE_PASSWORD'), 'icon' => 'key', ]; if(sizeof($user->getEnabledAuthDrivers()) > 1){ $ret[] = [ 'link' => '/datastoreauth/disable/' . $user->get('id'), 'title' => t('STRING_DISABLE_PASSWORD_LOGIN'), 'icon' => 'ban', 'confirm' => 'Are you sure you want to disable password-based logins? (They can be re-enabled if requested.)', ]; } return $ret; }
public function view(){ $v = $this->getView(); $pages = PageModel::Find(array('admin' => '1')); $groups = array(); $flatlist = array(); if(isset($_SESSION['user_sudo'])){ $p = new PageModel('/user/sudo'); $p->set('title', 'Exit SUDO Mode'); $groups['SUDO'] = [ 'title' => 'SUDO', 'href' => '', 'children' => [ 'Exit SUDO Mode' => $p, ], ]; $flatlist[ 'Exit SUDO Mode' ] = $p; } if(\Core\user()){ foreach($pages as $p){ /** @var PageModel $p */ if(!\Core\user()->checkAccess($p->get('access'))) continue; // Pages can define which sub-menu they get grouped under. // The 'Admin' submenu is the default. $group = $p->get('admin_group') ? $p->get('admin_group') : 't:STRING_ADMIN'; // Support i18n here! if(strpos($group, 't:') === 0){ $group = t(substr($group, 2)); } if(!isset($groups[$group])){ $groups[$group] = [ 'title' => $group, 'href' => '', 'children' => [], ]; } if($p->get('baseurl') == '/admin'){ // Admin gets special treatment. $groups[t('STRING_ADMIN')]['href'] = '/admin'; continue; } switch($p->get('title')){ case 'System Configuration': $p->set('title', "System Config"); break; case 'Navigation Listings': $p->set('title', "Navigation"); break; case 'Content Page Listings': $p->set('title', "Content Pages"); break; default: $p->set( 'title', trim( str_replace(['Administration', 'Admin'],'', $p->get('title')) ) ); } $title = $p->get('title'); // Support i18n here! if(strpos($title, 't:') === 0){ $title = t(substr($title, 2)); } if(isset($groups[$title])){ // Link the main group to this page instead of an empty link. // This removes duplicate links such as the group "User" and page "User". $groups[$title]['href'] = $p->get('rewriteurl'); } else{ // The new grouped pages $groups[$group]['children'][ $title ] = $p; // And the flattened list to support legacy templates. $flatlist[ $title ] = $p; } } // This is a hack to make sure that users can view the /admin link if they can view other admin pages. /*if(sizeof($flatlist) && !isset($groups['Admin']['Dashboard'])){ $p = new PageModel('/admin'); $p->set('title', 'Dashboard'); $groups['Admin']['Dashboard'] = $p; }*/ } ksort($flatlist); ksort($groups); foreach($groups as $gname => $dat){ ksort($groups[$gname]['children']); } // Build a list of languages that can be set by the user. $locales = \Core\i18n\I18NLoader::GetLocalesEnabled(); $selected = \Core\i18n\I18NLoader::GetUsersLanguage(); $languages = []; if(sizeof($locales) > 1){ // There is at least 1 language available on the system, YAY! foreach($locales as $localeKey => $localeDat){ if(($pos = strpos($localeKey, '_')) !== false){ // This locale contains an underscore, that means it has a corresponding country! // These are what we want to display to the end user. $country = substr($localeKey, $pos+1); // Here I am retrieving the language and dialect in the native dialect if at all possible. // This is because if you as a user only can read your native language and your browser renders something different, // then you want to be able to read what you're switching it to. $str1 = new \Core\i18n\I18NString($localeDat['lang']); $str1->setLanguage($localeKey); $localeTitle = $str1->getTranslation(); if($localeDat['dialect']){ $str2 = new \Core\i18n\I18NString($localeDat['dialect']); $str2->setLanguage($localeKey); $localeTitle .= ' (' . $str2->getTranslation() . ')'; } $languages[] = [ 'key' => $localeKey, 'title' => $localeTitle, 'country' => $country, 'image' => 'assets/images/iso-country-flags/' . strtolower($country) . '.png', 'selected' => $localeKey == $selected, ]; } } } $v->templatename = 'widgets/adminmenu/view.tpl'; $v->assign('pages', $flatlist); $v->assign('groups', $groups); $v->assign('languages', $languages); return $v; }
public function check(){ if( !\Core\user()->checkAccess('g:admin') ) return ''; }
/** * 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); }
public function edit() { $request = $this->getPageRequest(); $view = $this->getView(); $manager = \Core\user()->checkAccess('p:/package_repository/licenses/manager'); if (!$manager) { return View::ERROR_ACCESSDENIED; } $model = PackageRepositoryLicenseModel::Construct($request->getParameter(0)); if (!$model->exists()) { return View::ERROR_NOTFOUND; } $form = new Form(); $form->set('callsmethod', 'PackageRepositoryLicenseController::_SaveLicense'); $form->addModel($model); $form->addElement('submit', ['value' => 'Update License']); $view->title = 'Edit License'; $view->assign('form', $form); }
/** * Provide the admins with a general "howto" page for setting up cron jobs. * * This is linked to from the "your cron hasn't run recently" error. */ public function howto() { $view = $this->getView(); $request = $this->getPageRequest(); $view->mode = View::MODE_PAGEORAJAX; if (!\Core\user()->checkAccess('p:/cron/viewlog')) { return View::ERROR_ACCESSDENIED; } $view->mastertemplate = 'admin'; $view->title = 'Cron Howto'; $view->assign('url', ROOT_URL_NOSSL); $view->assign('sitename', SITENAME); }
public function analytics() { $request = $this->getPageRequest(); $view = $this->getView(); $manager = \Core\user()->checkAccess('p:/package_repository/view_analytics'); if (!$manager) { return View::ERROR_ACCESSDENIED; } // Retrieve a list of connections to this repo for both downloading and checks! $where = new \Core\Datamodel\DatasetWhereClause(); $where->addWhereSub('OR', ['baseurl = /packagerepository', 'baseurl = /packagerepository/download']); // Default to a 3-month window for now just to have a relatively useful sample of data. // This will be expanded to include a filter at some point in time. $window = new \Core\Date\DateTime(); $window->modify('-3 months'); $window = $window->format('U'); // Generate a boilerplate dataset for the all-history view. // This is required because the graphing software expects all data to be in the same columns, // and these columns are simply indexed arrays. // As we're pulling the data potentially out-of-order and across different versions, // this array will provide a consistent scaffold for unset versions. $allboilerplate = []; // Series Boilerplate $allmonths = []; // Labels // This goes back 12 months. $date = new \Core\Date\DateTime(); $date->modify('-11 months'); for ($i = 1; $i <= 12; $i++) { $allboilerplate[$date->format('Ym')] = null; $allmonths[] = $date->format('M'); $date->nextMonth(); } $raw = UserActivityModel::FindRaw($where); // Will contain a list of useragents along with the count of how many access. $useragents = []; // Will contain how many times a given IP has requested the site. // This is for a metric that currently is not enabled. $ipaddresses = []; // A rich list of hosts along with the latest version, the IP connecting from, and the date of the last check. $hosts = []; // All series for the bar graph at the top of the page, Keyed by version and contains the total number of hits. $allseries = []; $allseries['Total'] = ['class' => 'series-other', 'name' => 'Total', 'title' => 'Total', 'useragent' => '', 'values' => $allboilerplate]; // Used so I can compare the version of the connecting useragent against the current version of Core. // This of course does noothing to ensure that this site is updated, but it at least should give some perspective. $currentVersion = Core::VersionSplit(Core::GetComponent('core')->getVersion()); foreach ($raw as $dat) { if (strpos($dat['useragent'], '(http://corepl.us)') !== false) { /** @var string $ua ex: "Core Plus 1.2.3" */ $ua = str_replace(' (http://corepl.us)', '', $dat['useragent']); /** @var string $version Just the version, ex: "1.2.3" */ $version = str_replace('Core Plus ', '', $ua); /** @var string $referrer Original Site/Server, ex: "http://corepl.us" */ $referrer = $dat['referrer'] ? $dat['referrer'] : $dat['ip_addr']; // The set of logic to compare the current version of Core against the version connecting. // This is used primarily to set a class name onto the graphs so that they can be coloured specifically. $v = Core::VersionSplit($version); // These two values are used in the historical map, (as revision may be a bit useless at this scale). $briefVersion = $v['major'] . '.' . $v['minor'] . '.x'; $briefUA = 'Core Plus ' . $briefVersion; if ($v['major'] == $currentVersion['major'] && $v['minor'] == $currentVersion['minor']) { // Check is same version as current (or newer), blue! $class = 'series-current'; } elseif ($v['major'] + 2 <= $currentVersion['major']) { // Check is at least 2 major versions out of date, red. $class = 'series-outdated-2'; } elseif ($v['major'] + 1 <= $currentVersion['major']) { // Check is at least 1 major version out of date, green. $class = 'series-outdated-1'; } else { // Same major version, close enough. $class = 'series-outdated-0'; } $month = date('Ym', $dat['datetime']); } else { $ua = 'Other'; $briefUA = 'Other'; $version = null; $briefVersion = null; $referrer = null; $class = 'series-other'; $month = null; } // All Data! if ($month && array_key_exists($month, $allboilerplate)) { if (!isset($allseries[$briefUA])) { $allseries[$briefUA] = ['class' => $class, 'name' => $briefVersion, 'title' => $briefUA, 'useragent' => $briefUA, 'values' => $allboilerplate]; } $allseries[$briefUA]['values'][$month]++; //$allseries['Total']['values'][$month]++; } // Is this data new enough to display on the graph? // This is required because the "all" graph at the top needs all-time, (or at least the past 12 months). if ($dat['datetime'] >= $window) { // USER AGENT DATA if (!isset($useragents[$ua])) { $useragents[$ua] = ['value' => 0, 'class' => $class, 'name' => $version, 'title' => $ua, 'useragent' => $ua]; } $useragents[$ua]['value']++; // IP ADDRESS DATA if (!isset($ipaddresses[$dat['ip_addr']])) { $ipaddresses[$dat['ip_addr']] = ['ip_addr' => $dat['ip_addr'], 'count' => 0]; } $ipaddresses[$dat['ip_addr']]['count']++; // HOSTS DATA if ($version && $referrer) { $k = $referrer . '-' . $dat['ip_addr']; if (!isset($hosts[$k])) { $hosts[$k] = ['servername' => $referrer, 'ip_addr' => $dat['ip_addr'], 'version' => '0.0', 'datetime' => 1]; } if (Core::VersionCompare($hosts[$k]['version'], $version, 'lt')) { $hosts[$k]['version'] = $version; } if ($hosts[$k]['datetime'] < $dat['datetime']) { $hosts[$k]['datetime'] = $dat['datetime']; } } } } ksort($useragents); ksort($hosts, SORT_NATURAL); ksort($allseries, SORT_NATURAL); ksort($ipaddresses, SORT_NATURAL); // Update the title of the values now that the totals have been created. // Also, take this opportunity to set the chart data as necessary, (as its format will be slightly different). $chart = ['versions' => ['labels' => [], 'series' => []], 'all' => ['labels' => array_values($allmonths), 'series' => []], 'ips' => []]; foreach ($useragents as &$dat) { $dat['title'] .= ' (' . $dat['value'] . ' Total Hits)'; $chart['versions']['labels'][] = $dat['name']; $chart['versions']['series'][] = ['value' => $dat['value'], 'className' => $dat['class'], 'name' => $dat['name'], 'title' => $dat['title']]; } foreach ($allseries as &$dat) { $data = []; foreach ($dat['values'] as $v) { $data[] = ['value' => $v, 'title' => $dat['title'] . ' (' . $v . ' Monthly Hits)']; //$data[] = $v; } $chart['all']['series'][] = ['data' => $data, 'className' => $dat['class'], 'name' => $dat['name'], 'title' => $dat['title']]; } // Convert these to JSON data! $chart['versions'] = json_encode($chart['versions']); $chart['all'] = json_encode($chart['all']); //$chart['ips'] = json_encode($chart['ips']); $view->title = 't:STRING_PACKAGE_REPOSITORY_ANALYTICS'; $view->assign('chart', $chart); $view->assign('raw', $raw); $view->assign('ip_addresses', $ipaddresses); $view->assign('useragents', $useragents); $view->assign('hosts', $hosts); //var_dump($chart, $useragents, $ipaddresses, $ipversion, $raw); die(); }
private function _viewAlbum(GalleryAlbumModel $album) { $view = $this->getView(); $manager = \Core\user()->checkAccess('p:/gallery/manage_all'); $editor = \Core\user()->checkAccess($album->get('editpermissions')) || $manager; $uploader = \Core\user()->checkAccess($album->get('uploadpermissions')) || $editor; $url = $album->get('rewriteurl'); $images = $album->getLink('GalleryImage', 'weight'); $lastupdated = $album->get('updated'); if ($uploader) { $uploadform = new Form(); $uploadform->set('action', \Core\resolve_link('/gallery/images_update/' . $album->get('id'))); $uploadform->addElement('multifile', array('basedir' => $album->getFullUploadDirectory(), 'title' => 'Bulk Upload Files', 'name' => 'images', 'accept' => $album->get('accepttypes'))); $uploadform->addElement('submit', array('value' => 'Save Gallery Changes')); } else { $uploadform = false; } // I need to attach a friendly URL for each image. // This gets a little tricky since each image doesn't have a unique title necessarily. foreach ($images as $i) { // I would like to know when the last change overall was, not just for the gallery. $lastupdated = max($lastupdated, $i->get('updated')); } $view->templatename = '/pages/gallery/view.tpl'; $view->assign('album', $album); $view->assign('images', $images); $view->assign('editor', $editor); $view->assign('manager', $manager); $view->assign('uploader', $uploader); $view->assign('uploadform', $uploadform); $view->assign('userid', \Core\user()->get('id')); $view->updated = $lastupdated; // If there are images in this gallery, grab the first one to show as a preview! if (count($images)) { $view->meta['og:image'] = $images[0]->getFile()->getPreviewURL('200x200'); } if ($editor) { $view->addControl('Gallery Albums Administration', '/gallery/admin', 'directory'); $view->addControl('Edit Gallery Album', '/gallery/edit/' . $album->get('id'), 'edit'); } if ($uploader) { // If they can upload images, they can rearrange them! $view->addControl(array('title' => 'Rearrange Images', 'link' => '/gallery/order/' . $album->get('id'), 'icon' => 'move')); } }
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'; }
/** * Get a valid DateTimeZone from its name. Useful for caching timezone objects. * * @param string $timezone * * @return DateTimeZone */ private static function _GetTimezone($timezone) { static $timezones = array(); if ($timezone == Time::TIMEZONE_USER) { // Convert this to the user's timezone. $timezone = \Core\user()->get('timezone'); if($timezone === null) $timezone = date_default_timezone_get(); // Users must have valid timezone strings too! if (is_numeric($timezone)) $timezone = Time::TIMEZONE_DEFAULT; } if($timezone === Time::TIMEZONE_GMT || $timezone === 'GMT'){ $timezone = 'UTC'; } elseif($timezone == Time::TIMEZONE_DEFAULT){ $timezone = TIME_DEFAULT_TIMEZONE; } if (!isset($timezones[$timezone])) { $timezones[$timezone] = new DateTimeZone($timezone); } return $timezones[$timezone]; }