Ejemplo n.º 1
0
 /**
  * Save Email.Flag preference list in config for easier access.
  */
 public function userModel_beforeSaveSerialized_handler($Sender)
 {
     if (Gdn::session()->checkPermission('Plugins.Flagging.Notify')) {
         if ($Sender->EventArguments['Column'] == 'Preferences' && is_array($Sender->EventArguments['Name'])) {
             // Shorten our arguments
             $UserID = $Sender->EventArguments['UserID'];
             $Prefs = $Sender->EventArguments['Name'];
             $FlagPref = val('Email.Flag', $Prefs, null);
             if ($FlagPref !== null) {
                 // Add or remove user from config array
                 $NotifyUsers = c('Plugins.Flagging.NotifyUsers', array());
                 $IsNotified = array_search($UserID, $NotifyUsers);
                 // beware '0' key
                 if ($IsNotified !== false && !$FlagPref) {
                     // Remove from NotifyUsers
                     unset($NotifyUsers[$IsNotified]);
                 } elseif ($IsNotified === false && $FlagPref) {
                     // Add to NotifyUsers
                     $NotifyUsers[] = $UserID;
                 }
                 // Save new list of users to notify
                 saveToConfig('Plugins.Flagging.NotifyUsers', array_values($NotifyUsers));
             }
         }
     }
 }
Ejemplo n.º 2
0
 /**
  * Add button, remove options, increase click area on discussions list.
  */
 public function discussionsController_render_before($Sender)
 {
     $Sender->ShowOptions = false;
     saveToConfig('Vanilla.AdminCheckboxes.Use', false, false);
     $this->addButton($Sender, 'Discussion');
     $this->discussionsClickable($Sender);
 }
Ejemplo n.º 3
0
 /**
  * Statistics setup & configuration.
  *
  * @since 2.0.17
  * @access public
  */
 public function index()
 {
     $this->permission('Garden.Settings.Manage');
     $this->addSideMenu('dashboard/statistics');
     //$this->addJsFile('statistics.js');
     $this->title(t('Vanilla Statistics'));
     $this->enableSlicing($this);
     if ($this->Form->authenticatedPostBack()) {
         $Flow = true;
         if ($Flow && $this->Form->getFormValue('Reregister')) {
             $id = Gdn::installationID();
             $secret = Gdn::installationSecret();
             Gdn::installationID(false);
             Gdn::installationSecret(false);
             Gdn::Statistics()->register();
             if (!Gdn::installationID()) {
                 Gdn::installationID($id);
                 Gdn::installationSecret($secret);
             }
             $this->Form->setFormValue('InstallationID', Gdn::installationID());
             $this->Form->setFormValue('InstallationSecret', Gdn::installationSecret());
         }
         if ($Flow && $this->Form->getFormValue('Save')) {
             Gdn::installationID($this->Form->getFormValue('InstallationID'));
             Gdn::installationSecret($this->Form->getFormValue('InstallationSecret'));
             $this->informMessage(t("Your settings have been saved."));
         }
         if ($Flow && $this->Form->getFormValue('AllowLocal')) {
             saveToConfig('Garden.Analytics.AllowLocal', true);
         }
         if ($Flow && $this->Form->getFormValue('Allow')) {
             saveToConfig('Garden.Analytics.Enabled', true);
         }
         if ($Flow && $this->Form->getFormValue('ClearCredentials')) {
             Gdn::installationID(false);
             Gdn::installationSecret(false);
             Gdn::statistics()->Tick();
             $Flow = false;
         }
     } else {
         $this->Form->setValue('InstallationID', Gdn::installationID());
         $this->Form->setValue('InstallationSecret', Gdn::installationSecret());
     }
     $AnalyticsEnabled = Gdn_Statistics::checkIsEnabled();
     if ($AnalyticsEnabled) {
         $ConfFile = Gdn::config()->defaultPath();
         $this->setData('ConfWritable', $ConfWritable = is_writable($ConfFile));
         if (!$ConfWritable) {
             $AnalyticsEnabled = false;
         }
     }
     $this->setData('AnalyticsEnabled', $AnalyticsEnabled);
     $NotifyMessage = Gdn::get('Garden.Analytics.Notify', false);
     $this->setData('NotifyMessage', $NotifyMessage);
     if ($NotifyMessage !== false) {
         Gdn::set('Garden.Analytics.Notify', null);
     }
     $this->render();
 }
