request() public static method

Get or set the current request object.
public static request ( Gdn_Request $NewRequest = null ) : Gdn_Request
$NewRequest Gdn_Request The new request or null to just get the request.
return Gdn_Request
 /**
  * Set the sort order for data on an arbitrary database table.
  *
  * Expect post values TransientKey, Target (redirect URL), Table (database table name),
  * and TableID (an array of sort order => unique ID).
  *
  * @since 2.0.0
  * @access public
  */
 public function sort()
 {
     $this->permission('Garden.Settings.Manage');
     if (Gdn::request()->isAuthenticatedPostBack()) {
         $TableID = Gdn::request()->Post('TableID');
         if ($TableID) {
             $Rows = Gdn::request()->Post($TableID);
             if (is_array($Rows)) {
                 $Table = str_replace(array('Table', '`'), '', $TableID);
                 $ModelName = $Table . 'Model';
                 if (class_exists($ModelName)) {
                     $TableModel = new $ModelName();
                 } else {
                     $TableModel = new Gdn_Model($Table);
                 }
                 foreach ($Rows as $Sort => $ID) {
                     if (strpos($ID, '_') !== false) {
                         list(, $ID) = explode('_', $ID, 2);
                     }
                     if (!$ID) {
                         continue;
                     }
                     $TableModel->setField($ID, 'Sort', $Sort);
                 }
                 $this->setData('Result', true);
             }
         }
     }
     $this->render('Blank');
 }
Example #2
0
 /**
  * Map an API request to a resource
  *
  * @since  0.1.0
  * @access public
  * @param  Gdn_Dispatcher $sender
  * @return void
  */
 public function Gdn_Dispatcher_beforeDispatch_handler($sender)
 {
     $path = APIEngine::getRequestURI();
     // Set the call and resource paths if they exist
     $call = val(0, $path);
     $resource = val(1, $path);
     // Abandon the dispatch if this isn't an API call with a valid resource
     if ($call != "api" || !$resource) {
         return;
     }
     APIEngine::setRequestHeaders();
     try {
         // Mark the dispatch with the API version
         $sender->API = c("API.Version", "Undefined");
         // Attempt dispatching the API request
         APIEngine::dispatchRequest();
     } catch (Exception $exception) {
         // As we can"t pass an object to WithControllerMethod(), we extract
         // the values we need manually before passing them on. The exception
         // message is Base64 encoded as WithControllerMethod() mangles
         // the formatting.
         $code = $exception->getCode();
         $message = base64_encode($exception->getMessage());
         $arguments = [$code, $message];
         // Call the Exception method if an exception is thrown
         Gdn::request()->withControllerMethod("API", "Exception", $arguments);
     }
 }
Example #3
0
 /**
  * Generate a Gravatar image URL based on the provided email address.
  *
  * @link http://en.gravatar.com/site/implement/images/ Gravatar Image Requests
  * @param string $email Email address for the user, used to generate the avatar ID.
  * @param int $size Target image size.
  * @return string A formatted Gravatar image URL.
  */
 public static function generateUrl($email, $size = 80)
 {
     $avatarID = md5(strtolower($email));
     // Figure out our base URLs.  Gravatar doesn't support SVGs, so we're stuck with using Vanillicon v1.
     if (Gdn::request()->scheme() === 'https') {
         $baseUrl = 'https://secure.gravatar.com/avatar';
         $vanilliconBaseUrl = 'https://vanillicon.com';
     } else {
         $baseUrl = 'http://www.gravatar.com/avatar';
         $vanilliconBaseUrl = 'http://vanillicon.com';
     }
     if (c('Plugins.Gravatar.UseVanillicon', true)) {
         // Version 1 of Vanillicon only supports three sizes.  Figure out which one is best for this image.
         if ($size <= 50) {
             $vanilliconSize = 50;
         } elseif ($size <= 100) {
             $vanilliconSize = 100;
         } else {
             $vanilliconSize = 200;
         }
         $default = "{$vanilliconBaseUrl}/{$avatarID}_{$vanilliconSize}.png";
     } else {
         $configuredDefaultAvatar = c('Plugins.Gravatar.DefaultAvatar', c('Garden.DefaultAvatar'));
         if ($configuredDefaultAvatar) {
             $defaultParsed = Gdn_Upload::parse($configuredDefaultAvatar);
             $default = val('Url', $defaultParsed);
         }
     }
     if (empty($default)) {
         $default = asset($size <= 50 ? 'plugins/Gravatar/default.png' : 'plugins/Gravatar/default_250.png', true);
     }
     $query = ['default' => $default, 'rating' => c('Plugins.Gravatar.Rating', 'g'), 'size' => $size];
     return $baseUrl . "/{$avatarID}/?" . http_build_query($query);
 }
 /**
  *
  *
  * @return LightOpenID
  */
 public function getOpenID()
 {
     $OpenID = new LightOpenID();
     if ($url = Gdn::request()->get('url')) {
         if (!filter_var($url, FILTER_VALIDATE_URL)) {
             throw new Gdn_UserException(sprintf(t('ValidateUrl'), 'OpenID'), 400);
         }
         // Don't allow open ID on a non-standard scheme.
         $scheme = parse_url($url, PHP_URL_SCHEME);
         if (!in_array($scheme, array('http', 'https'))) {
             throw new Gdn_UserException(sprintf(t('ValidateUrl'), 'OpenID'), 400);
         }
         // Don't allow open ID on a non-standard port.
         $port = parse_url($url, PHP_URL_PORT);
         if ($port && !in_array($port, array(80, 8080, 443))) {
             throw new Gdn_UserException(t('OpenID is not allowed on non-standard ports.'));
         }
         $OpenID->identity = $url;
     }
     $Url = url('/entry/connect/openid', true);
     $UrlParts = explode('?', $Url);
     parse_str(val(1, $UrlParts, ''), $Query);
     $Query = array_merge($Query, arrayTranslate($_GET, array('display', 'Target')));
     $OpenID->returnUrl = $UrlParts[0] . '?' . http_build_query($Query);
     $OpenID->required = array('contact/email', 'namePerson/first', 'namePerson/last', 'pref/language');
     $this->EventArguments['OpenID'] = $OpenID;
     $this->fireEvent('GetOpenID');
     return $OpenID;
 }
