Inheritance: extends Gdn_Pluggable
Ejemplo n.º 1
0
 /**
  * Manage the current ranks and add new ones
  */
 public function Settings()
 {
     $this->Permission('Yaga.Ranks.Manage');
     $this->AddSideMenu('rank/settings');
     $this->Title(T('Yaga.Ranks.Manage'));
     // Get list of ranks from the model and pass to the view
     $this->SetData('Ranks', $this->RankModel->Get());
     if ($this->Form->IsPostBack() == TRUE) {
         // Handle the photo upload
         $Upload = new Gdn_Upload();
         $TmpImage = $Upload->ValidateUpload('PhotoUpload', FALSE);
         if ($TmpImage) {
             // Generate the target image name
             $TargetImage = $Upload->GenerateTargetName(PATH_UPLOADS);
             $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
             // Save the uploaded image
             $Parts = $Upload->SaveAs($TmpImage, 'yaga' . DS . $ImageBaseName);
             $RelativeUrl = StringBeginsWith($Parts['Url'], Gdn_Url::WebRoot(TRUE), TRUE, TRUE);
             SaveToConfig('Yaga.Ranks.Photo', $RelativeUrl);
             if (C('Yaga.Ranks.Photo') == $Parts['SaveName']) {
                 $this->InformMessage(T('Yaga.Rank.PhotoUploaded'));
             }
         }
     }
     include_once $this->FetchViewLocation('helper_functions', 'rank');
     $this->Render();
 }
Ejemplo n.º 2
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);
 }
Ejemplo n.º 3
0
/**
 *
 *
 * @param $Data
 */
function _checkTable($Data)
{
    echo "<table class='Data' width='100%' style='table-layout: fixed;'>\n";
    echo "<thead><tr><td width='20%'>Field</td><td width='45%'>Current</td><td width='35%'>File</td></tr></thead>";
    $First = true;
    foreach ($Data as $Key => $Value) {
        if (stringBeginsWith($Key, 'File_') || is_array($Value) || $Key == 'Name') {
            continue;
        }
        $Value = Gdn_Format::html($Value);
        $FileValue = Gdn_Format::html(val('File_' . $Key, $Data));
        if ($Key == 'MD5') {
            $Value = substr($Value, 0, 10);
            $FileValue = substr($FileValue, 0, 10);
        }
        if ($Key == 'FileSize') {
            $Value = Gdn_Upload::FormatFileSize($Value);
        }
        echo "<tr><td>{$Key}</td><td>{$Value}</td>";
        if ($Error = val('File_Error', $Data)) {
            if ($First) {
                echo '<td rowspan="4">', htmlspecialchars($Error), '</td>';
            }
        } else {
            echo "<td>{$FileValue}</td></tr>";
        }
        echo "\n";
        $First = false;
    }
    echo '</table>';
}
Ejemplo n.º 4
0
 /**
  * Validates the uploaded image. Returns the temporary name of the uploaded file.
  */
 public function ValidateUpload($InputName)
 {
     // Make sure that all standard file upload checks are performed.
     $TmpFileName = parent::ValidateUpload($InputName);
     // Now perform image-specific checks
     $Size = getimagesize($TmpFileName);
     if ($Size === FALSE) {
         throw new Exception(Gdn::Translate('The uploaded file was not an image.'));
     }
     return $TmpFileName;
 }
Ejemplo n.º 5
0
 /**
  * Validates the uploaded image. Returns the temporary name of the uploaded file.
  */
 public function ValidateUpload($InputName)
 {
     if (!function_exists('gd_info')) {
         throw new Exception(T('The uploaded file could not be processed because GD is not installed.'));
     }
     // Make sure that all standard file upload checks are performed.
     $TmpFileName = parent::ValidateUpload($InputName);
     // Now perform image-specific checks
     $Size = getimagesize($TmpFileName);
     if ($Size === FALSE) {
         throw new Exception(T('The uploaded file was not an image.'));
     }
     return $TmpFileName;
 }