Ejemplo n.º 4
0
 public function structure()
 {
     // Get a user for operations.
     $UserID = Gdn::sql()->GetWhere('User', array('Name' => 'Akismet', 'Admin' => 2))->Value('UserID');
     if (!$UserID) {
         $UserID = Gdn::sql()->Insert('User', array('Name' => 'Akismet', 'Password' => RandomString('20'), 'HashMethod' => 'Random', 'Email' => '*****@*****.**', 'DateInserted' => Gdn_Format::toDateTime(), 'Admin' => '2'));
     }
     saveToConfig('Plugins.Akismet.UserID', $UserID);
 }
 /**
  * Default search functionality.
  *
  * @since 2.0.0
  * @access public
  * @param int $Page Page number.
  */
 public function index($Page = '')
 {
     $this->addJsFile('search.js');
     $this->title(t('Search'));
     saveToConfig('Garden.Format.EmbedSize', '160x90', false);
     Gdn_Theme::section('SearchResults');
     list($Offset, $Limit) = offsetLimit($Page, c('Garden.Search.PerPage', 20));
     $this->setData('_Limit', $Limit);
     $Search = $this->Form->getFormValue('Search');
     $Mode = $this->Form->getFormValue('Mode');
     if ($Mode) {
         $this->SearchModel->ForceSearchMode = $Mode;
     }
     try {
         $ResultSet = $this->SearchModel->Search($Search, $Offset, $Limit);
     } catch (Gdn_UserException $Ex) {
         $this->Form->addError($Ex);
         $ResultSet = array();
     } catch (Exception $Ex) {
         LogException($Ex);
         $this->Form->addError($Ex);
         $ResultSet = array();
     }
     Gdn::userModel()->joinUsers($ResultSet, array('UserID'));
     // Fix up the summaries.
     $SearchTerms = explode(' ', Gdn_Format::text($Search));
     foreach ($ResultSet as &$Row) {
         $Row['Summary'] = SearchExcerpt(Gdn_Format::plainText($Row['Summary'], $Row['Format']), $SearchTerms);
         $Row['Summary'] = Emoji::instance()->translateToHtml($Row['Summary']);
         $Row['Format'] = 'Html';
     }
     $this->setData('SearchResults', $ResultSet, true);
     $this->setData('SearchTerm', Gdn_Format::text($Search), true);
     if ($ResultSet) {
         $NumResults = count($ResultSet);
     } else {
         $NumResults = 0;
     }
     if ($NumResults == $Offset + $Limit) {
         $NumResults++;
     }
     // Build a pager
     $PagerFactory = new Gdn_PagerFactory();
     $this->Pager = $PagerFactory->GetPager('MorePager', $this);
     $this->Pager->MoreCode = 'More Results';
     $this->Pager->LessCode = 'Previous Results';
     $this->Pager->ClientID = 'Pager';
     $this->Pager->configure($Offset, $Limit, $NumResults, 'dashboard/search/%1$s/%2$s/?Search=' . Gdn_Format::url($Search));
     //		if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
     //         $this->setJson('LessRow', $this->Pager->toString('less'));
     //         $this->setJson('MoreRow', $this->Pager->toString('more'));
     //         $this->View = 'results';
     //      }
     $this->canonicalUrl(url('search', true));
     $this->render();
 }
 /**
  *
  *
  * @param $Sender
  */
 public function settingsController_privateCommunity_create($Sender)
 {
     $Session = Gdn::session();
     $Switch = val(0, $Sender->RequestArgs);
     $TransientKey = val(1, $Sender->RequestArgs);
     if (in_array($Switch, array('on', 'off')) && $Session->validateTransientKey($TransientKey) && $Session->checkPermission('Garden.Settings.Manage')) {
         saveToConfig('Garden.PrivateCommunity', $Switch == 'on' ? false : true);
     }
     redirect('dashboard/role');
 }
 public function gdn_dispatcher_afterAnalyzeRequest_handler($sender)
 {
     $inPublicDashboard = in_array($sender->controller(), array('Activity', 'Profile', 'Search'));
     if (in_array($sender->application(), array('vanilla', 'conversations')) || $inPublicDashboard) {
         Gdn::pluginManager()->removeMobileUnfriendlyPlugins();
     }
     saveToConfig('Garden.Format.EmbedSize', '240x135', false);
     saveToConfig('Vanilla.AdminCheckboxes.Use', false, false);
     //the table discussions layout takes up too much space on small screens
     saveToConfig('Vanilla.Discussions.Layout', 'modern', false);
 }
Ejemplo n.º 8
0
 /**
  * Allow updating the list of spam providers manually.
  *
  * @param settingsController $sender Instance of the calling class.
  * @package mailchecker
  * @since 0.2
  * @return void.
  */
 public function settingsController_mailchecker_create($sender)
 {
     $sender->permission('Garden.Settings.Manage');
     $sender->addSideMenu('dashboard/settings/plugins');
     $sender->setData('Title', t('Mailchecker Settings'));
     $sender->setData('Description', t('You can update the list from time to time but it is not needed at all since the plugin comes with an initial list.'));
     // Fetch new list and give feedback abut the number of providers.
     $sender->Form = new Gdn_Form();
     if ($sender->Form->authenticatedPostBack()) {
         $count = $this->updateList();
         if ($count) {
             saveToConfig('mailchecker.LastUpdate', date(time()));
             $sender->informMessage(sprintf(t('There are currently %1s spam providers in the list'), $count));
         }
     }
     $sender->render($this->getView('settings.php'));
 }
 public function settingsController_moduleSort_create($sender, $reset = false)
 {
     $sender->permission('Garden.Settings.Manage');
     $sender->addSideMenu('settings/modulesort');
     $sender->addJsFile('html.sortable.min.js', 'plugins/modulesort');
     $sender->addJsFile('modulesort.js', 'plugins/modulesort');
     if (Gdn::request()->isAuthenticatedPostBack()) {
         if ($reset) {
             removeFromConfig('Modules');
             $sender->jsonTarget('', '', 'Refresh');
         } elseif ($sort = json_decode(Gdn::request()->post('Modules'), true)) {
             saveToConfig('Modules', $sort);
         }
     }
     $sender->title(t('Module Sort Order'));
     $sender->render('modulesort', '', 'plugins/modulesort');
 }