Example #5
0
 /**
  * Token-based, per-request authentication
  *
  * This method takes the entire request string and turns the query into an
  * array of data. It then uses all the data to generate a signature the same
  * way it got generated on the client. If the server signature and client
  * token match, the client is considered legimate and the request is served.
  *
  * Based on initial work by Diego Zanella
  * @link http://careers.stackoverflow.com/diegozanella
  *
  * @since  0.1.0
  * @access public
  * @throws Exception
  * @return void
  * @static
  */
 public static function authenticateRequest()
 {
     $username = getIncomingValue("username");
     $email = getIncomingValue("email");
     if (!$username && !$email) {
         throw new Exception(t("API.Error.User.Missing"), 401);
     }
     if (!($userID = static::getUserID($username, $email))) {
         throw new Exception(t("API.Error.User.Invalid"), 401);
     }
     if (!($timestamp = getIncomingValue("timestamp"))) {
         throw new Exception(t("API.Error.Timestamp.Missing"), 401);
     }
     // Make sure that request is still valid
     if (abs($timestamp - time()) > c("API.Expiration")) {
         throw new Exception(t("API.Error.Timestamp.Invalid"), 401);
     }
     if (!($token = getIncomingValue("token"))) {
         throw new Exception(t("API.Error.Token.Missing"), 401);
     }
     $parsedUrl = parse_url(Gdn::request()->pathAndQuery());
     // Turn the request query data into an array to be used in the token
     // generation
     parse_str(val("query", $parsedUrl, []), $data);
     // Unset the values we don't want to include in the token generation
     unset($data["token"], $data["DeliveryType"], $data["DeliveryMethod"]);
     if ($token != ($signature = static::generateSignature($data))) {
         throw new Exception(t("API.Error.Token.Invalid"), 401);
     }
     // Now that the client has been thoroughly verified, start a session for
     // the duration of the request using the User ID specified earlier
     if ($token == $signature) {
         Gdn::session()->start(intval($userID), false);
     }
 }
 function __construct()
 {
     $this->trustRoot = Gdn::request()->Scheme() . '://' . Gdn::request()->Host();
     $uri = rtrim(preg_replace('#((?<=\\?)|&)openid\\.[^&]+#', '', $_SERVER['REQUEST_URI']), '?');
     $this->returnUrl = $this->trustRoot . $uri;
     $this->data = $_POST + $_GET;
     # OPs may send data as POST or GET.
 }
Example #7
0
 /**
  * Returns the Request part of the current url. ie. "/controller/action/" in
  * "http://localhost/garden/index.php?/controller/action/".
  *
  * @param boolean $WithWebRoot
  * @param boolean $WithDomain
  * @param boolean $RemoveSyndication
  * @return string
  */
 public static function request($WithWebRoot = false, $WithDomain = false, $RemoveSyndication = false)
 {
     $Result = Gdn::request()->path();
     if ($WithWebRoot) {
         $Result = self::webRoot($WithDomain) . '/' . $Result;
     }
     return $Result;
 }
Example #8
0
    /**
     * Adds a "My Forums" menu option to the dashboard area.
     */
    public function settingsController_render_before($Sender)
    {
        // Have they visited their dashboard?
        if (strtolower($Sender->RequestMethod) != 'index') {
            $this->saveStep('Plugins.GettingStarted.Dashboard');
        }
        // Save the action if editing registration settings
        if (strcasecmp($Sender->RequestMethod, 'registration') == 0 && $Sender->Form->authenticatedPostBack() === true) {
            $this->saveStep('Plugins.GettingStarted.Registration');
        }
        // Save the action if they reviewed plugins
        if (strcasecmp($Sender->RequestMethod, 'plugins') == 0) {
            $this->saveStep('Plugins.GettingStarted.Plugins');
        }
        // Save the action if they reviewed plugins
        if (strcasecmp($Sender->RequestMethod, 'managecategories') == 0) {
            $this->saveStep('Plugins.GettingStarted.Categories');
        }
        // Add messages & their css on dashboard
        if (strcasecmp($Sender->RequestMethod, 'index') == 0) {
            $Sender->addCssFile('getting-started.css', 'plugins/GettingStarted');
            $Session = Gdn::session();
            $WelcomeMessage = '<div class="GettingStarted">' . anchor('×', '/dashboard/plugin/dismissgettingstarted/' . $Session->transientKey(), 'Dismiss') . "<h1>" . t("Here's how to get started:") . "</h1>" . '<ul>
      <li class="One' . (c('Plugins.GettingStarted.Dashboard', '0') == '1' ? ' Done' : '') . '">
	 <strong>' . anchor(t('Welcome to your Dashboard'), 'settings') . '</strong>
         <p>' . t('This is the administrative dashboard for your new community. Check out the configuration options to the left: from here you can configure how your community works. <b>Only users in the "Administrator" role can see this part of your community.</b>') . '</p>
      </li>
      <li class="Two' . (c('Plugins.GettingStarted.Discussions', '0') == '1' ? ' Done' : '') . '">
	 <strong>' . anchor(t("Where is your Community Forum?"), '/') . '</strong>
         <p>' . t('Access your community forum by clicking the "Visit Site" link on the top-left of this page, or by ') . anchor(t('clicking here'), '/') . t('. The community forum is what all of your users &amp; customers will see when they visit ') . anchor(Gdn::request()->Url('/', true), Gdn::request()->Url('/', true)) . '.</p>
      </li>
      <li class="Three' . (c('Plugins.GettingStarted.Categories', '0') == '1' ? ' Done' : '') . '">
         <strong>' . anchor(t('Organize your Categories'), 'vanilla/settings/managecategories') . '</strong>
         <p>' . t('Discussion categories are used to help your users organize their discussions in a way that is meaningful for your community.') . '</p>
      </li>
      <li class="Four' . (c('Plugins.GettingStarted.Profile', '0') == '1' ? ' Done' : '') . '">
         <strong>' . anchor(t('Customize your Public Profile'), 'profile') . '</strong>
         <p>' . t('Everyone who signs up for your community gets a public profile page where they can upload a picture of themselves, manage their profile settings, and track cool things going on in the community. You should ') . anchor(t('customize your profile now'), 'profile') . '.</p>
      </li>
      <li class="Five' . (c('Plugins.GettingStarted.Discussion', '0') == '1' ? ' Done' : '') . '">
         <strong>' . anchor(t('Start your First Discussion'), 'post/discussion') . '</strong>
	 <p>' . t('Get the ball rolling in your community by ') . anchor(t('starting your first discussion'), 'post/discussion') . t(' now.') . '</p>
      </li>
      <li class="Six' . (c('Plugins.GettingStarted.Plugins', '0') == '1' ? ' Done' : '') . '">
         <strong>' . anchor(t('Manage your Plugins'), 'settings/plugins') . '</strong>
         <p>' . t('Change the way your community works with plugins. We\'ve bundled popular plugins with the software, and there are more available online.') . '</p>
      </li>
   </ul>
</div>';
            $Sender->addAsset('Messages', $WelcomeMessage, 'WelcomeMessage');
        }
    }