function WriteDiscussion($Discussion, &$Sender, &$Session, $Alt) {
   $CssClass = 'Item';
   $CssClass .= $Discussion->Bookmarked == '1' ? ' Bookmarked' : '';
   $CssClass .= $Alt.' ';
   $CssClass .= $Discussion->Announce == '1' ? ' Announcement' : '';
   $CssClass .= $Discussion->Closed == '1' ? ' Closed' : '';
   $CssClass .= $Discussion->InsertUserID == $Session->UserID ? ' Mine' : '';
   $CssClass .= ($Discussion->CountUnreadComments > 0 && $Session->IsValid()) ? ' New' : '';
   $Sender->EventArguments['Discussion'] = &$Discussion;
   $Sender->FireEvent('BeforeDiscussionName');
   
   $DiscussionName = Gdn_Format::Text($Discussion->Name);
   if ($DiscussionName == '')
      $DiscussionName = T('Blank Discussion Topic');

   static $FirstDiscussion = TRUE;
   if (!$FirstDiscussion)
      $Sender->FireEvent('BetweenDiscussion');
   else
      $FirstDiscussion = FALSE;
?>
<li class="<?php echo $CssClass; ?>">
   <?php
      if ($Discussion->FirstPhoto) {
         $PhotoImage = 'n'.basename($Discussion->FirstPhoto);
         $PhotoUrl = Gdn_Upload::Url(dirname($Discussion->FirstPhoto).'/'.$PhotoImage);
         echo Img($PhotoUrl, array('alt' => $Discussion->FirstName));
		}
   ?>
   <div class="ItemContent Discussion">
      <?php echo Anchor($DiscussionName, '/discussion/'.$Discussion->DiscussionID.'/'.Gdn_Format::Url($Discussion->Name).($Discussion->CountCommentWatch > 0 && C('Vanilla.Comments.AutoOffset') ? '/#Item_'.$Discussion->CountCommentWatch : ''), 'Title'); ?>
      <?php $Sender->FireEvent('AfterDiscussionTitle'); ?>
      <div class="Meta">
         <span class="Author"><?php echo $Discussion->FirstName; ?></span>
         <?php
            echo '<span class="Counts'.($Discussion->CountUnreadComments > 0 ? ' NewCounts' : '').'">'
               .($Discussion->CountUnreadComments > 0 ? $Discussion->CountUnreadComments.'/' : '')
               .$Discussion->CountComments
            .'</span>';
            if ($Discussion->LastCommentID != '')
               echo '<span class="LastCommentBy">'.sprintf(T('Latest %1$s'), $Discussion->LastName).'</span> ';
               
            echo '<span class="LastCommentDate">'.Gdn_Format::Date($Discussion->LastDate).'</span> ';
         ?>
      </div>
   </div>
</li>
<?php
}
Ejemplo n.º 7
0
 /**
  * Import a Yaga transport file
  */
 public function Import()
 {
     $this->Title(T('Yaga.Import'));
     $this->SetData('TransportType', 'Import');
     if (!class_exists('ZipArchive')) {
         $this->Form->AddError(T('Yaga.Error.TransportRequirements'));
     }
     if ($this->Form->IsPostBack() == TRUE) {
         // Handle the file upload
         $Upload = new Gdn_Upload();
         $TmpZip = $Upload->ValidateUpload('FileUpload', FALSE);
         $ZipFile = FALSE;
         if ($TmpZip) {
             // Generate the target name
             $TargetFile = $Upload->GenerateTargetName(PATH_UPLOADS, 'zip');
             $BaseName = pathinfo($TargetFile, PATHINFO_BASENAME);
             // Save the uploaded zip
             $Parts = $Upload->SaveAs($TmpZip, $BaseName);
             $ZipFile = PATH_UPLOADS . DS . $Parts['SaveName'];
             $this->SetData('TransportPath', $ZipFile);
         }
         $Include = $this->_FindIncludes();
         if (count($Include)) {
             $Info = $this->_ExtractZip($ZipFile);
             $this->_ImportData($Info, $Include);
             Gdn_FileSystem::RemoveFolder(PATH_UPLOADS . DS . 'import' . DS . 'yaga');
         } else {
             $this->Form->AddError(T('Yaga.Error.Includes'));
         }
     }
     if ($this->Form->ErrorCount() == 0 && $this->Form->IsPostBack()) {
         $this->Render('transport-success');
     } else {
         $this->Render();
     }
 }
Ejemplo n.º 8
0
 /**
  * Perform formatting against a string for the attach tag.
  *
  * @param Nbbc $bbcode Instance of Nbbc doing the parsing.
  * @param int $action Value of one of NBBC's defined constants.  Typically, this will be BBCODE_CHECK.
  * @param string $name Name of the tag.
  * @param string $default Value of the _default parameter, from the $params array.
  * @param array $params A standard set parameters related to the tag.
  * @param string $content Value between the open and close tags, if any.
  * @return string Formatted value.
  */
 public function doAttachment($bbcode, $action, $name, $default, $params, $content)
 {
     $medias = $this->media();
     $mediaID = $content;
     if (isset($medias[$mediaID])) {
         $media = $medias[$mediaID];
         $src = htmlspecialchars(Gdn_Upload::url(val('Path', $media)));
         $name = htmlspecialchars(val('Name', $media));
         if (val('ImageWidth', $media)) {
             return "<div class=\"Attachment Image\"><img src=\"{$src}\" alt=\"{$name}\" /></div>";
         } else {
             return anchor($name, $src, 'Attachment File');
         }
     }
     return anchor(t('Attachment not found.'), '#', 'Attachment NotFound');
 }
Ejemplo n.º 9
0
    public function DoAttachment($bbcode, $action, $name, $default, $params, $content)
    {
        $Medias = $this->Media();
        $MediaID = $content;
        if (isset($Medias[$MediaID])) {
            $Media = $Medias[$MediaID];
            //         decho($Media, 'Media');
            $Src = htmlspecialchars(Gdn_Upload::Url(GetValue('Path', $Media)));
            $Name = htmlspecialchars(GetValue('Name', $Media));
            if (GetValue('ImageWidth', $Media)) {
                return <<<EOT
<div class="Attachment Image"><img src="{$Src}" alt="{$Name}" /></div>
EOT;
            } else {
                return Anchor($Name, $Src, 'Attachment File');
            }
        }
        return Anchor(T('Attachment not found.'), '#', 'Attachment NotFound');
    }
Ejemplo n.º 10
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();
 }