Ejemplo n.º 10
0
 /**
  *
  * @param  object $sender SettingsController.
  * @return void.
  * @package Shariff
  * @since 0.1
  */
 public function settingsController_shariff_create($sender)
 {
     $sender->permission('Garden.Settings.Manage');
     $sender->addSideMenu('dashboard/settings/plugins');
     $sender->title(t('Shariff Settings'));
     $sender->setData('Description', t('Shariff Setup Description'));
     // Save values to config.
     if ($sender->Form->authenticatedPostBack()) {
         $formPostValues = $sender->Form->formValues();
         $services = $formPostValues['Shariff.Services'];
         $dataServices = '["' . implode('","', $services) . '"]';
         saveToConfig('Shariff.Services', $services);
         saveToConfig('Shariff.DataServices', $dataServices);
         saveToConfig('Shariff.Theme', $formPostValues['Shariff.Theme']);
     }
     $sender->Form->setData(array('Shariff.Services' => c('Shariff.Services'), 'Shariff.Theme' => c('Shariff.Theme')));
     $configurationModule = new ConfigurationModule($sender);
     // fill in all the info that is needed to build the settings view
     $configurationModule->schema(array('Shariff.Services' => array('Control' => 'CheckBoxList', 'Description' => t('Check services that should be enabled.'), 'Items' => array('facebook' => 'facebook', 'Google+' => 'googleplus', 'LinkedIn' => 'linkedin', t('E-Mail') => 'mail', 'Twitter' => 'twitter', 'Pinterest' => 'pinterest', 'WhatsApp' => 'whatsapp', 'Xing' => 'xing'), 'LabelCode' => 'Services'), 'Shariff.Theme' => array('Control' => 'DropDown', 'Items' => array('standard' => t('Standard'), 'grey' => t('Grey'), 'white' => t('White')), 'LabelCode' => 'Theme', 'Options' => array('IncludeNull' => false))));
     $configurationModule->renderAll();
 }
 /**
  * Webhook for Teamwork.
  *
  * POST data looks like this:
  * [  'event' => 'TASK.COMPLETED',
  *    'objectId' => '000',
  *    'accountId' => '000',
  *    'userId' => '000',
  * ]
  *
  * @see http://developer.teamwork.com/todolistitems
  *
  * @param Gdn_Controller $sender
  * @param $secret
  * @throws Exception
  */
 public function utilityController_teamworkTaskCompleted_create($sender, $secret)
 {
     if ($secret != c('SprintNotifier.Teamwork.Secret')) {
         throw new Exception('Invalid token.');
     }
     // Get data
     $data = Gdn::request()->post();
     // Sanity check we set up webhooks right.
     if (val('event', $data) != 'TASK.COMPLETED') {
         return;
     }
     // Cheat by storing some data in the config.
     $users = c('SprintNotifier.Teamwork.Users', []);
     $projects = c('SprintNotifier.Teamwork.Projects', []);
     // Get full task data via Teamwork's *ahem* "API".
     $task = self::teamworkTask(val('objectId', $data));
     // DEBUG
     UserModel::setMeta(0, array('TaskAPI' => var_export($task, true)), 'SprintNotifier.Debug.');
     // Respect project whitelist if we're using one.
     if (count($projects) && !in_array($task['project-name'], $projects)) {
         return;
     }
     // Build data for the chat message.
     $teamworkUserID = val('userId', $data);
     $userName = val($teamworkUserID, $users, 'User ' . val('userId', $data));
     $taskUrl = sprintf('https://%1$s.teamwork.com/tasks/%2$s', c('Teamwork.Account'), val('objectId', $data));
     $message = sprintf('%1$s completed %2$s task: <a href="%3$s">%4$s</a>', $userName, strtolower($task['project-name']), $taskUrl, $task['content']);
     // Override HipChat plugin's default token & room.
     saveToConfig('HipChat.Room', c('SprintNotifier.HipChat.RoomID'), false);
     saveToConfig('HipChat.Token', c('SprintNotifier.HipChat.Token'), false);
     // DEBUG
     UserModel::setMeta(0, array('Message' => var_export($message, true)), 'SprintNotifier.Debug.');
     // Say it! Bust it!
     if (class_exists('HipChat')) {
         HipChat::say($message);
     }
     self::bustCache();
     // 200 OK
     $sender->render('blank', 'utility', 'dashboard');
 }
Ejemplo n.º 12
0
 /**
  * Homepage of VanillaForums.org.
  *
  * @param Gdn_Controller $sender
  */
 public function homeController_homepage_create($sender)
 {
     try {
         $AddonModel = new AddonModel();
         $Addon = $AddonModel->getSlug('vanilla-core', true);
         $sender->setData('CountDownloads', val('CountDownloads', $Addon));
         $sender->setData('Version', val('Version', $Addon));
         $sender->setData('DateUploaded', val('DateInserted', $Addon));
     } catch (Exception $ex) {
     }
     $sender->title('The most powerful custom community solution in the world');
     $sender->setData('Description', "Vanilla is forum software that powers discussions on hundreds of thousands of sites. Built for flexibility and integration, Vanilla is the best, most powerful community solution in the world.");
     $sender->Head->addTag('meta', array('name' => 'description', 'content' => $sender->data('Description')));
     $sender->clearJsFiles();
     $sender->addJsFile('jquery.js', 'vforg');
     $sender->addJsFile('easySlider1.7.js', 'vforg');
     saveToConfig('Garden.Embed.Allow', false, false);
     // Prevent JS errors
     $sender->clearCssFiles();
     $sender->addCssFile('vforg-home.css', 'vforg');
     $sender->MasterView = 'empty';
     $sender->render('index', 'home', 'vforg');
 }
Ejemplo n.º 13
0
 /**
  * Default search functionality.
  *
  * @since 2.0.0
  * @access public
  * @param int $Page Page number.
  */
 public function index($Page = '')
 {
     $this->addJsFile('search.js');
     $this->title(t('Search'));
     saveToConfig('Garden.Format.EmbedSize', '160x90', false);
     Gdn_Theme::section('SearchResults');
     list($Offset, $Limit) = offsetLimit($Page, c('Garden.Search.PerPage', 20));
     $this->setData('_Limit', $Limit);
     $Search = $this->Form->getFormValue('Search');
     $Mode = $this->Form->getFormValue('Mode');
     if ($Mode) {
         $this->SearchModel->ForceSearchMode = $Mode;
     }
     try {
         $ResultSet = $this->SearchModel->search($Search, $Offset, $Limit);
     } catch (Gdn_UserException $Ex) {
         $this->Form->addError($Ex);
         $ResultSet = array();
     } catch (Exception $Ex) {
         LogException($Ex);
         $this->Form->addError($Ex);
         $ResultSet = array();
     }
     Gdn::userModel()->joinUsers($ResultSet, array('UserID'));
     // Fix up the summaries.
     $SearchTerms = explode(' ', Gdn_Format::text($Search));
     foreach ($ResultSet as &$Row) {
         $Row['Summary'] = searchExcerpt(htmlspecialchars(Gdn_Format::plainText($Row['Summary'], $Row['Format'])), $SearchTerms);
         $Row['Summary'] = Emoji::instance()->translateToHtml($Row['Summary']);
         $Row['Format'] = 'Html';
     }
     $this->setData('SearchResults', $ResultSet, true);
     $this->setData('SearchTerm', Gdn_Format::text($Search), true);
     $this->setData('_CurrentRecords', count($ResultSet));
     $this->canonicalUrl(url('search', true));
     $this->render();
 }