Example #9
0
 /**
  *
  *
  * @param $Sender
  * @param $Args
  */
 public function profileController_afterAddSideMenu_handler($Sender, $Args)
 {
     if (!$Sender->User->Photo) {
         $Email = val('Email', $Sender->User);
         $Protocol = Gdn::request()->scheme() == 'https' ? 'https://secure.' : 'http://www.';
         $Url = $Protocol . 'gravatar.com/avatar.php?' . 'gravatar_id=' . md5(strtolower($Email)) . '&amp;size=' . c('Garden.Profile.MaxWidth', 200);
         if (c('Plugins.Gravatar.UseVanillicon', true)) {
             $Url .= '&default=' . urlencode(Gdn::request()->scheme() . '://vanillicon.com/' . md5($Email) . '_200.png');
         } else {
             $Url .= '&default=' . urlencode(asset(c('Plugins.Gravatar.DefaultAvatar', c('Garden.DefaultAvatar', 'plugins/Gravatar/default_250.png')), true));
         }
         $Sender->User->Photo = $Url;
     }
 }
 /**
  * Check whether or not the record is spam.
  * @param string $RecordType By default, this should be one of the following:
  *  - Comment: A comment.
  *  - Discussion: A discussion.
  *  - User: A user registration.
  * @param array $Data The record data.
  * @param array $Options Options for fine-tuning this method call.
  *  - Log: Log the record if it is found to be spam.
  */
 public static function isSpam($RecordType, $Data, $Options = array())
 {
     if (self::$Disabled) {
         return false;
     }
     // Set some information about the user in the data.
     if ($RecordType == 'Registration') {
         touchValue('Username', $Data, $Data['Name']);
     } else {
         touchValue('InsertUserID', $Data, Gdn::session()->UserID);
         $User = Gdn::userModel()->getID(val('InsertUserID', $Data), DATASET_TYPE_ARRAY);
         if ($User) {
             if (val('Verified', $User)) {
                 // The user has been verified and isn't a spammer.
                 return false;
             }
             touchValue('Username', $Data, $User['Name']);
             touchValue('Email', $Data, $User['Email']);
             touchValue('IPAddress', $Data, $User['LastIPAddress']);
         }
     }
     if (!isset($Data['Body']) && isset($Data['Story'])) {
         $Data['Body'] = $Data['Story'];
     }
     touchValue('IPAddress', $Data, Gdn::request()->ipAddress());
     $Sp = self::_Instance();
     $Sp->EventArguments['RecordType'] = $RecordType;
     $Sp->EventArguments['Data'] =& $Data;
     $Sp->EventArguments['Options'] =& $Options;
     $Sp->EventArguments['IsSpam'] = false;
     $Sp->fireEvent('CheckSpam');
     $Spam = $Sp->EventArguments['IsSpam'];
     // Log the spam entry.
     if ($Spam && val('Log', $Options, true)) {
         $LogOptions = array();
         switch ($RecordType) {
             case 'Registration':
                 $LogOptions['GroupBy'] = array('RecordIPAddress');
                 break;
             case 'Comment':
             case 'Discussion':
             case 'Activity':
             case 'ActivityComment':
                 $LogOptions['GroupBy'] = array('RecordID');
                 break;
         }
         LogModel::insert('Spam', $RecordType, $Data, $LogOptions);
     }
     return $Spam;
 }
Example #11
0
 /**
  *
  *
  * @return string
  */
 public function execute()
 {
     $SliceArgs = func_get_args();
     switch (count($SliceArgs)) {
         case 1:
             //die('slice request: '.$SliceArgs[0]);
             $Request = Gdn::request()->create()->fromEnvironment()->withURI($SliceArgs[0])->withDeliveryType(DELIVERY_TYPE_VIEW);
             ob_start();
             $this->Dispatcher->dispatch($Request, false);
             return ob_get_clean();
             break;
         case 2:
             break;
     }
 }
 /**
  * FlatCategoryModule constructor.
  *
  * @param string|Gdn_Controller $sender
  * @param bool|string $applicationFolder
  */
 public function __construct($sender = '', $applicationFolder = false)
 {
     parent::__construct($sender, $applicationFolder);
     $this->categoryModel = new CategoryModel();
     $this->limit = $this::DEFAULT_LIMIT;
     // If this is coming from the module controller, populate some properties by query parameters.
     if ($sender instanceof ModuleController) {
         $paramWhitelist = ['categoryID' => Gdn::request()->get('categoryID', Gdn::request()->get('CategoryID')), 'filter' => Gdn::request()->get('filter', Gdn::request()->get('Filter')), 'limit' => Gdn::request()->get('limit', Gdn::request()->get('Limit'))];
         foreach ($paramWhitelist as $property => $value) {
             if ($value) {
                 $this->{$property} = $value;
             }
         }
     }
 }
 /**
  * Set the preference in the user's session.
  */
 public function setToggle()
 {
     $Session = Gdn::session();
     if (!$Session->isValid()) {
         return;
     }
     $ShowAllCategories = GetIncomingValue('ShowAllCategories', '');
     if ($ShowAllCategories != '') {
         $ShowAllCategories = $ShowAllCategories == 'true' ? true : false;
         $ShowAllCategoriesPref = $Session->GetPreference('ShowAllCategories');
         if ($ShowAllCategories != $ShowAllCategoriesPref) {
             $Session->setPreference('ShowAllCategories', $ShowAllCategories);
         }
         redirect('/' . ltrim(Gdn::request()->Path(), '/'));
     }
 }
 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');
 }