Ejemplo n.º 11
0
function MediaThumbnail($Media, $Data = FALSE)
{
    $Media = (array) $Media;
    if (GetValue('ThumbPath', $Media)) {
        $Src = Gdn_Upload::Url(ltrim(GetValue('ThumbPath', $Media), '/'));
    } else {
        $Width = GetValue('ImageWidth', $Media);
        $Height = GetValue('ImageHeight', $Media);
        if (!$Width || !$Height) {
            $Height = MediaModel::ThumbnailHeight();
            if (!$Height) {
                $Height = 100;
            }
            SetValue('ThumbHeight', $Media, $Height);
            return DefaultMediaThumbnail($Media);
        }
        $RequiresThumbnail = FALSE;
        if (MediaModel::ThumbnailHeight() && $Height > MediaModel::ThumbnailHeight()) {
            $RequiresThumbnail = TRUE;
        } elseif (MediaModel::ThumbnailWidth() && $Width > MediaModel::ThumbnailWidth()) {
            $RequiresThumbnail = TRUE;
        }
        $Path = ltrim(GetValue('Path', $Media), '/');
        if ($RequiresThumbnail) {
            $Src = Url('/utility/thumbnail/' . GetValue('MediaID', $Media, 'x') . '/' . $Path, TRUE);
        } else {
            $Src = Gdn_Upload::Url($Path);
        }
    }
    if ($Data) {
        $Result = array('src' => $Src, 'width' => GetValue('ThumbWidth', $Media), 'height' => GetValue('ThumbHeight', $Media));
    } else {
        $Result = Img($Src, array('class' => 'ImageThumbnail', 'width' => GetValue('ThumbWidth', $Media), 'height' => GetValue('ThumbHeight', $Media)));
    }
    return $Result;
}
Ejemplo n.º 12
0
 /**
  *
  */
 public function renderMaster()
 {
     // Build the master view if necessary
     if (in_array($this->_DeliveryType, array(DELIVERY_TYPE_ALL))) {
         $this->MasterView = $this->masterView();
         // Only get css & ui components if this is NOT a syndication request
         if ($this->SyndicationMethod == SYNDICATION_NONE && is_object($this->Head)) {
             $CssAnchors = AssetModel::getAnchors();
             $this->EventArguments['CssFiles'] =& $this->_CssFiles;
             $this->fireEvent('BeforeAddCss');
             $ETag = AssetModel::eTag();
             $CombineAssets = c('Garden.CombineAssets');
             $ThemeType = isMobile() ? 'mobile' : 'desktop';
             // And now search for/add all css files.
             foreach ($this->_CssFiles as $CssInfo) {
                 $CssFile = $CssInfo['FileName'];
                 if (!array_key_exists('Options', $CssInfo) || !is_array($CssInfo['Options'])) {
                     $CssInfo['Options'] = array();
                 }
                 $Options =& $CssInfo['Options'];
                 // style.css and admin.css deserve some custom processing.
                 if (in_array($CssFile, $CssAnchors)) {
                     if (!$CombineAssets) {
                         // Grab all of the css files from the asset model.
                         $AssetModel = new AssetModel();
                         $CssFiles = $AssetModel->getCssFiles($ThemeType, ucfirst(substr($CssFile, 0, -4)), $ETag);
                         foreach ($CssFiles as $Info) {
                             $this->Head->addCss($Info[1], 'all', true, $CssInfo);
                         }
                     } else {
                         $Basename = substr($CssFile, 0, -4);
                         $this->Head->addCss(url("/asset/css/{$ThemeType}/{$Basename}-{$ETag}.css", '//'), 'all', false, $CssInfo['Options']);
                     }
                     continue;
                 }
                 $AppFolder = $CssInfo['AppFolder'];
                 $LookupFolder = !empty($AppFolder) ? $AppFolder : $this->ApplicationFolder;
                 $Search = AssetModel::CssPath($CssFile, $LookupFolder, $ThemeType);
                 if (!$Search) {
                     continue;
                 }
                 list($Path, $UrlPath) = $Search;
                 if (isUrl($Path)) {
                     $this->Head->AddCss($Path, 'all', val('AddVersion', $Options, true), $Options);
                     continue;
                 } else {
                     // Check to see if there is a CSS cacher.
                     $CssCacher = Gdn::factory('CssCacher');
                     if (!is_null($CssCacher)) {
                         $Path = $CssCacher->get($Path, $AppFolder);
                     }
                     if ($Path !== false) {
                         $Path = substr($Path, strlen(PATH_ROOT));
                         $Path = str_replace(DS, '/', $Path);
                         $this->Head->addCss($Path, 'all', true, $Options);
                     }
                 }
             }
             // Add a custom js file.
             if (arrayHasValue($this->_CssFiles, 'style.css')) {
                 $this->addJsFile('custom.js');
                 // only to non-admin pages.
             }
             $Cdns = array();
             if (!c('Garden.Cdns.Disable', false)) {
                 $Cdns = array('jquery.js' => "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js");
             }
             // And now search for/add all JS files.
             $this->EventArguments['Cdns'] =& $Cdns;
             $this->fireEvent('AfterJsCdns');
             $this->Head->addScript('', 'text/javascript', false, array('content' => $this->definitionList(false)));
             foreach ($this->_JsFiles as $Index => $JsInfo) {
                 $JsFile = $JsInfo['FileName'];
                 if (!is_array($JsInfo['Options'])) {
                     $JsInfo['Options'] = array();
                 }
                 $Options =& $JsInfo['Options'];
                 if (isset($Cdns[$JsFile])) {
                     $JsFile = $Cdns[$JsFile];
                 }
                 $AppFolder = $JsInfo['AppFolder'];
                 $LookupFolder = !empty($AppFolder) ? $AppFolder : $this->ApplicationFolder;
                 $Search = AssetModel::JsPath($JsFile, $LookupFolder, $ThemeType);
                 if (!$Search) {
                     continue;
                 }
                 list($Path, $UrlPath) = $Search;
                 if ($Path !== false) {
                     $AddVersion = true;
                     if (!isUrl($Path)) {
                         $Path = substr($Path, strlen(PATH_ROOT));
                         $Path = str_replace(DS, '/', $Path);
                         $AddVersion = val('AddVersion', $Options, true);
                     }
                     $this->Head->addScript($Path, 'text/javascript', $AddVersion, $Options);
                     continue;
                 }
             }
         }
         // Add the favicon.
         $Favicon = C('Garden.FavIcon');
         if ($Favicon) {
             $this->Head->setFavIcon(Gdn_Upload::url($Favicon));
         }
         // Make sure the head module gets passed into the assets collection.
         $this->addModule('Head');
     }
     // Master views come from one of four places:
     $MasterViewPaths = array();
     if (strpos($this->MasterView, '/') !== false) {
         $MasterViewPaths[] = combinePaths(array(PATH_ROOT, str_replace('/', DS, $this->MasterView) . '.master*'));
     } else {
         if ($this->Theme) {
             // 1. Application-specific theme view. eg. root/themes/theme_name/app_name/views/
             $MasterViewPaths[] = combinePaths(array(PATH_THEMES, $this->Theme, $this->ApplicationFolder, 'views', $this->MasterView . '.master*'));
             // 2. Garden-wide theme view. eg. /path/to/application/themes/theme_name/views/
             $MasterViewPaths[] = combinePaths(array(PATH_THEMES, $this->Theme, 'views', $this->MasterView . '.master*'));
         }
         // 3. Plugin default. eg. root/plugin_name/views/
         $MasterViewPaths[] = combinePaths(array(PATH_ROOT, $this->ApplicationFolder, 'views', $this->MasterView . '.master*'));
         // 4. Application default. eg. root/app_name/views/
         $MasterViewPaths[] = combinePaths(array(PATH_APPLICATIONS, $this->ApplicationFolder, 'views', $this->MasterView . '.master*'));
         // 5. Garden default. eg. root/dashboard/views/
         $MasterViewPaths[] = combinePaths(array(PATH_APPLICATIONS, 'dashboard', 'views', $this->MasterView . '.master*'));
     }
     // Find the first file that matches the path.
     $MasterViewPath = false;
     foreach ($MasterViewPaths as $Glob) {
         $Paths = safeGlob($Glob);
         if (is_array($Paths) && count($Paths) > 0) {
             $MasterViewPath = $Paths[0];
             break;
         }
     }
     $this->EventArguments['MasterViewPath'] =& $MasterViewPath;
     $this->fireEvent('BeforeFetchMaster');
     if ($MasterViewPath === false) {
         trigger_error(errorMessage("Could not find master view: {$this->MasterView}.master*", $this->ClassName, '_FetchController'), E_USER_ERROR);
     }
     /// A unique identifier that can be used in the body tag of the master view if needed.
     $ControllerName = $this->ClassName;
     // Strip "Controller" from the body identifier.
     if (substr($ControllerName, -10) == 'Controller') {
         $ControllerName = substr($ControllerName, 0, -10);
     }
     // Strip "Gdn_" from the body identifier.
     if (substr($ControllerName, 0, 4) == 'Gdn_') {
         $ControllerName = substr($ControllerName, 4);
     }
     $this->setData('CssClass', $this->Application . ' ' . $ControllerName . ' ' . $this->RequestMethod . ' ' . $this->CssClass, true);
     // Check to see if there is a handler for this particular extension.
     $ViewHandler = Gdn::factory('ViewHandler' . strtolower(strrchr($MasterViewPath, '.')));
     if (is_null($ViewHandler)) {
         $BodyIdentifier = strtolower($this->ApplicationFolder . '_' . $ControllerName . '_' . Gdn_Format::alphaNumeric(strtolower($this->RequestMethod)));
         include $MasterViewPath;
     } else {
         $ViewHandler->render($MasterViewPath, $this);
     }
 }