Ejemplo n.º 14
0
 /**
  * If looking at the root node, make sure it exists and that the
  * nested set columns exist in the table.
  *
  * @since 2.0.15
  * @access public
  */
 public function applyUpdates()
 {
     if (!c('Vanilla.NestedCategoriesUpdate')) {
         // Add new columns
         $Construct = Gdn::database()->Structure();
         $Construct->table('Category')->column('TreeLeft', 'int', true)->column('TreeRight', 'int', true)->column('Depth', 'int', true)->column('CountComments', 'int', '0')->column('LastCommentID', 'int', true)->set(0, 0);
         // Insert the root node
         if ($this->SQL->getWhere('Category', array('CategoryID' => -1))->numRows() == 0) {
             $this->SQL->insert('Category', array('CategoryID' => -1, 'TreeLeft' => 1, 'TreeRight' => 4, 'Depth' => 0, 'InsertUserID' => 1, 'UpdateUserID' => 1, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime(), 'Name' => t('Root Category Name', 'Root'), 'UrlCode' => '', 'Description' => t('Root Category Description', 'Root of category tree. Users should never see this.')));
         }
         // Build up the TreeLeft & TreeRight values.
         $this->rebuildTree();
         saveToConfig('Vanilla.NestedCategoriesUpdate', 1);
     }
 }
Ejemplo n.º 15
0
 /**
  * Retrieves a "system user" id that can be used to perform non-real-person tasks.
  *
  * @return int Returns a user ID.
  */
 public function getSystemUserID()
 {
     $SystemUserID = c('Garden.SystemUserID');
     if ($SystemUserID) {
         return $SystemUserID;
     }
     $SystemUser = ['Name' => t('System'), 'Photo' => asset('/applications/dashboard/design/images/usericon.png', true), 'Password' => randomString('20'), 'HashMethod' => 'Random', 'Email' => '*****@*****.**', 'DateInserted' => Gdn_Format::toDateTime(), 'Admin' => '2'];
     $this->EventArguments['SystemUser'] =& $SystemUser;
     $this->fireEvent('BeforeSystemUser');
     $SystemUserID = $this->SQL->insert($this->Name, $SystemUser);
     saveToConfig('Garden.SystemUserID', $SystemUserID);
     return $SystemUserID;
 }