Example #15
0
 /**
  *
  *
  * @param $SliceName
  * @param array $Arguments
  * @return Gdn_Slice
  */
 public function slice($SliceName, $Arguments = array())
 {
     $CurrentPath = Gdn::request()->path();
     $ExplodedPath = explode('/', $CurrentPath);
     switch ($this instanceof Gdn_IPlugin) {
         case true:
             $ReplacementIndex = 2;
             break;
         case false:
             $ReplacementIndex = 1;
             break;
     }
     if ($ExplodedPath[0] == strtolower(Gdn::dispatcher()->application()) && $ExplodedPath[1] == strtolower(Gdn::dispatcher()->controller())) {
         $ReplacementIndex++;
     }
     $ExplodedPath[$ReplacementIndex] = $SliceName;
     $SlicePath = implode('/', $ExplodedPath);
     return Gdn::Slice($SlicePath);
 }
Example #16
0
 /**
  *
  *
  * @param string $ID
  * @param string $ServeFile
  */
 public function index($ID = '', $ServeFile = '0')
 {
     $this->addJsFile('jquery.js');
     // Define the item being downloaded
     if (strtolower($ID) == 'vanilla') {
         $ID = 'vanilla-core';
     }
     $UrlFilename = Gdn::request()->filename();
     $PathInfo = pathinfo($UrlFilename);
     $Ext = val('extension', $PathInfo);
     if ($Ext == 'zip') {
         $ServeFile = '1';
         $ID = $Ext = val('filename', $PathInfo);
     }
     // Find the requested addon
     $this->Addon = $this->AddonModel->getSlug($ID, true);
     $this->setData('Addon', $this->Addon);
     if (!is_array($this->Addon) || !val('File', $this->Addon)) {
         $this->Addon = array('Name' => 'Not Found', 'Version' => 'undefined', 'File' => '');
     } else {
         $AddonID = $this->Addon['AddonID'];
         if ($ServeFile != '1') {
             $this->addJsFile('get.js');
         }
         if ($ServeFile == '1') {
             // Record this download
             $this->Database->sql()->insert('Download', array('AddonID' => $AddonID, 'DateInserted' => Gdn_Format::toDateTime(), 'RemoteIp' => @$_SERVER['REMOTE_ADDR']));
             $this->AddonModel->setProperty($AddonID, 'CountDownloads', $this->Addon['CountDownloads'] + 1);
             if (val('Slug', $this->Addon)) {
                 $Filename = $this->Addon['Slug'];
             } else {
                 $Filename = "{$this->Addon['Name']}-{$this->Addon['Version']}";
             }
             $Filename = Gdn_Format::url($Filename) . '.zip';
             $File = $this->Addon['File'];
             $Url = Gdn_Upload::url($File);
             Gdn_FileSystem::serveFile($Url, $Filename);
         }
     }
     $this->addModule('AddonHelpModule');
     $this->render();
 }