Ejemplo n.º 13
0
 /**
  * Returns the current image in a field.
  * This is meant to be used with image uploads so that users can see the current value.
  * 
  * @param type $FieldName
  * @param type $Attributes
  * @since 2.1
  */
 public function CurrentImage($FieldName, $Attributes = array())
 {
     $Result = $this->Hidden($FieldName);
     $Value = $this->GetValue($FieldName);
     if ($Value) {
         TouchValue('class', $Attributes, 'CurrentImage');
         $Result .= Img(Gdn_Upload::Url($Value), $Attributes);
     }
     return $Result;
 }
   public function Thumbnail($UserReference = '', $Username = '') {
      $this->Permission('Garden.SignIn.Allow');
      $this->AddJsFile('jquery.jcrop.pack.js');
      $this->AddJsFile('profile.js');
            
      $Session = Gdn::Session();
      if (!$Session->IsValid())
         $this->Form->AddError('You must be authenticated in order to use this form.');
               
      $this->GetUserInfo($UserReference, $Username);
      
      if ($this->User->UserID != $Session->UserID && !$Session->CheckPermission('Garden.Users.Edit'))
         throw new Exception(T('You cannot edit the thumbnail of another member.'));
      
      $this->Form->SetModel($this->UserModel);
      $this->Form->AddHidden('UserID', $this->User->UserID);
      
      if (!$this->User->Photo)
         $this->Form->AddError('You must first upload a picture before you can create a thumbnail.');
      
      // Define the thumbnail size
      $this->ThumbSize = Gdn::Config('Garden.Thumbnail.Size', 32);
      
      // Define the source (profile sized) picture & dimensions.
      $Basename = ChangeBasename($this->User->Photo, 'p%s');
      $Upload = new Gdn_UploadImage();
      $PhotoParsed = Gdn_Upload::Parse($Basename);
      $Source = $Upload->CopyLocal($Basename);

      if (!$Source) {
         $this->Form->AddError('You cannot edit the thumbnail of an externally linked profile picture.');
      } else {
         $this->SourceSize = getimagesize($Source);
      }
      
      // Add some more hidden form fields for jcrop
      $this->Form->AddHidden('x', '0');
      $this->Form->AddHidden('y', '0');
      $this->Form->AddHidden('w', $this->ThumbSize);
      $this->Form->AddHidden('h', $this->ThumbSize);
      $this->Form->AddHidden('HeightSource', $this->SourceSize[1]);
      $this->Form->AddHidden('WidthSource', $this->SourceSize[0]);
      $this->Form->AddHidden('ThumbSize', $this->ThumbSize);      
      if ($this->Form->AuthenticatedPostBack() === TRUE) {
         try {
            // Get the dimensions from the form.
            Gdn_UploadImage::SaveImageAs(
               $Source,
               'userpics/'.ChangeBasename(basename($this->User->Photo), 'n%s'),
               $this->ThumbSize, $this->ThumbSize,
               array('Crop' => TRUE, 'SourceX' => $this->Form->GetValue('x'), 'SourceY' => $this->Form->GetValue('y'), 'SourceWidth' => $this->Form->GetValue('w'), 'SourceHeight' => $this->Form->GetValue('h')));
         } catch (Exception $Ex) {
            $this->Form->AddError($Ex);
         }
         // If there were no problems, redirect back to the user account
         if ($this->Form->ErrorCount() == 0) {
            Redirect('dashboard/profile/'.$this->ProfileUrl());
         }
      }
      // Delete the source image if it is externally hosted.
      if ($PhotoParsed['Type']) {
         @unlink($Source);
      }
      $this->Render();
   }