Ejemplo n.º 16
0
 /**
  * Allows the configuration of basic setup information in Garden. This
  * should not be functional after the application has been set up.
  *
  * @since 2.0.0
  * @access public
  * @param string $RedirectUrl Where to send user afterward.
  */
 private function configure($RedirectUrl = '')
 {
     // Create a model to save configuration settings
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $ConfigurationModel->setField(array('Garden.Locale', 'Garden.Title', 'Garden.WebRoot', 'Garden.Cookie.Salt', 'Garden.Cookie.Domain', 'Database.Name', 'Database.Host', 'Database.User', 'Database.Password', 'Garden.Registration.ConfirmEmail', 'Garden.Email.SupportName'));
     // Set the models on the forms.
     $this->Form->setModel($ConfigurationModel);
     // If seeing the form for the first time...
     if (!$this->Form->isPostback()) {
         // Force the webroot using our best guesstimates
         $ConfigurationModel->Data['Database.Host'] = 'localhost';
         $this->Form->setData($ConfigurationModel->Data);
     } else {
         // Define some validation rules for the fields being saved
         $ConfigurationModel->Validation->applyRule('Database.Name', 'Required', 'You must specify the name of the database in which you want to set up Vanilla.');
         // Let's make some user-friendly custom errors for database problems
         $DatabaseHost = $this->Form->getFormValue('Database.Host', '~~Invalid~~');
         $DatabaseName = $this->Form->getFormValue('Database.Name', '~~Invalid~~');
         $DatabaseUser = $this->Form->getFormValue('Database.User', '~~Invalid~~');
         $DatabasePassword = $this->Form->getFormValue('Database.Password', '~~Invalid~~');
         $ConnectionString = GetConnectionString($DatabaseName, $DatabaseHost);
         try {
             $Connection = new PDO($ConnectionString, $DatabaseUser, $DatabasePassword);
         } catch (PDOException $Exception) {
             switch ($Exception->getCode()) {
                 case 1044:
                     $this->Form->addError(t('The database user you specified does not have permission to access the database. Have you created the database yet? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage()));
                     break;
                 case 1045:
                     $this->Form->addError(t('Failed to connect to the database with the username and password you entered. Did you mistype them? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage()));
                     break;
                 case 1049:
                     $this->Form->addError(t('It appears as though the database you specified does not exist yet. Have you created it yet? Did you mistype the name? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage()));
                     break;
                 case 2005:
                     $this->Form->addError(t("Are you sure you've entered the correct database host name? Maybe you mistyped it? The database reported: <code>%s</code>"), strip_tags($Exception->getMessage()));
                     break;
                 default:
                     $this->Form->addError(sprintf(t('ValidateConnection'), strip_tags($Exception->getMessage())));
                     break;
             }
         }
         $ConfigurationModel->Validation->applyRule('Garden.Title', 'Required');
         $ConfigurationFormValues = $this->Form->formValues();
         if ($ConfigurationModel->validate($ConfigurationFormValues) !== true || $this->Form->errorCount() > 0) {
             // Apply the validation results to the form(s)
             $this->Form->setValidationResults($ConfigurationModel->validationResults());
         } else {
             $Host = array_shift(explode(':', Gdn::request()->requestHost()));
             $Domain = Gdn::request()->domain();
             // Set up cookies now so that the user can be signed in.
             $ExistingSalt = c('Garden.Cookie.Salt', false);
             $ConfigurationFormValues['Garden.Cookie.Salt'] = $ExistingSalt ? $ExistingSalt : betterRandomString(16, 'Aa0');
             $ConfigurationFormValues['Garden.Cookie.Domain'] = '';
             // Don't set this to anything by default. # Tim - 2010-06-23
             // Additional default setup values.
             $ConfigurationFormValues['Garden.Registration.ConfirmEmail'] = true;
             $ConfigurationFormValues['Garden.Email.SupportName'] = $ConfigurationFormValues['Garden.Title'];
             $ConfigurationModel->save($ConfigurationFormValues, true);
             // If changing locale, redefine locale sources:
             $NewLocale = 'en-CA';
             // $this->Form->getFormValue('Garden.Locale', false);
             if ($NewLocale !== false && Gdn::config('Garden.Locale') != $NewLocale) {
                 $Locale = Gdn::locale();
                 $Locale->set($NewLocale);
             }
             // Install db structure & basic data.
             $Database = Gdn::database();
             $Database->init();
             $Drop = false;
             $Explicit = false;
             try {
                 include PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'structure.php';
             } catch (Exception $ex) {
                 $this->Form->addError($ex);
             }
             if ($this->Form->errorCount() > 0) {
                 return false;
             }
             // Create the administrative user
             $UserModel = Gdn::userModel();
             $UserModel->defineSchema();
             $UsernameError = t('UsernameError', 'Username can only contain letters, numbers, underscores, and must be between 3 and 20 characters long.');
             $UserModel->Validation->applyRule('Name', 'Username', $UsernameError);
             $UserModel->Validation->applyRule('Name', 'Required', t('You must specify an admin username.'));
             $UserModel->Validation->applyRule('Password', 'Required', t('You must specify an admin password.'));
             $UserModel->Validation->applyRule('Password', 'Match');
             $UserModel->Validation->applyRule('Email', 'Email');
             if (!($AdminUserID = $UserModel->SaveAdminUser($ConfigurationFormValues))) {
                 $this->Form->setValidationResults($UserModel->validationResults());
             } else {
                 // The user has been created successfully, so sign in now.
                 saveToConfig('Garden.Installed', true, array('Save' => false));
                 Gdn::session()->start($AdminUserID, true);
                 saveToConfig('Garden.Installed', false, array('Save' => false));
             }
             if ($this->Form->errorCount() > 0) {
                 return false;
             }
             // Assign some extra settings to the configuration file if everything succeeded.
             $ApplicationInfo = array();
             include CombinePaths(array(PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'about.php'));
             // Detect Internet connection for CDNs
             $Disconnected = !(bool) @fsockopen('ajax.googleapis.com', 80);
             saveToConfig(array('Garden.Version' => val('Version', val('Dashboard', $ApplicationInfo, array()), 'Undefined'), 'Garden.Cdns.Disable' => $Disconnected, 'Garden.CanProcessImages' => function_exists('gd_info'), 'EnabledPlugins.GettingStarted' => 'GettingStarted', 'EnabledPlugins.HtmLawed' => 'HtmLawed'));
         }
     }
     return $this->Form->errorCount() == 0 ? true : false;
 }
Ejemplo n.º 17
0
 /**
  *
  *
  * @param $Sender
  * @param $Args
  */
 public function socialController_twitter_create($Sender, $Args)
 {
     $Sender->permission('Garden.Settings.Manage');
     if ($Sender->Form->authenticatedPostBack()) {
         $Settings = array('Plugins.Twitter.ConsumerKey' => trim($Sender->Form->getFormValue('ConsumerKey')), 'Plugins.Twitter.Secret' => trim($Sender->Form->getFormValue('Secret')), 'Plugins.Twitter.SocialSignIn' => $Sender->Form->getFormValue('SocialSignIn'), 'Plugins.Twitter.SocialReactions' => $Sender->Form->getFormValue('SocialReactions'), 'Plugins.Twitter.SocialSharing' => $Sender->Form->getFormValue('SocialSharing'));
         saveToConfig($Settings);
         $Sender->informMessage(t("Your settings have been saved."));
     } else {
         $Sender->Form->setValue('ConsumerKey', c('Plugins.Twitter.ConsumerKey'));
         $Sender->Form->setValue('Secret', c('Plugins.Twitter.Secret'));
         $Sender->Form->setValue('SocialSignIn', $this->SocialSignIn());
         $Sender->Form->setValue('SocialReactions', $this->SocialReactions());
         $Sender->Form->setValue('SocialSharing', $this->SocialSharing());
     }
     $Sender->addSideMenu('dashboard/social');
     $Sender->setData('Title', t('Twitter Settings'));
     $Sender->render('Settings', '', 'plugins/Twitter');
 }
 /**
  * Manage options for a mobile theme.
  *
  * @since 2.0.0
  * @access public
  * @param string $Style Unique ID.
  * @todo Why is this in a giant try/catch block?
  */
 public function mobileThemeOptions($Style = null)
 {
     $this->permission('Garden.Settings.Manage');
     try {
         $this->addJsFile('addons.js');
         $this->addSideMenu('dashboard/settings/mobilethemeoptions');
         $ThemeManager = Gdn::themeManager();
         $EnabledThemeName = $ThemeManager->mobileTheme();
         $EnabledThemeInfo = $ThemeManager->getThemeInfo($EnabledThemeName);
         $this->setData('ThemeInfo', $EnabledThemeInfo);
         if ($this->Form->authenticatedPostBack()) {
             // Save the styles to the config.
             $StyleKey = $this->Form->getFormValue('StyleKey');
             $ConfigSaveData = array('Garden.MobileThemeOptions.Styles.Key' => $StyleKey, 'Garden.MobileThemeOptions.Styles.Value' => $this->data("ThemeInfo.Options.Styles.{$StyleKey}.Basename"));
             // Save the text to the locale.
             $Translations = array();
             foreach ($this->data('ThemeInfo.Options.Text', array()) as $Key => $Default) {
                 $Value = $this->Form->getFormValue($this->Form->escapeString('Text_' . $Key));
                 $ConfigSaveData["ThemeOption.{$Key}"] = $Value;
                 //$this->Form->setFormValue('Text_'.$Key, $Value);
             }
             saveToConfig($ConfigSaveData);
             $this->informMessage(t("Your changes have been saved."));
         } elseif ($Style) {
             saveToConfig(array('Garden.MobileThemeOptions.Styles.Key' => $Style, 'Garden.MobileThemeOptions.Styles.Value' => $this->data("ThemeInfo.Options.Styles.{$Style}.Basename")));
         }
         $this->setData('ThemeOptions', c('Garden.MobileThemeOptions'));
         $StyleKey = $this->data('ThemeOptions.Styles.Key');
         if (!$this->Form->authenticatedPostBack()) {
             foreach ($this->data('ThemeInfo.Options.Text', array()) as $Key => $Options) {
                 $Default = val('Default', $Options, '');
                 $Value = c("ThemeOption.{$Key}", '#DEFAULT#');
                 if ($Value === '#DEFAULT#') {
                     $Value = $Default;
                 }
                 $this->Form->setFormValue($this->Form->escapeString('Text_' . $Key), $Value);
             }
         }
         $this->setData('ThemeFolder', $EnabledThemeName);
         $this->title(t('Mobile Theme Options'));
         $this->Form->addHidden('StyleKey', $StyleKey);
     } catch (Exception $Ex) {
         $this->Form->addError($Ex);
     }
     $this->render('themeoptions');
 }
Ejemplo n.º 19
0
 /**
  * Show list of roles.
  *
  * @since 2.0.0
  * @access public
  */
 public function index($roleID = null)
 {
     $this->_permission();
     $this->setHighlightRoute('dashboard/role');
     $this->addJsFile('jquery.tablednd.js');
     $this->title(t('Roles & Permissions'));
     if (!$roleID) {
         $roles = $this->RoleModel->getWithRankPermissions()->resultArray();
         // Check to see which roles can be modified.
         foreach ($roles as &$row) {
             $canModify = true;
             if (!Gdn::session()->checkPermission('Garden.Settings.Manage')) {
                 foreach ($this->RoleModel->RankPermissions as $permission) {
                     if ($row[$permission] && !Gdn::session()->checkPermission($permission)) {
                         $canModify = false;
                         break;
                     }
                 }
             }
             $row['CanModify'] = $canModify;
         }
         $this->setData('Roles', $roles);
     } elseif ($this->deliveryType() === DELIVERY_TYPE_DATA) {
         // This is an API request. Get the role in a nicer format.
         $role = $this->RoleModel->getID($roleID, DATASET_TYPE_ARRAY);
         // Get the global permissions.
         $permissions = Gdn::permissionModel()->getGlobalPermissions($roleID);
         unset($permissions['PermissionID']);
         // Get the per-category permissions.
         $permissions['Category'] = $this->RoleModel->getCategoryPermissions($roleID);
         $role['Permissions'] = $permissions;
         $this->setData('Role', $role);
         saveToConfig('Api.Clean', false, false);
     } else {
         $Role = $this->RoleModel->getID($roleID);
         $this->setData('Roles', [$Role]);
     }
     // Grab the total users for each role.
     if (is_array($this->data('Roles'))) {
         $pastThreshold = Gdn::userModel()->pastUserMegaThreshold();
         $thresholdTypeExceptions = RoleModel::getDefaultTypes();
         unset($thresholdTypeExceptions[RoleModel::TYPE_MEMBER]);
         $roles = $this->data('Roles');
         foreach ($roles as &$role) {
             if ($pastThreshold && !in_array($role['Type'], $thresholdTypeExceptions)) {
                 $countUsers = t('View');
             } else {
                 $countUsers = $this->RoleModel->getUserCount($role['RoleID']);
             }
             $role['CountUsers'] = $countUsers;
         }
         $this->setData('Roles', $roles);
     }
     $this->render();
 }
Ejemplo n.º 20
0
 /**
  * Show list of roles.
  *
  * @since 2.0.0
  * @access public
  */
 public function index($roleID = null)
 {
     $this->_permission();
     $this->addSideMenu('dashboard/role');
     $this->addJsFile('jquery.tablednd.js');
     $this->title(t('Roles & Permissions'));
     if (!$roleID) {
         $roles = $this->RoleModel->getWithRankPermissions()->resultArray();
         // Check to see which roles can be modified.
         foreach ($roles as &$row) {
             $canModify = true;
             if (!Gdn::session()->checkPermission('Garden.Settings.Manage')) {
                 foreach ($this->RoleModel->RankPermissions as $permission) {
                     if ($row[$permission] && !Gdn::session()->checkPermission($permission)) {
                         $canModify = false;
                         break;
                     }
                 }
             }
             $row['CanModify'] = $canModify;
         }
         $this->setData('Roles', $roles);
     } elseif ($this->deliveryType() === DELIVERY_TYPE_DATA) {
         // This is an API request. Get the role in a nicer format.
         $role = $this->RoleModel->getID($roleID, DATASET_TYPE_ARRAY);
         // Get the global permissions.
         $permissions = Gdn::permissionModel()->getGlobalPermissions($roleID);
         unset($permissions['PermissionID']);
         // Get the per-category permissions.
         $permissions['Category'] = $this->RoleModel->getCategoryPermissions($roleID);
         $role['Permissions'] = $permissions;
         $this->setData('Role', $role);
         saveToConfig('Api.Clean', false, false);
     } else {
         $Role = $this->RoleModel->getID($roleID);
         $this->setData('Roles', [$Role]);
     }
     $this->render();
 }
Ejemplo n.º 21
0
 /**
  * Set the default authenticator.
  *
  * @param string $AuthenticationSchemeAlias
  * @return bool
  */
 public function setDefaultAuthenticator($AuthenticationSchemeAlias)
 {
     $AuthenticationSchemeAlias = strtolower($AuthenticationSchemeAlias);
     $EnabledSchemes = Gdn::config('Garden.Authenticator.EnabledSchemes', array());
     if (!in_array($AuthenticationSchemeAlias, $EnabledSchemes)) {
         return false;
     }
     saveToConfig('Garden.Authenticator.DefaultScheme', $AuthenticationSchemeAlias);
     return true;
 }
Ejemplo n.º 22
0
 /**
  * Handle toggling this version of embedding on and off. Take care of disabling the other version of embed (the old plugin).
  *
  * @param string $Toggle
  * @param string $TransientKey
  * @return boolean
  * @throws Gdn_UserException
  */
 private function toggle($Toggle = '', $TransientKey = '')
 {
     if (in_array($Toggle, array('enable', 'disable')) && Gdn::session()->validateTransientKey($TransientKey)) {
         if ($Toggle == 'enable' && array_key_exists('embedvanilla', Gdn::pluginManager()->enabledPlugins())) {
             throw new Gdn_UserException('You must disable the "Embed Vanilla" plugin before continuing.');
         }
         // Do the toggle
         saveToConfig('Garden.Embed.Allow', $Toggle == 'enable' ? true : false);
         return true;
     }
     return false;
 }
Ejemplo n.º 23
0
 /**
  * Save our current message locations in the config.
  */
 public function setMessageCache()
 {
     // Retrieve an array of all controllers that have enabled messages associated
     saveToConfig('Garden.Messages.Cache', $this->getEnabledLocations());
 }
Ejemplo n.º 24
0
 /**
  *
  * @param Gdn_Controller $Sender
  * @param array $Args
  */
 public function base_connectData_handler($Sender, $Args)
 {
     if (val(0, $Args) != 'facebook') {
         return;
     }
     if (isset($_GET['error'])) {
         // TODO global nope x2
         throw new Gdn_UserException(val('error_description', $_GET, t('There was an error connecting to Facebook')));
     }
     $AppID = c('Plugins.Facebook.ApplicationID');
     $Secret = c('Plugins.Facebook.Secret');
     $Code = val('code', $_GET);
     // TODO nope
     $Query = '';
     if ($Sender->Request->get('display')) {
         $Query = 'display=' . urlencode($Sender->Request->get('display'));
     }
     $RedirectUri = concatSep('&', $this->redirectUri(), $Query);
     $AccessToken = $Sender->Form->getFormValue('AccessToken');
     // Get the access token.
     if (!$AccessToken && $Code) {
         // Exchange the token for an access token.
         $Code = urlencode($Code);
         $AccessToken = $this->getAccessToken($Code, $RedirectUri);
         $NewToken = true;
     }
     // Get the profile.
     try {
         $Profile = $this->getProfile($AccessToken);
     } catch (Exception $Ex) {
         if (!isset($NewToken)) {
             // There was an error getting the profile, which probably means the saved access token is no longer valid. Try and reauthorize.
             if ($Sender->deliveryType() == DELIVERY_TYPE_ALL) {
                 redirect($this->authorizeUri());
             } else {
                 $Sender->setHeader('Content-type', 'application/json');
                 $Sender->deliveryMethod(DELIVERY_METHOD_JSON);
                 $Sender->RedirectUrl = $this->authorizeUri();
             }
         } else {
             $Sender->Form->addError('There was an error with the Facebook connection.');
         }
     }
     $Form = $Sender->Form;
     //new Gdn_Form();
     $ID = val('id', $Profile);
     $Form->setFormValue('UniqueID', $ID);
     $Form->setFormValue('Provider', self::ProviderKey);
     $Form->setFormValue('ProviderName', 'Facebook');
     $Form->setFormValue('FullName', val('name', $Profile));
     $Form->setFormValue('Email', val('email', $Profile));
     $Form->setFormValue('Photo', "//graph.facebook.com/{$ID}/picture?width=200&height=200");
     $Form->addHidden('AccessToken', $AccessToken);
     if (c('Plugins.Facebook.UseFacebookNames')) {
         $Form->setFormValue('Name', val('name', $Profile));
         saveToConfig(array('Garden.User.ValidationRegex' => UserModel::USERNAME_REGEX_MIN, 'Garden.User.ValidationLength' => '{3,50}', 'Garden.Registration.NameUnique' => false), '', false);
     }
     // Save some original data in the attributes of the connection for later API calls.
     $Attributes = array();
     $Attributes[self::ProviderKey] = array('AccessToken' => $AccessToken, 'Profile' => $Profile);
     $Form->setFormValue('Attributes', $Attributes);
     $Sender->setData('Verified', true);
 }
Ejemplo n.º 25
0
 /**
  *
  */
 public function onDisable()
 {
     saveToConfig('Debug', FALSE, array('RemoveEmpty' => TRUE));
 }
Ejemplo n.º 26
0
 /**
  * Takes a set of form data ($Form->_PostValues), validates them, and
  * inserts or updates them to the configuration file.
  *
  * @param array $FormPostValues An associative array of $Field => $Value pairs that represent data posted
  * from the form in the $_POST or $_GET collection.
  */
 public function save($FormPostValues, $Live = false)
 {
     // Fudge your way through the schema application. This will allow me to
     // force the validation object to expect the fieldnames contained in
     // $this->Data.
     $this->Validation->setSchema($this->Data);
     // Validate the form posted values
     if ($this->Validation->validate($FormPostValues)) {
         // Merge the validation fields and the forced settings into a single array
         $Settings = $this->Validation->validationFields();
         if (is_array($this->_ForceSettings)) {
             $Settings = mergeArrays($Settings, $this->_ForceSettings);
         }
         $SaveResults = saveToConfig($Settings);
         // If the Live flag is true, set these in memory too
         if ($SaveResults && $Live) {
             Gdn::config()->set($Settings, true);
         }
         return $SaveResults;
     } else {
         return false;
     }
 }
Ejemplo n.º 27
0
 /**
  * Database & config changes to be done upon enable.
  *
  * @since 2.0.0
  * @access public
  */
 public function setup()
 {
     $Database = Gdn::database();
     $Config = Gdn::factory(Gdn::AliasConfig);
     $Drop = false;
     //c('Conversations.Version') === FALSE ? TRUE : FALSE;
     $Validation = new Gdn_Validation();
     // This is going to be needed by structure.php to validate permission names
     include PATH_APPLICATIONS . DS . 'conversations' . DS . 'settings' . DS . 'structure.php';
     include PATH_APPLICATIONS . DS . 'conversations' . DS . 'settings' . DS . 'stub.php';
     $ApplicationInfo = array();
     include combinePaths(array(PATH_APPLICATIONS . DS . 'conversations' . DS . 'settings' . DS . 'about.php'));
     $Version = val('Version', val('Conversations', $ApplicationInfo, array()), 'Undefined');
     saveToConfig('Conversations.Version', $Version);
 }
Ejemplo n.º 28
0
 /**
  * Record when the various actions are taken.
  *
  * 1. If the user edits the registration settings.
  *
  * @param $Step
  * @throws Exception
  */
 public function saveStep($Step)
 {
     if (Gdn::config($Step, '') != '1') {
         saveToConfig($Step, '1');
     }
     // If all of the steps are now completed, disable this plugin
     if (Gdn::config('Plugins.GettingStarted.Registration', '0') == '1' && Gdn::config('Plugins.GettingStarted.Plugins', '0') == '1' && Gdn::config('Plugins.GettingStarted.Categories', '0') == '1' && Gdn::config('Plugins.GettingStarted.Profile', '0') == '1' && Gdn::config('Plugins.GettingStarted.Discussion', '0') == '1') {
         Gdn::pluginManager()->disablePlugin('GettingStarted');
     }
 }
Ejemplo n.º 29
0
$Construct->table('Regarding')->primaryKey('RegardingID')->column('Type', 'varchar(100)', false, 'key')->column('InsertUserID', 'int', false)->column('DateInserted', 'datetime', false)->column('ForeignType', 'varchar(32)', false)->column('ForeignID', 'int(11)', false)->column('OriginalContent', 'text', true)->column('ParentType', 'varchar(32)', true)->column('ParentID', 'int(11)', true)->column('ForeignURL', 'varchar(255)', true)->column('Comment', 'text', false)->column('Reports', 'int(11)', true)->engine('InnoDB')->set($Explicit, $Drop);
$Construct->table('Ban')->primaryKey('BanID')->column('BanType', array('IPAddress', 'Name', 'Email'), false, 'unique')->column('BanValue', 'varchar(50)', false, 'unique')->column('Notes', 'varchar(255)', null)->column('CountUsers', 'uint', 0)->column('CountBlockedRegistrations', 'uint', 0)->column('InsertUserID', 'int')->column('DateInserted', 'datetime')->column('InsertIPAddress', 'varchar(15)', true)->column('UpdateUserID', 'int', true)->column('DateUpdated', 'datetime', true)->column('UpdateIPAddress', 'varchar(15)', true)->engine('InnoDB')->set($Explicit, $Drop);
$Construct->table('Spammer')->column('UserID', 'int', false, 'primary')->column('CountSpam', 'usmallint', 0)->column('CountDeletedSpam', 'usmallint', 0)->set($Explicit, $Drop);
$Construct->table('Media')->primaryKey('MediaID')->column('Name', 'varchar(255)')->column('Path', 'varchar(255)')->column('Type', 'varchar(128)')->column('Size', 'int(11)')->column('InsertUserID', 'int(11)')->column('DateInserted', 'datetime')->column('ForeignID', 'int(11)', true, 'index.Foreign')->column('ForeignTable', 'varchar(24)', true, 'index.Foreign')->column('ImageWidth', 'usmallint', null)->column('ImageHeight', 'usmallint', null)->column('ThumbWidth', 'usmallint', null)->column('ThumbHeight', 'usmallint', null)->column('ThumbPath', 'varchar(255)', null)->set(false, false);
// Merge backup.
$Construct->table('UserMerge')->primaryKey('MergeID')->column('OldUserID', 'int', false, 'key')->column('NewUserID', 'int', false, 'key')->column('DateInserted', 'datetime')->column('InsertUserID', 'int')->column('DateUpdated', 'datetime', true)->column('UpdateUserID', 'int', true)->column('Attributes', 'text', true)->set();
$Construct->table('UserMergeItem')->column('MergeID', 'int', false, 'key')->column('Table', 'varchar(30)')->column('Column', 'varchar(30)')->column('RecordID', 'int')->column('OldUserID', 'int')->column('NewUserID', 'int')->set();
$Construct->table('Attachment')->primaryKey('AttachmentID')->column('Type', 'varchar(64)')->column('ForeignID', 'varchar(50)', false, 'index')->column('ForeignUserID', 'int', false, 'key')->column('Source', 'varchar(64)')->column('SourceID', 'varchar(32)')->column('SourceURL', 'varchar(255)')->column('Attributes', 'text', true)->column('DateInserted', 'datetime')->column('InsertUserID', 'int', false, 'key')->column('InsertIPAddress', 'varchar(64)')->column('DateUpdated', 'datetime', true)->column('UpdateUserID', 'int', true)->column('UpdateIPAddress', 'varchar(15)', true)->set($Explicit, $Drop);
// Save the current input formatter to the user's config.
// This will allow us to change the default later and grandfather existing forums in.
saveToConfig('Garden.InputFormatter', c('Garden.InputFormatter'));
// Make sure the default locale is in its canonical form.
$currentLocale = c('Garden.Locale');
$canonicalLocale = Gdn_Locale::canonicalize($currentLocale);
if ($currentLocale !== $canonicalLocale) {
    saveToConfig('Garden.Locale', $canonicalLocale);
}
// We need to undo cleditor's bad behavior for our reformed users.
// If you still need to manipulate this, do it in memory instead (SAVE = false).
if (!c('Garden.Html.SafeStyles')) {
    removeFromConfig('Garden.Html.SafeStyles');
}
// Make sure the smarty folders exist.
if (!file_exists(PATH_CACHE . '/Smarty')) {
    @mkdir(PATH_CACHE . '/Smarty');
}
if (!file_exists(PATH_CACHE . '/Smarty/cache')) {
    @mkdir(PATH_CACHE . '/Smarty/cache');
}
if (!file_exists(PATH_CACHE . '/Smarty/compile')) {
    @mkdir(PATH_CACHE . '/Smarty/compile');
 /**
  *
  */
 public function setRoleDefaults()
 {
     if (!$this->importExists('Role', 'RoleID')) {
         return;
     }
     $Data = $this->SQL->get('zRole')->resultArray();
     $RoleDefaults = array('Garden.Registration.ConfirmEmail' => false);
     $RoleTypes = array();
     foreach ($Data as $Row) {
         if ($this->importExists('Role', '_Default')) {
             $Name = $Row['_Default'];
         } else {
             $Name = val('Name', $Row);
         }
         $RoleID = $Row['RoleID'];
         if (preg_match('`anonymous`', $Name)) {
             $Name = 'guest';
         } elseif (preg_match('`admin`', $Name)) {
             $Name = 'administrator';
         }
         switch (strtolower($Name)) {
             case 'email':
             case 'confirm email':
             case 'users awaiting email confirmation':
             case 'pending':
                 $RoleTypes[$RoleID] = RoleModel::TYPE_UNCONFIRMED;
                 $RoleDefaults['Garden.Registration.ConfirmEmail'] = true;
                 break;
             case 'member':
             case 'members':
             case 'registered':
             case 'registered users':
                 $RoleTypes[$RoleID] = RoleModel::TYPE_MEMBER;
                 break;
             case 'guest':
             case 'guests':
             case 'unauthenticated':
             case 'unregistered':
             case 'unregistered / not logged in':
                 $RoleTypes[$RoleID] = RoleModel::TYPE_GUEST;
                 break;
             case 'applicant':
             case 'applicants':
                 $RoleTypes[$RoleID] = RoleModel::TYPE_APPLICANT;
                 break;
         }
     }
     saveToConfig($RoleDefaults);
     $roleModel = new RoleModel();
     foreach ($RoleTypes as $RoleID => $Type) {
         $roleModel->setField($RoleID, 'Type', $Type);
     }
 }