Example #17
0
 /**
  * Settings screen placeholder
  *
  * @param mixed $Sender
  */
 public function Controller_Index($Sender)
 {
     Gdn_Theme::section('Moderation');
     $Sender->Permission('Garden.Settings.Manage');
     $Sender->Title('Community Reporting');
     $Sender->AddCssFile('reporting.css', 'plugins/Reporting');
     // Check to see if the admin is toggling a feature
     $Feature = GetValue('1', $Sender->RequestArgs);
     $Command = GetValue('2', $Sender->RequestArgs);
     $TransientKey = Gdn::request()->get('TransientKey');
     if (Gdn::Session()->ValidateTransientKey($TransientKey)) {
         if (in_array($Feature, array('awesome', 'report'))) {
             SaveToConfig('Plugins.Reporting.' . ucfirst($Feature) . 'Enabled', $Command == 'disable' ? FALSE : TRUE);
             Redirect('plugin/reporting');
         }
     }
     $CategoryModel = new CategoryModel();
     $Sender->SetData('Plugins.Reporting.Data', array('ReportEnabled' => $this->ReportEnabled, 'AwesomeEnabled' => $this->AwesomeEnabled));
     $Sender->Render($this->GetView('settings.php'));
 }
 /**
  * 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');
 }
 /**
  * Save uploads.
  *
  * @param $id
  * @param $type
  */
 public function saveUploads($id, $type)
 {
     // Array of Media IDs, as input is MediaIDs[]
     $mediaIds = (array) Gdn::request()->getValue('MediaIDs');
     if (count($mediaIds)) {
         foreach ($mediaIds as $mediaId) {
             $this->attachEditorUploads($mediaId, $id, $type);
         }
     }
     // Array of Media IDs to remove, if any.
     $removeMediaIds = (array) Gdn::request()->getValue('RemoveMediaIDs');
     // Clean it if it's empty.
     $removeMediaIds = array_filter($removeMediaIds);
     if (count($removeMediaIds)) {
         foreach ($removeMediaIds as $mediaId) {
             $this->deleteEditorUploads($mediaId, $id, $type);
         }
     }
 }
 /**
  * Builds and returns an anchor tag.
  */
 function anchor($Text, $Destination = '', $CssClass = '', $Attributes = array(), $ForceAnchor = false)
 {
     if (!is_array($CssClass) && $CssClass != '') {
         $CssClass = array('class' => $CssClass);
     }
     if ($Destination == '' && $ForceAnchor === false) {
         return $Text;
     }
     if (!is_array($Attributes)) {
         $Attributes = array();
     }
     $SSL = null;
     if (isset($Attributes['SSL'])) {
         $SSL = $Attributes['SSL'];
         unset($Attributes['SSL']);
     }
     $WithDomain = false;
     if (isset($Attributes['WithDomain'])) {
         $WithDomain = $Attributes['WithDomain'];
         unset($Attributes['WithDomain']);
     }
     $Prefix = substr($Destination, 0, 7);
     if (!in_array($Prefix, array('https:/', 'http://', 'mailto:')) && ($Destination != '' || $ForceAnchor === false)) {
         $Destination = Gdn::request()->url($Destination, $WithDomain, $SSL);
     }
     return '<a href="' . htmlspecialchars($Destination, ENT_COMPAT, C('Garden.Charset', 'UTF-8')) . '"' . Attribute($CssClass) . Attribute($Attributes) . '>' . $Text . '</a>';
 }
 /**
  *
  *
  * @param $Path
  * @param $Controller
  */
 public function init($Path, $Controller)
 {
     $Smarty = $this->smarty();
     // Get a friendly name for the controller.
     $ControllerName = get_class($Controller);
     if (StringEndsWith($ControllerName, 'Controller', true)) {
         $ControllerName = substr($ControllerName, 0, -10);
     }
     // Get an ID for the body.
     $BodyIdentifier = strtolower($Controller->ApplicationFolder . '_' . $ControllerName . '_' . Gdn_Format::alphaNumeric(strtolower($Controller->RequestMethod)));
     $Smarty->assign('BodyID', $BodyIdentifier);
     //$Smarty->assign('Config', Gdn::Config());
     // Assign some information about the user.
     $Session = Gdn::session();
     if ($Session->isValid()) {
         $User = array('Name' => $Session->User->Name, 'Photo' => '', 'CountNotifications' => (int) val('CountNotifications', $Session->User, 0), 'CountUnreadConversations' => (int) val('CountUnreadConversations', $Session->User, 0), 'SignedIn' => true);
         $Photo = $Session->User->Photo;
         if ($Photo) {
             if (!IsUrl($Photo)) {
                 $Photo = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s'));
             }
         } else {
             if (function_exists('UserPhotoDefaultUrl')) {
                 $Photo = UserPhotoDefaultUrl($Session->User, 'ProfilePhoto');
             } elseif ($ConfigPhoto = C('Garden.DefaultAvatar')) {
                 $Photo = Gdn_Upload::url($ConfigPhoto);
             } else {
                 $Photo = Asset('/applications/dashboard/design/images/defaulticon.png', true);
             }
         }
         $User['Photo'] = $Photo;
     } else {
         $User = false;
         /*array(
           'Name' => '',
           'CountNotifications' => 0,
           'SignedIn' => FALSE);*/
     }
     $Smarty->assign('User', $User);
     // Make sure that any datasets use arrays instead of objects.
     foreach ($Controller->Data as $Key => $Value) {
         if ($Value instanceof Gdn_DataSet) {
             $Controller->Data[$Key] = $Value->resultArray();
         } elseif ($Value instanceof stdClass) {
             $Controller->Data[$Key] = (array) $Value;
         }
     }
     $BodyClass = val('CssClass', $Controller->Data, '', true);
     $Sections = Gdn_Theme::section(null, 'get');
     if (is_array($Sections)) {
         foreach ($Sections as $Section) {
             $BodyClass .= ' Section-' . $Section;
         }
     }
     $Controller->Data['BodyClass'] = $BodyClass;
     // Set the current locale for themes to take advantage of.
     $Locale = Gdn::locale()->Locale;
     $CurrentLocale = array('Key' => $Locale, 'Lang' => str_replace('_', '-', $Locale));
     if (class_exists('Locale')) {
         $CurrentLocale['Language'] = Locale::getPrimaryLanguage($Locale);
         $CurrentLocale['Region'] = Locale::getRegion($Locale);
         $CurrentLocale['DisplayName'] = Locale::getDisplayName($Locale, $Locale);
         $CurrentLocale['DisplayLanguage'] = Locale::getDisplayLanguage($Locale, $Locale);
         $CurrentLocale['DisplayRegion'] = Locale::getDisplayRegion($Locale, $Locale);
     }
     $Smarty->assign('CurrentLocale', $CurrentLocale);
     $Smarty->assign('Assets', (array) $Controller->Assets);
     $Smarty->assign('Path', Gdn::request()->path());
     // Assign the controller data last so the controllers override any default data.
     $Smarty->assign($Controller->Data);
     $Smarty->Controller = $Controller;
     // for smarty plugins
     $Smarty->security = true;
     $Smarty->security_settings['IF_FUNCS'] = array_merge($Smarty->security_settings['IF_FUNCS'], array('Category', 'CheckPermission', 'InSection', 'InCategory', 'MultiCheckPermission', 'GetValue', 'SetValue', 'Url'));
     $Smarty->security_settings['MODIFIER_FUNCS'] = array_merge($Smarty->security_settings['MODIFIER_FUNCS'], array('sprintf'));
     $Smarty->secure_dir = array($Path);
 }