Ejemplo n.º 15
0
    public function DoAttachment($bbcode, $action, $name, $default, $params, $content)
    {
        $Medias = $this->Media();
        $Parts = explode(':', $default);
        $MediaID = $Parts[0];
        if (isset($Medias[$MediaID])) {
            $Media = $Medias[$MediaID];
            //         decho($Media, 'Media');
            $Src = htmlspecialchars(Gdn_Upload::Url(GetValue('Path', $Media)));
            $Name = htmlspecialchars(GetValue('Name', $Media));
            return <<<EOT
<div class="Attachment"><img src="{$Src}" alt="{$Name}" /></div>
EOT;
        }
        return '';
    }
 /**
  * Banner management screen.
  */
 public function Banner()
 {
     $this->Permission('Garden.Settings.Manage');
     $this->AddSideMenu('dashboard/settings/banner');
     $this->Title(T('Banner'));
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $ConfigurationModel->SetField(array('Garden.Title'));
     // Set the model on the form.
     $this->Form->SetModel($ConfigurationModel);
     // If seeing the form for the first time...
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         // Apply the config settings to the form.
         $this->Form->SetData($ConfigurationModel->Data);
     } else {
         // Define some validation rules for the fields being saved
         $ConfigurationModel->Validation->ApplyRule('Garden.Title', 'Required');
         if ($this->Form->Save() !== FALSE) {
             $Upload = new Gdn_Upload();
             try {
                 // Validate the upload
                 $TmpImage = $Upload->ValidateUpload('Logo', FALSE);
                 if ($TmpImage) {
                     // Generate the target image name
                     $TargetImage = $Upload->GenerateTargetName(PATH_ROOT . DS . 'uploads');
                     $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
                     // Delete any previously uploaded images
                     @unlink(PATH_ROOT . DS . C('Garden.Logo', ''));
                     // Save the uploaded image
                     $Upload->SaveAs($TmpImage, PATH_ROOT . DS . 'uploads' . DS . $ImageBaseName);
                 }
             } catch (Exception $ex) {
                 $this->Form->AddError($ex->getMessage());
             }
             // If there were no errors, save the path to the logo in the config
             if ($this->Form->ErrorCount() == 0 && $Upload->GetUploadedFileName() != '') {
                 SaveToConfig('Garden.Logo', 'uploads' . DS . $ImageBaseName);
             }
             $this->StatusMessage = T("Your settings have been saved.");
         }
     }
     $this->Render();
 }
 /**
  * Remove the logo from config & delete it.
  *
  * @since 2.1
  * @param string $TransientKey Security token.
  */
 public function RemoveFavicon($TransientKey = '')
 {
     $Session = Gdn::Session();
     if ($Session->ValidateTransientKey($TransientKey) && $Session->CheckPermission('Garden.Settings.Manage')) {
         $Favicon = C('Garden.FavIcon', '');
         RemoveFromConfig('Garden.FavIcon');
         $Upload = new Gdn_Upload();
         $Upload->Delete($Favicon);
     }
     Redirect('/settings/banner');
 }
Ejemplo n.º 18
0
 /**
  * Set fields that need additional manipulation after retrieval.
  *
  * @param array|object &$User
  * @throws Exception
  */
 public function setCalculatedFields(&$User)
 {
     if ($v = val('Attributes', $User)) {
         if (is_string($v)) {
             setValue('Attributes', $User, dbdecode($v));
         }
     }
     if ($v = val('Permissions', $User)) {
         if (is_string($v)) {
             setValue('Permissions', $User, dbdecode($v));
         }
     }
     if ($v = val('Preferences', $User)) {
         if (is_string($v)) {
             setValue('Preferences', $User, dbdecode($v));
         }
     }
     if ($v = val('Photo', $User)) {
         if (!isUrl($v)) {
             $PhotoUrl = Gdn_Upload::url(changeBasename($v, 'n%s'));
         } else {
             $PhotoUrl = $v;
         }
         setValue('PhotoUrl', $User, $PhotoUrl);
     }
     // We store IPs in the UserIP table. To avoid unnecessary queries, the full list is not built here. Shim for BC.
     setValue('AllIPAddresses', $User, [val('InsertIPAddress', $User), val('LastIPAddress', $User)]);
     setValue('_CssClass', $User, '');
     if (val('Banned', $User)) {
         setValue('_CssClass', $User, 'Banned');
     }
     $this->EventArguments['User'] =& $User;
     $this->fireEvent('SetCalculatedFields');
 }