Example #22
0
    $Filename = val($this->data('ImportPath'), $ImportPaths);
} else {
    $Filename = '';
}
//$Filename = val('OriginalFilename', $this->Data);
if ($Filename) {
    $Header[T('Source')] = $Filename;
}
$Header = array_merge($Header, (array) GetValue('Header', $this->Data, array()));
$Stats = (array) GetValue('Stats', $this->Data, array());
$Info = array_merge($Header, $Stats);
foreach ($Info as $Name => $Value) {
    switch ($Name) {
        case 'Orphaned Comments':
        case 'Orphaned Discussions':
            $Value .= ' ' . anchor(t('Click here to fix.'), Gdn::request()->Url('dba/fixinsertuserid'));
            break;
        default:
            $Name = htmlspecialchars($Name);
            $Value = htmlspecialchars($Value);
            if (substr_compare('Time', $Name, 0, 4, true) == 0) {
                $Value = Gdn_Timer::FormatElapsed($Value);
            }
    }
    echo "<tr><th>{$Name}</th><td class=\"Alt\">{$Value}</td></tr>\n";
}
if ($this->data('GenerateSQL')) {
    echo "<tr><th>" . t('Special') . "</th><td class=\"Alt\">" . t('Generate import SQL only') . "</td></tr>\n";
}
?>
</table>
 /**
  *
  *
  * @param null $NewValue
  * @return null|string
  */
 public function redirectUri($NewValue = null)
 {
     if ($NewValue !== null) {
         $this->_RedirectUri = $NewValue;
     } elseif ($this->_RedirectUri === null) {
         $RedirectUri = url('/entry/connect/facebook', true);
         if (strpos($RedirectUri, '=') !== false) {
             $p = strrchr($RedirectUri, '=');
             $Uri = substr($RedirectUri, 0, -strlen($p));
             $p = urlencode(ltrim($p, '='));
             $RedirectUri = $Uri . '=' . $p;
         }
         $Path = Gdn::request()->path();
         $Target = val('Target', $_GET, $Path ? $Path : '/');
         // TODO rm global
         if (ltrim($Target, '/') == 'entry/signin' || empty($Target)) {
             $Target = '/';
         }
         $Args = array('Target' => $Target);
         $RedirectUri .= strpos($RedirectUri, '?') === false ? '?' : '&';
         $RedirectUri .= http_build_query($Args);
         $this->_RedirectUri = $RedirectUri;
     }
     return $this->_RedirectUri;
 }
 /**
  * Main import page.
  *
  * @since 2.0.0
  * @access public
  */
 public function index()
 {
     $this->permission('Garden.Import');
     // This permission doesn't exist, so only users with Admin == '1' will succeed.
     $Timer = new Gdn_Timer();
     // Determine the current step.
     $this->Form = new Gdn_Form();
     $Imp = new ImportModel();
     $Imp->loadState();
     // Search for the list of acceptable imports.
     $ImportPaths = array();
     $ExistingPaths = SafeGlob(PATH_UPLOADS . '/export*', array('gz', 'txt'));
     $ExistingPaths2 = SafeGlob(PATH_UPLOADS . '/porter/export*', array('gz'));
     $ExistingPaths = array_merge($ExistingPaths, $ExistingPaths2);
     foreach ($ExistingPaths as $Path) {
         $ImportPaths[$Path] = basename($Path);
     }
     // Add the database as a path.
     $ImportPaths = array_merge(array('db:' => t('This Database')), $ImportPaths);
     if ($Imp->CurrentStep < 1) {
         // Check to see if there is a file.
         $ImportPath = c('Garden.Import.ImportPath');
         $Validation = new Gdn_Validation();
         if (strcasecmp(Gdn::request()->requestMethod(), 'post') == 0) {
             $Upload = new Gdn_Upload();
             $Validation = new Gdn_Validation();
             if (count($ImportPaths) > 0) {
                 $Validation->applyRule('PathSelect', 'Required', t('You must select a file to import.'));
             }
             if (count($ImportPaths) == 0 || $this->Form->getFormValue('PathSelect') == 'NEW') {
                 $TmpFile = $Upload->ValidateUpload('ImportFile', false);
             } else {
                 $TmpFile = '';
             }
             if ($TmpFile) {
                 $Filename = $_FILES['ImportFile']['name'];
                 $Extension = pathinfo($Filename, PATHINFO_EXTENSION);
                 $TargetFolder = PATH_ROOT . DS . 'uploads' . DS . 'import';
                 if (!file_exists($TargetFolder)) {
                     mkdir($TargetFolder, 0777, true);
                 }
                 $ImportPath = $Upload->GenerateTargetName(PATH_ROOT . DS . 'uploads' . DS . 'import', $Extension);
                 $Upload->SaveAs($TmpFile, $ImportPath);
                 $Imp->ImportPath = $ImportPath;
                 $this->Form->setFormValue('PathSelect', $ImportPath);
                 $UploadedFiles = val('UploadedFiles', $Imp->Data);
                 $UploadedFiles[$ImportPath] = basename($Filename);
                 $Imp->Data['UploadedFiles'] = $UploadedFiles;
             } elseif ($PathSelect = $this->Form->getFormValue('PathSelect')) {
                 if ($PathSelect == 'NEW') {
                     $Validation->addValidationResult('ImportFile', 'ValidateRequired');
                 } else {
                     $Imp->ImportPath = $PathSelect;
                 }
             } elseif (!$Imp->ImportPath && count($ImportPaths) == 0) {
                 // There was no file uploaded this request or before.
                 $Validation->addValidationResult('ImportFile', $Upload->Exception);
             }
             // Validate the overwrite.
             if (true || strcasecmp($this->Form->getFormValue('Overwrite'), 'Overwrite') == 0) {
                 if (!stringBeginsWith($this->Form->getFormValue('PathSelect'), 'Db:', true)) {
                     $Validation->applyRule('Email', 'Required');
                 }
             }
             if ($Validation->validate($this->Form->formValues())) {
                 $this->Form->setFormValue('Overwrite', 'overwrite');
                 $Imp->fromPost($this->Form->formValues());
                 $this->View = 'Info';
             } else {
                 $this->Form->setValidationResults($Validation->results());
             }
         } else {
             $this->Form->setFormValue('PathSelect', $Imp->ImportPath);
         }
         $Imp->saveState();
     } else {
         $this->setData('Steps', $Imp->steps());
         $this->View = 'Info';
     }
     if (!stringBeginsWith($Imp->ImportPath, 'db:') && !file_exists($Imp->ImportPath)) {
         $Imp->deleteState();
     }
     try {
         $UploadedFiles = val('UploadedFiles', $Imp->Data, array());
         $ImportPaths = array_merge($ImportPaths, $UploadedFiles);
         $this->setData('ImportPaths', $ImportPaths);
         $this->setData('Header', $Imp->getImportHeader());
         $this->setData('Stats', val('Stats', $Imp->Data, array()));
         $this->setData('GenerateSQL', val('GenerateSQL', $Imp->Data));
         $this->setData('ImportPath', $Imp->ImportPath);
         $this->setData('OriginalFilename', val('OriginalFilename', $Imp->Data));
         $this->setData('CurrentStep', $Imp->CurrentStep);
         $this->setData('LoadSpeedWarning', $Imp->loadTableType(false) == 'LoadTableWithInsert');
     } catch (Gdn_UserException $Ex) {
         $this->Form->addError($Ex);
         $Imp->saveState();
         $this->View = 'Index';
     }
     $this->render();
 }
Example #25
0
 /**
  *
  *
  * @param $Path
  * @param bool $Text
  * @param null $Format
  * @param array $Options
  * @return mixed|null|string
  */
 public static function link($Path, $Text = false, $Format = null, $Options = array())
 {
     $Session = Gdn::session();
     $Class = val('class', $Options, '');
     $WithDomain = val('WithDomain', $Options);
     $Target = val('Target', $Options, '');
     if ($Target == 'current') {
         $Target = trim(url('', true), '/ ');
     }
     if (is_null($Format)) {
         $Format = '<a href="%url" class="%class">%text</a>';
     }
     switch ($Path) {
         case 'activity':
             touchValue('Permissions', $Options, 'Garden.Activity.View');
             break;
         case 'category':
             $Breadcrumbs = Gdn::controller()->data('Breadcrumbs');
             if (is_array($Breadcrumbs) && count($Breadcrumbs) > 0) {
                 $Last = array_pop($Breadcrumbs);
                 $Path = val('Url', $Last);
                 $DefaultText = val('Name', $Last, T('Back'));
             } else {
                 $Path = '/';
                 $DefaultText = c('Garden.Title', T('Back'));
             }
             if (!$Text) {
                 $Text = $DefaultText;
             }
             break;
         case 'dashboard':
             $Path = 'dashboard/settings';
             touchValue('Permissions', $Options, array('Garden.Settings.Manage', 'Garden.Settings.View'));
             if (!$Text) {
                 $Text = t('Dashboard');
             }
             break;
         case 'home':
             $Path = '/';
             if (!$Text) {
                 $Text = t('Home');
             }
             break;
         case 'inbox':
             $Path = 'messages/inbox';
             touchValue('Permissions', $Options, 'Garden.SignIn.Allow');
             if (!$Text) {
                 $Text = t('Inbox');
             }
             if ($Session->isValid() && $Session->User->CountUnreadConversations) {
                 $Class = trim($Class . ' HasCount');
                 $Text .= ' <span class="Alert">' . $Session->User->CountUnreadConversations . '</span>';
             }
             if (!$Session->isValid() || !Gdn::applicationManager()->checkApplication('Conversations')) {
                 $Text = false;
             }
             break;
         case 'forumroot':
             $Route = Gdn::router()->getDestination('DefaultForumRoot');
             if (is_null($Route)) {
                 $Path = '/';
             } else {
                 $Path = combinePaths(array('/', $Route));
             }
             break;
         case 'profile':
             touchValue('Permissions', $Options, 'Garden.SignIn.Allow');
             if (!$Text && $Session->isValid()) {
                 $Text = $Session->User->Name;
             }
             if ($Session->isValid() && $Session->User->CountNotifications) {
                 $Class = trim($Class . ' HasCount');
                 $Text .= ' <span class="Alert">' . $Session->User->CountNotifications . '</span>';
             }
             break;
         case 'user':
             $Path = 'profile';
             touchValue('Permissions', $Options, 'Garden.SignIn.Allow');
             if (!$Text && $Session->isValid()) {
                 $Text = $Session->User->Name;
             }
             break;
         case 'photo':
             $Path = 'profile';
             TouchValue('Permissions', $Options, 'Garden.SignIn.Allow');
             if (!$Text && $Session->isValid()) {
                 $IsFullPath = strtolower(substr($Session->User->Photo, 0, 7)) == 'http://' || strtolower(substr($Session->User->Photo, 0, 8)) == 'https://';
                 $PhotoUrl = $IsFullPath ? $Session->User->Photo : Gdn_Upload::url(changeBasename($Session->User->Photo, 'n%s'));
                 $Text = img($PhotoUrl, array('alt' => $Session->User->Name));
             }
             break;
         case 'drafts':
             TouchValue('Permissions', $Options, 'Garden.SignIn.Allow');
             if (!$Text) {
                 $Text = t('My Drafts');
             }
             if ($Session->isValid() && $Session->User->CountDrafts) {
                 $Class = trim($Class . ' HasCount');
                 $Text .= ' <span class="Alert">' . $Session->User->CountDrafts . '</span>';
             }
             break;
         case 'discussions/bookmarked':
             TouchValue('Permissions', $Options, 'Garden.SignIn.Allow');
             if (!$Text) {
                 $Text = t('My Bookmarks');
             }
             if ($Session->isValid() && $Session->User->CountBookmarks) {
                 $Class = trim($Class . ' HasCount');
                 $Text .= ' <span class="Count">' . $Session->User->CountBookmarks . '</span>';
             }
             break;
         case 'discussions/mine':
             TouchValue('Permissions', $Options, 'Garden.SignIn.Allow');
             if (!$Text) {
                 $Text = t('My Discussions');
             }
             if ($Session->isValid() && $Session->User->CountDiscussions) {
                 $Class = trim($Class . ' HasCount');
                 $Text .= ' <span class="Count">' . $Session->User->CountDiscussions . '</span>';
             }
             break;
         case 'register':
             if (!$Text) {
                 $Text = t('Register');
             }
             $Path = registerUrl($Target);
             break;
         case 'signin':
         case 'signinout':
             // The destination is the signin/signout toggle link.
             if ($Session->isValid()) {
                 if (!$Text) {
                     $Text = T('Sign Out');
                 }
                 $Path = signOutUrl($Target);
                 $Class = concatSep(' ', $Class, 'SignOut');
             } else {
                 if (!$Text) {
                     $Text = t('Sign In');
                 }
                 $Path = signInUrl($Target);
                 if (signInPopup() && strpos(Gdn::Request()->Url(), 'entry') === false) {
                     $Class = concatSep(' ', $Class, 'SignInPopup');
                 }
             }
             break;
     }
     if ($Text == false && strpos($Format, '%text') !== false) {
         return '';
     }
     if (val('Permissions', $Options) && !$Session->checkPermission($Options['Permissions'], false)) {
         return '';
     }
     $Url = Gdn::request()->url($Path, $WithDomain);
     if ($TK = val('TK', $Options)) {
         if (in_array($TK, array(1, 'true'))) {
             $TK = 'TransientKey';
         }
         $Url .= (strpos($Url, '?') === false ? '?' : '&') . $TK . '=' . urlencode(Gdn::session()->transientKey());
     }
     if (strcasecmp(trim($Path, '/'), Gdn::request()->path()) == 0) {
         $Class = concatSep(' ', $Class, 'Selected');
     }
     // Build the final result.
     $Result = $Format;
     $Result = str_replace('%url', $Url, $Result);
     $Result = str_replace('%text', $Text, $Result);
     $Result = str_replace('%class', $Class, $Result);
     return $Result;
 }
 /**
  *
  *
  * @throws Exception
  * @throws Gdn_UserException
  */
 public function save()
 {
     $this->permission('Garden.Users.Edit');
     if (!Gdn::request()->isAuthenticatedPostBack()) {
         throw new Exception('Requires POST', 405);
     }
     $Form = new Gdn_Form();
     if ($SSOString = $Form->getFormValue('SSOString')) {
         $Parts = explode(' ', $SSOString);
         $String = $Parts[0];
         $Data = json_decode(base64_decode($String), true);
         $User = arrayTranslate($Data, array('name' => 'Name', 'email' => 'Email', 'photourl' => 'Photo', 'client_id' => 'ClientID', 'uniqueid' => 'UniqueID'));
     } else {
         $User = $Form->formValues();
     }
     if (!isset($User['UserID']) && isset($User['UniqueID'])) {
         // Try and find the user based on SSO.
         $Auth = Gdn::userModel()->getAuthentication($User['UniqueID'], $User['ClientID']);
         if ($Auth) {
             $User['UserID'] = $Auth['UserID'];
         }
     }
     if (!isset($User['UserID'])) {
         // Add some default values to make saving easier.
         if (!isset($User['RoleID'])) {
             $DefaultRoles = RoleModel::getDefaultRoles(RoleModel::TYPE_MEMBER);
             $User['RoleID'] = $DefaultRoles;
         } elseif (is_numeric($User['RoleID'])) {
             // UserModel->save() demands an array for RoleID.
             $User['RoleID'] = array($User['RoleID']);
         }
         if (!isset($User['Password'])) {
             $User['Password'] = md5(microtime());
             $User['HashMethod'] = 'Random';
         }
     }
     $UserID = Gdn::userModel()->save($User, array('SaveRoles' => isset($User['RoleID']), 'NoConfirmEmail' => true));
     if ($UserID) {
         if (!isset($User['UserID'])) {
             $User['UserID'] = $UserID;
         }
         if (isset($User['ClientID']) && isset($User['UniqueID'])) {
             Gdn::userModel()->saveAuthentication(array('UserID' => $User['UserID'], 'Provider' => $User['ClientID'], 'UniqueID' => $User['UniqueID']));
         }
         $this->setData('User', $User);
     } else {
         throw new Gdn_UserException(Gdn::userModel()->Validation->resultsText());
     }
     $this->render('Blank', 'Utility');
 }
 /**
  * Context-aware call to setcookie().
  *
  * This method is context-aware and will avoid setting cookies if the request
  * context is not HTTP.
  *
  * @param string $name
  * @param string $value
  * @param integer $expire
  * @param string $path
  * @param string $domain
  * @param boolean|null $secure
  * @param boolean $httponly
  */
 function safeCookie($name, $value = null, $expire = 0, $path = null, $domain = null, $secure = null, $httponly = false)
 {
     static $context = null;
     if (is_null($context)) {
         $context = requestContext();
     }
     if ($context == 'http') {
         if ($secure === null && c('Garden.ForceSSL') && Gdn::request()->scheme() === 'https') {
             $secure = true;
         }
         setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
     }
 }
 /**
  * Delete an activity item.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $ActivityID Unique ID of item to delete.
  * @param string $TransientKey Verify intent.
  */
 public function delete($ActivityID = '', $TransientKey = '')
 {
     $session = Gdn::session();
     if (!$session->validateTransientKey($TransientKey)) {
         throw permissionException();
     }
     if (!is_numeric($ActivityID)) {
         throw Gdn_UserException('Invalid ID');
     }
     if (!$this->ActivityModel->canDelete($this->ActivityModel->getID($ActivityID))) {
         throw permissionException();
     }
     $this->ActivityModel->deleteID($ActivityID);
     if ($this->_DeliveryType === DELIVERY_TYPE_ALL) {
         $target = Gdn::request()->get('Target');
         if ($target) {
             // Bail with a redirect if we got one.
             redirect($target);
         } else {
             // We got this as a full page somehow, so send them back to /activity.
             $this->RedirectUrl = url('activity');
         }
     }
     $this->render();
 }