Ejemplo n.º 19
0
 /**
  * Add UserCategory modifiers
  *
  * Update &$Categories in memory by applying modifiers from UserCategory for
  * the currently logged-in user.
  *
  * @since 2.0.18
  * @access public
  * @param array &$Categories
  * @param bool $AddUserCategory
  */
 public static function JoinUserData(&$Categories, $AddUserCategory = TRUE)
 {
     $IDs = array_keys($Categories);
     $DoHeadings = C('Vanilla.Categories.DoHeadings');
     if ($AddUserCategory) {
         $SQL = clone Gdn::SQL();
         $SQL->Reset();
         if (Gdn::Session()->UserID) {
             $Key = 'UserCategory_' . Gdn::Session()->UserID;
             $UserData = Gdn::Cache()->Get($Key);
             if ($UserData === Gdn_Cache::CACHEOP_FAILURE) {
                 $UserData = $SQL->GetWhere('UserCategory', array('UserID' => Gdn::Session()->UserID))->ResultArray();
                 $UserData = Gdn_DataSet::Index($UserData, 'CategoryID');
                 Gdn::Cache()->Store($Key, $UserData);
             }
         } else {
             $UserData = array();
         }
         //         Gdn::Controller()->SetData('UserData', $UserData);
         foreach ($IDs as $ID) {
             $Category = $Categories[$ID];
             $DateMarkedRead = GetValue('DateMarkedRead', $Category);
             $Row = GetValue($ID, $UserData);
             if ($Row) {
                 $UserDateMarkedRead = $Row['DateMarkedRead'];
                 if (!$DateMarkedRead || $UserDateMarkedRead && Gdn_Format::ToTimestamp($UserDateMarkedRead) > Gdn_Format::ToTimestamp($DateMarkedRead)) {
                     $Categories[$ID]['DateMarkedRead'] = $UserDateMarkedRead;
                     $DateMarkedRead = $UserDateMarkedRead;
                 }
                 $Categories[$ID]['Unfollow'] = $Row['Unfollow'];
             } else {
                 $Categories[$ID]['Unfollow'] = FALSE;
             }
             // Calculate the following field.
             $Following = !((bool) GetValue('Archived', $Category) || (bool) GetValue('Unfollow', $Row, FALSE));
             $Categories[$ID]['Following'] = $Following;
             // Calculate the read field.
             if ($DoHeadings && $Category['Depth'] <= 1) {
                 $Categories[$ID]['Read'] = FALSE;
             } elseif ($DateMarkedRead) {
                 if (GetValue('LastDateInserted', $Category)) {
                     $Categories[$ID]['Read'] = Gdn_Format::ToTimestamp($DateMarkedRead) >= Gdn_Format::ToTimestamp($Category['LastDateInserted']);
                 } else {
                     $Categories[$ID]['Read'] = TRUE;
                 }
             } else {
                 $Categories[$ID]['Read'] = FALSE;
             }
         }
     }
     // Add permissions.
     $Session = Gdn::Session();
     foreach ($IDs as $CID) {
         $Category = $Categories[$CID];
         $Categories[$CID]['Url'] = Url($Category['Url'], '//');
         if ($Photo = val('Photo', $Category)) {
             $Categories[$CID]['PhotoUrl'] = Gdn_Upload::Url($Photo);
         }
         if ($Category['LastUrl']) {
             $Categories[$CID]['LastUrl'] = Url($Category['LastUrl'], '//');
         }
         $Categories[$CID]['PermsDiscussionsView'] = $Session->CheckPermission('Vanilla.Discussions.View', TRUE, 'Category', $Category['PermissionCategoryID']);
         $Categories[$CID]['PermsDiscussionsAdd'] = $Session->CheckPermission('Vanilla.Discussions.Add', TRUE, 'Category', $Category['PermissionCategoryID']);
         $Categories[$CID]['PermsDiscussionsEdit'] = $Session->CheckPermission('Vanilla.Discussions.Edit', TRUE, 'Category', $Category['PermissionCategoryID']);
         $Categories[$CID]['PermsCommentsAdd'] = $Session->CheckPermission('Vanilla.Comments.Add', TRUE, 'Category', $Category['PermissionCategoryID']);
     }
 }
 /**
  * Deletes uploaded default avatars.
  *
  * @param string $avatar The avatar to delete.
  */
 private function deleteDefaultAvatars($avatar = '')
 {
     if ($avatar && $this->isUploadedDefaultAvatar($avatar)) {
         $upload = new Gdn_Upload();
         $upload->delete(self::DEFAULT_AVATAR_FOLDER . '/' . basename($avatar));
         $upload->delete(self::DEFAULT_AVATAR_FOLDER . '/' . basename(changeBasename($avatar, 'p%s')));
         $upload->delete(self::DEFAULT_AVATAR_FOLDER . '/' . basename(changeBasename($avatar, 'n%s')));
     }
 }
Ejemplo n.º 21
0
 /**
  * Returns the mobile banner logo. If there is no mobile logo defined then this will just return
  * the regular logo or the mobile title.
  *
  * @return string
  */
 public static function mobileLogo()
 {
     $Logo = C('Garden.MobileLogo', C('Garden.Logo'));
     $Title = C('Garden.MobileTitle', C('Garden.Title', 'Title'));
     if ($Logo) {
         return Img(Gdn_Upload::url($Logo), array('alt' => $Title));
     } else {
         return $Title;
     }
 }
Ejemplo n.º 22
0
echo Wrap(T('LogoDescription', 'The banner logo appears at the top of your site. Some themes may not display this logo.'), 'div', array('class' => 'Info'));
$Logo = $this->Data('Logo');
if ($Logo) {
    echo Wrap(Img(Gdn_Upload::Url($Logo)), 'div');
    echo Wrap(Anchor(T('Remove Banner Logo'), '/dashboard/settings/removelogo/' . $Session->TransientKey(), 'SmallButton'), 'div', array('style' => 'padding: 10px 0;'));
    echo Wrap(T('LogoBrowse', 'Browse for a new banner logo if you would like to change it:'), 'div', array('class' => 'Info'));
}
echo $this->Form->Input('Logo', 'file');
?>
         </li>
         <li>
            <?php 