Example #29
0
 /**
  * Allows the explicit definition of the email's sender address & name.
  * Defaults to the applications Configuration 'SupportEmail' & 'SupportName' settings respectively.
  *
  * @param string $SenderEmail
  * @param string $SenderName
  * @return Email
  */
 public function from($SenderEmail = '', $SenderName = '', $bOverrideSender = false)
 {
     if ($SenderEmail == '') {
         $SenderEmail = c('Garden.Email.SupportAddress', '');
         if (!$SenderEmail) {
             $SenderEmail = 'noreply@' . Gdn::request()->host();
         }
     }
     if ($SenderName == '') {
         $SenderName = c('Garden.Email.SupportName', c('Garden.Title', ''));
     }
     if ($this->PhpMailer->Sender == '' || $bOverrideSender) {
         $this->PhpMailer->Sender = $SenderEmail;
     }
     ob_start();
     $this->PhpMailer->setFrom($SenderEmail, $SenderName, false);
     ob_end_clean();
     return $this;
 }
Example #30
0
 /**
  * Checks if a url is saved as a navigation preference and if so, deletes it.
  * Also optionally resets the section dashboard landing page, which may be desirable if a user no longer has
  * permission to access pages in that section.
  *
  * @param string $url The url to search the user navigation preferences for, defaults to the request
  * @param string $userID The ID of the user to clear the preferences for, defaults to the sessioned user
  * @param bool $resetSectionPreference Whether to reset the dashboard section landing page
  */
 public function clearSectionNavigationPreference($url = '', $userID = '', $resetSectionPreference = true)
 {
     if (!$userID) {
         $userID = Gdn::session()->UserID;
     }
     if ($url == '') {
         $url = Gdn::request()->url();
     }
     $user = $this->getID($userID);
     $preferences = val('Preferences', $user, []);
     $landingPages = val('DashboardNav.SectionLandingPages', $preferences, []);
     // Run through the user's saved landing page per section and if the url matches the passed url,
     // remove that preference.
     foreach ($landingPages as $section => $landingPage) {
         $url = strtolower(trim($url, '/'));
         $landingPage = strtolower(trim($landingPage, '/'));
         if ($url == $landingPage || stringEndsWith($url, $landingPage)) {
             unset($landingPages[$section]);
         }
     }
     $this->savePreference($userID, 'DashboardNav.SectionLandingPages', $landingPages);
     if ($resetSectionPreference) {
         $this->savePreference($userID, 'DashboardNav.DashboardLandingPage', '');
     }
 }