echo $this->Form->Label('Favicon', 'Favicon');
echo Wrap(T('FaviconDescription', "Your site's favicon appears in your browser's title bar. It will be scaled to 16x16 pixels."), 'div', array('class' => 'Info'));
$Favicon = $this->Data('Favicon');
if ($Favicon) {
    echo Wrap(Img(Gdn_Upload::Url($Favicon)), 'div');
    echo Wrap(Anchor(T('Remove Favicon'), '/dashboard/settings/removefavicon/' . $Session->TransientKey(), 'SmallButton'), 'div', array('style' => 'padding: 10px 0;'));
    echo Wrap(T('FaviconBrowse', 'Browse for a new favicon if you would like to change it:'), 'div', array('class' => 'Info'));
} else {
    echo Wrap(T('FaviconDescription', "The shortcut icon that shows up in your browser's bookmark menu (16x16 px)."), 'div', array('class' => 'Info'));
}
echo $this->Form->Input('Favicon', 'file');
?>
         </li>
      </ul>
   </div>
</div>
<?php 
echo '<div class="Buttons">' . $this->Form->Button('Save') . '</div>';
echo $this->Form->Close();
 /**
  * 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();
 }
Ejemplo n.º 24
0
 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();
     if ($Imp->CurrentStep < 1) {
         // Check to see if there is a file.
         $ImportPath = Gdn::Config('Garden.Import.ImportPath');
         $Validation = new Gdn_Validation();
         if (strcasecmp(Gdn::Request()->RequestMethod(), 'post') == 0) {
             $Upload = new Gdn_Upload();
             $Validation = new Gdn_Validation();
             $TmpFile = $Upload->ValidateUpload('ImportFile', FALSE);
             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;
                 $Imp->Data['OriginalFilename'] = basename($Filename);
             } elseif (!$Imp->ImportPath) {
                 // There was no file uploaded this request or before.
                 $Validation->AddValidationResult('ImportFile', $Upload->Exception);
             }
             // Validate the overwrite.
             if (strcasecmp($this->Form->GetFormValue('Overwrite'), 'Overwrite') == 0) {
                 $Validation->ApplyRule('Email', 'Required');
                 $Validation->ApplyRule('Password', 'Required');
             }
             if ($Validation->Validate($this->Form->FormValues())) {
                 $Imp->Overwrite($this->Form->GetFormValue('Overwrite', 'Overwrite'), $this->Form->GetFormValue('Email'), $this->Form->GetFormValue('Password'));
                 $this->View = 'Info';
             } else {
                 $this->Form->SetValidationResults($Validation->Results());
             }
         } else {
             // Search for an existing file that was uploaded by the web admin.
             $ImportPaths = SafeGlob(PATH_ROOT . DS . 'uploads' . DS . 'import' . DS . 'import.*');
             if ($ImportPaths) {
                 $ImportPath = $ImportPaths[0];
                 if (in_array(pathinfo($ImportPath, PATHINFO_EXTENSION), array('gz', 'txt'))) {
                     $Imp->ImportPath = $ImportPath;
                     $Imp->Data['OriginalFilename'] = basename($ImportPath);
                 }
             }
         }
         $Imp->SaveState();
     } else {
         $this->View = 'Info';
     }
     $this->SetData('Header', $Imp->GetImportHeader());
     $this->SetData('ImportPath', $Imp->ImportPath);
     $this->SetData('OriginalFilename', GetValue('OriginalFilename', $Imp->Data));
     $this->Render();
 }
Ejemplo n.º 25
0
 /**
  *
  *
  * @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);
 }
 public function remote_login()
 {
     $user_login = Gdn::Session()->User->Name;
     $avatar = '';
     if (Gdn::Session()->User->Photo != '') {
         $avatar = Gdn_Upload::Url(ChangeBasename(Gdn::Session()->User->Photo, 'p%s'));
     }
     $isAdmin = Gdn::Session()->User->Admin;
     $chatId = C('Plugin.Chatwee.Chatid');
     $clientKey = C('Plugin.Chatwee.APIKey');
     $ismobile = $this->check_user_agent('mobile') == true ? 1 : 0;
     $ip = $this->get_the_user_ip();
     if (isset($_COOKIE["chch-SI"])) {
         $this->remote_logout();
     }
     if (isset($_SESSION['chatwee'][$user_login])) {
         $previousSessionId = $_SESSION['chatwee'][$user_login];
     } else {
         if (isset($_COOKIE["chch-PSI"])) {
             $previousSessionId = $_COOKIE["chch-PSI"];
         } else {
             $previousSessionId = null;
         }
     }
     $url = "http://chatwee-api.com/api/remotelogin?chatId=" . $chatId . "&clientKey=" . $clientKey . "&login="******"&isAdmin=" . $isAdmin . "&ipAddress=" . $ip . "&avatar=" . $avatar . "&isMobile=" . $ismobile . "&previousSessionId=" . $previousSessionId;
     $url = str_replace(' ', '%20', $url);
     $response = $this->get_response($url);
     $sessionArray = json_decode($response);
     if ($sessionArray->errorCode) {
         //	update_option('chatwee-settings-group[ssoiserror]',$sessionArray->errorMessage);
     } else {
         //	update_option('chatwee-settings-group[ssoiserror]','');
         $sessionId = $sessionArray->sessionId;
     }
     $fullDomain = $_SERVER["HTTP_HOST"];
     $isNumericDomain = preg_match('/\\d|"."/', $fullDomain);
     if ($isNumericDomain) {
         $CookieDomain = $fullDomain;
     } else {
         $hostChunks = explode(".", $fullDomain);
         $hostChunks = array_slice($hostChunks, -2);
         $CookieDomain = "." . implode(".", $hostChunks);
     }
     setcookie("chch-SI", $sessionId, time() + 2592000, "/", $CookieDomain);
     $_SESSION['chatwee'][$user_login] = $_SESSION['chatwee'][$user_login] == '' ? $sessionId : $_SESSION['chatwee'][$user_login];
 }
Ejemplo n.º 27
0
 /**
  * Take a user object an return the URL to their photo.
  *
  * @param object|array $User
  */
 function userPhotoUrl($User)
 {
     $FullUser = Gdn::userModel()->getID(val('UserID', $User), DATASET_TYPE_ARRAY);
     $Photo = val('Photo', $User);
     if ($FullUser && $FullUser['Banned']) {
         $Photo = 'https://c3409409.ssl.cf0.rackcdn.com/images/banned_100.png';
     }
     if ($Photo) {
         if (!isUrl($Photo)) {
             $PhotoUrl = Gdn_Upload::url(changeBasename($Photo, 'n%s'));
         } else {
             $PhotoUrl = $Photo;
         }
         return $PhotoUrl;
     }
     return UserModel::getDefaultAvatarUrl($User);
 }
Ejemplo n.º 28
0
 /**
  * Set fields that need additional manipulation after retrieval.
  *
  * @param $User
  * @throws Exception
  */
 public function setCalculatedFields(&$User)
 {
     if ($v = val('Attributes', $User)) {
         if (is_string($v)) {
             setValue('Attributes', $User, @unserialize($v));
         }
     }
     if ($v = val('Permissions', $User)) {
         if (is_string($v)) {
             setValue('Permissions', $User, @unserialize($v));
         }
     }
     if ($v = val('Preferences', $User)) {
         if (is_string($v)) {
             setValue('Preferences', $User, @unserialize($v));
         }
     }
     if ($v = val('Photo', $User)) {
         if (!isUrl($v)) {
             $PhotoUrl = Gdn_Upload::url(changeBasename($v, 'n%s'));
         } else {
             $PhotoUrl = $v;
         }
         setValue('PhotoUrl', $User, $PhotoUrl);
     }
     if ($v = val('AllIPAddresses', $User)) {
         if (is_string($v)) {
             $IPAddresses = explode(',', $v);
             foreach ($IPAddresses as $i => $IPAddress) {
                 $IPAddresses[$i] = ForceIPv4($IPAddress);
             }
             setValue('AllIPAddresses', $User, $IPAddresses);
         }
     }
     setValue('_CssClass', $User, '');
     if ($v = val('Banned', $User)) {
         setValue('_CssClass', $User, 'Banned');
     }
     $this->EventArguments['User'] =& $User;
     $this->fireEvent('SetCalculatedFields');
 }
Ejemplo n.º 29
0
 /**
  * Create and display a thumbnail of an uploaded file.
  */
 public function utilityController_mediaThumbnail_create($sender, $media_id)
 {
     // When it makes it into core, it will be available in
     // functions.general.php
     require 'generate_thumbnail.php';
     $model = new Gdn_Model('Media');
     $media = $model->getID($media_id, DATASET_TYPE_ARRAY);
     if (!$media) {
         throw notFoundException('File');
     }
     // Get actual path to the file.
     $local_path = Gdn_Upload::copyLocal($media['Path']);
     if (!file_exists($local_path)) {
         throw notFoundException('File');
     }
     $file_extension = pathinfo($local_path, PATHINFO_EXTENSION);
     // Generate new path for thumbnail
     $thumb_path = $this->getBaseUploadDestinationDir() . '/' . 'thumb';
     // Grab full path with filename, and validate it.
     $thumb_destination_path = $this->getAbsoluteDestinationFilePath($local_path, $file_extension, $thumb_path);
     // Create thumbnail, and grab debug data from whole process.
     $thumb_payload = generate_thumbnail($local_path, $thumb_destination_path, array('height' => c('Plugins.FileUpload.ThumbnailHeight', 128)));
     if ($thumb_payload['success'] === true) {
         // Thumbnail dimensions
         $thumb_height = round($thumb_payload['result_height']);
         $thumb_width = round($thumb_payload['result_width']);
         // Move the thumbnail to its proper location. Calling SaveAs with
         // cloudfiles enabled will trigger the move to cloudfiles, so use
         // same path for each arg in SaveAs. The file will be removed from the local filesystem.
         $parsed = Gdn_Upload::parse($thumb_destination_path);
         $target = $thumb_destination_path;
         // $parsed['Name'];
         $Upload = new Gdn_Upload();
         $filepath_parsed = $Upload->saveAs($thumb_destination_path, $target, array('source' => 'content'));
         // Save thumbnail information to DB.
         $model->save(array('MediaID' => $media_id, 'StorageMethod' => $filepath_parsed['Type'], 'ThumbWidth' => $thumb_width, 'ThumbHeight' => $thumb_height, 'ThumbPath' => $filepath_parsed['SaveName']));
         // Remove cf scratch copy, typically in cftemp, if there was actually a file pulled in from CF.
         if (strpos($local_path, 'cftemp') !== false) {
             if (!unlink($local_path)) {
                 // Maybe add logging for local cf copies not deleted.
             }
         }
         $url = $filepath_parsed['Url'];
     } else {
         // Fix the thumbnail information so this isn't requested again and again.
         $model->save(array('MediaID' => $media_id, 'ImageWidth' => 0, 'ImageHeight' => 0, 'ThumbPath' => ''));
         $url = asset('/plugins/FileUpload/images/file.png');
     }
     redirect($url, 301);
 }
Ejemplo n.º 30
0
</td>
            <td><?php 
echo t('Thumbnail');
?>
</td>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>
                <?php 
echo img(Gdn_Upload::url(changeBasename($this->User->Photo, 'p%s')), array('id' => 'cropbox'));
?>
            </td>
            <td>
                <div
                    style="<?php 
echo 'width:' . $this->ThumbSize . 'px;height:' . $this->ThumbSize . 'px;';
?>
overflow:hidden;">
                    <?php 
echo img(Gdn_Upload::url(changeBasename($this->User->Photo, 'p%s')), array('id' => 'preview'));
?>
                </div>
            </td>
        </tr>
        </tbody>
    </table>

<?php 
echo $this->Form->close('Save', '', array('class' => 'Button Primary'));