url() public static method

public static url ( $Name ) : mixed
$Name
return mixed
示例#1
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');
 }
示例#2
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();
 }
示例#3
0
/**
 *
 *
 * @param $Addon
 * @param $Alt
 */
function writeAddon($Addon, $Alt)
{
    $Url = '/addon/' . AddonModel::slug($Addon, FALSE);
    ?>
    <li class="Item AddonRow<?php 
    echo $Alt;
    ?>
">
        <?php 
    if ($Addon->Icon != '') {
        echo '<a class="Icon" href="' . url($Url) . '"><div class="IconWrap"><img src="' . Gdn_Upload::url($Addon->Icon) . '" /></div></a>';
    }
    ?>
        <div class="ItemContent">
            <?php 
    echo anchor(htmlspecialchars($Addon->Name), $Url, 'Title');
    echo '<div class="Description">', anchor(htmlspecialchars(sliceString(Gdn_Format::text($Addon->Description), 300)), $Url), '</div>';
    ?>
            <div class="Meta">
                <span class="TypeTag"><?php 
    echo $Addon->Type;
    ?>
</span>
                <?php 
    if ($Addon->Type === 'Locale') {
        ?>
                    <?php 
        if (!is_null($Addon->EnName)) {
            ?>
                <span class="EnName">
                    Name (en)
                    <span><?php 
            echo htmlspecialchars($Addon->EnName);
            ?>
</span>
                </span>
                    <?php 
        }
        ?>
                    <?php 
        if (!is_null($Addon->PercentComplete)) {
            ?>
                <span class="PercentComplete">
                    Translated
                    <span><?php 
            echo (int) $Addon->PercentComplete . '%';
            ?>
</span>
                </span>
                    <?php 
        }
        ?>
                <?php 
    } else {
        ?>
                <span class="Version">
                    Version
                    <span><?php 
        echo htmlspecialchars($Addon->Version);
        ?>
</span>
                </span>
                <?php 
    }
    ?>
                <span class="Author">
                    Author
                    <span><?php 
    echo val('Official', $Addon) ? t('Vanilla Staff') : htmlspecialchars($Addon->InsertName);
    ?>
</span>
                </span>
                <span class="Downloads">
                    Downloads
                    <span><?php 
    echo number_format($Addon->CountDownloads);
    ?>
</span>
                </span>
                <span class="Updated">
                    Updated
                    <span><?php 
    echo Gdn_Format::date($Addon->DateUpdated, 'html');
    ?>
</span>
                </span>
            </div>
        </div>
    </li>
<?php 
}
 /**
  * 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);
 }
示例#5
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;
     }
 }
示例#6
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);
     }
 }
示例#7
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');
 }
示例#8
0
        <?php 
echo $this->Form->label('Description', 'Description');
echo $this->Form->textBox('Description', array('MultiLine' => TRUE));
?>
    </li>
    <li>
        <?php 
echo $this->Form->label('Css Class', 'CssClass');
echo $this->Form->textBox('CssClass', array('MultiLine' => FALSE));
?>
    </li>
    <li>
        <?php 
echo $this->Form->label('Photo', 'PhotoUpload');
if ($Photo = $this->Form->getValue('Photo')) {
    echo img(Gdn_Upload::url($Photo));
    echo '<br />' . anchor(t('Delete Photo'), CombinePaths(array('vanilla/settings/deletecategoryphoto', $this->Category->CategoryID, Gdn::session()->TransientKey())), 'SmallButton Danger PopConfirm');
}
echo $this->Form->Input('PhotoUpload', 'file');
?>
    </li>
    <?php 
echo $this->Form->Simple($this->data('_ExtendedFields', array()), array('Wrap' => array('', '')));
?>
    <li>
        <?php 
echo $this->Form->label('Display As', 'DisplayAs');
echo $this->Form->DropDown('DisplayAs', array('Default' => 'Default', 'Categories' => 'Categories', 'Discussions' => 'Discussions', 'Heading' => 'Heading'));
?>
    </li>
    <li>
示例#9
0
// Define the current profile picture
$Picture = '';
if ($this->User->Photo != '') {
    if (IsUrl($this->User->Photo)) {
        $Picture = img($this->User->Photo, array('class' => 'ProfilePhotoLarge'));
    } else {
        $Picture = img(Gdn_Upload::url(changeBasename($this->User->Photo, 'p%s')), array('class' => 'ProfilePhotoLarge'));
    }
}
// Define the current thumbnail icon
$Thumbnail = $this->User->Photo;
if (!$Thumbnail && function_exists('UserPhotoDefaultUrl')) {
    $Thumbnail = UserPhotoDefaultUrl($this->User);
}
if ($Thumbnail && !isUrl($Thumbnail)) {
    $Thumbnail = Gdn_Upload::url(changeBasename($Thumbnail, 'n%s'));
}
$Thumbnail = img($Thumbnail, array('alt' => t('Thumbnail')));
?>
<div class="SmallPopup FormTitleWrapper">
    <h1 class="H"><?php 
echo $this->data('Title');
?>
</h1>
    <?php 
echo $this->Form->open(array('enctype' => 'multipart/form-data'));
echo $this->Form->errors();
?>
    <ul>
        <?php 
if ($Picture != '') {
示例#10
0
 /**
  * Finish setting up data for the retrieved addon(s).
  *
  * @param $Data
  */
 public function setCalculatedFields(&$Data)
 {
     if (!$Data) {
         return;
     }
     if (is_a($Data, 'Gdn_DataSet')) {
         $this->setCalculatedFields($Data->result());
     } elseif (is_object($Data) || isset($Data['Icon'])) {
         $File = val('File', $Data);
         setValue('Url', $Data, Gdn_Upload::url($File));
         $Icon = val('Icon', $Data, null);
         if ($Icon !== null) {
             // Fix the icon path.
             if ($Icon && strpos($Icon, '/') == false) {
                 $Icon = 'ai' . $Icon;
                 setValue('Icon', $Data, $Icon);
             }
             if (empty($Icon)) {
                 setValue('IconUrl', $Data, 'foo');
             } else {
                 setValue('IconUrl', $Data, Gdn_Upload::url($Icon));
             }
         } else {
             // Set a default icon.
             setValue('Icon', $Data, url('/applications/dashboard/design/images/eyes.png', true));
         }
         if (val('AddonKey', $Data) && val('Checked', $Data)) {
             $Slug = strtolower(val('AddonKey', $Data) . '-' . val('Type', $Data) . '-' . val('Version', $Data));
             setValue('Slug', $Data, $Slug);
         }
         // Set the requirements.
         if (val('Checked', $Data)) {
             $Requirements = val('Requirements', $Data);
             try {
                 $Requirements = unserialize($Requirements);
                 if (is_array($Requirements)) {
                     setValue('Requirements', $Data, $Requirements);
                 }
             } catch (Exception $Ex) {
             }
         }
     } elseif (is_array($Data)) {
         foreach ($Data as &$Row) {
             $this->setCalculatedFields($Row);
         }
     }
 }
示例#11
0
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>
                <li>
                    <?php 
echo $this->Form->label('Share Image', 'ShareImage');
echo wrap(t('ShareImageDescription', "When someone shares a link from your site we try and grab an image from the page. If there isn't an image on the page then we'll use this image instead. The image should be at least 50&times;50, but we recommend 200&times;200."), 'div', array('class' => 'Info'));
$ShareImage = $this->data('ShareImage');
if ($ShareImage) {
    echo wrap(img(Gdn_Upload::url($ShareImage), array('style' => 'max-width: 300px')), 'div');
    echo wrap(Anchor(t('Remove Image'), '/dashboard/settings/removeshareimage', 'SmallButton Hijack'), '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'));
}
echo $this->Form->Input('ShareImage', 'file');
?>
                </li>
            </ul>
        </div>
    </div>
<?php 
echo '<div class="Buttons">' . $this->Form->button('Save') . '</div>';
echo $this->Form->close();
示例#12
0
 /**
  *
  *
  * @param $Row
  */
 public function calculateRow(&$Row)
 {
     $ActivityType = self::GetActivityType($Row['ActivityTypeID']);
     $Row['ActivityType'] = val('Name', $ActivityType);
     if (is_string($Row['Data'])) {
         $Row['Data'] = @unserialize($Row['Data']);
     }
     $Row['PhotoUrl'] = url($Row['Route'], true);
     if (!$Row['Photo']) {
         if (isset($Row['ActivityPhoto'])) {
             $Row['Photo'] = $Row['ActivityPhoto'];
             $Row['PhotoUrl'] = userUrl($Row, 'Activity');
         } else {
             $User = Gdn::userModel()->getID($Row['ActivityUserID'], DATASET_TYPE_ARRAY);
             if ($User) {
                 $Photo = $User['Photo'];
                 $Row['PhotoUrl'] = userUrl($User);
                 if (!$Photo || stringBeginsWith($Photo, 'http')) {
                     $Row['Photo'] = $Photo;
                 } else {
                     $Row['Photo'] = Gdn_Upload::url(changeBasename($Photo, 'n%s'));
                 }
             }
         }
     }
     $Data = $Row['Data'];
     if (isset($Data['ActivityUserIDs'])) {
         $Row['ActivityUserID'] = array_merge(array($Row['ActivityUserID']), $Data['ActivityUserIDs']);
         $Row['ActivityUserID_Count'] = val('ActivityUserID_Count', $Data);
     }
     if (isset($Data['RegardingUserIDs'])) {
         $Row['RegardingUserID'] = array_merge(array($Row['RegardingUserID']), $Data['RegardingUserIDs']);
         $Row['RegardingUserID_Count'] = val('RegardingUserID_Count', $Data);
     }
     $Row['Url'] = ExternalUrl($Row['Route']);
     if ($Row['HeadlineFormat']) {
         $Row['Headline'] = formatString($Row['HeadlineFormat'], $Row);
     } else {
         $Row['Headline'] = Gdn_Format::activityHeadline($Row);
     }
 }
示例#13
0
    $BannedPhoto = c('Garden.BannedPhoto', 'http://cdn.vanillaforums.com/images/banned_large.png');
    if ($BannedPhoto) {
        $Photo = Gdn_Upload::url($BannedPhoto);
    }
}
if ($Photo) {
    ?>
    <div class="Photo PhotoWrap PhotoWrapLarge <?php 
    echo val('_CssClass', $User);
    ?>
">
        <?php 
    if (IsUrl($Photo)) {
        $Img = img($Photo, array('class' => 'ProfilePhotoLarge'));
    } else {
        $Img = img(Gdn_Upload::url(changeBasename($Photo, 'p%s')), array('class' => 'ProfilePhotoLarge'));
    }
    if (!$User->Banned && c('Garden.Profile.EditPhotos', true) && (Gdn::session()->UserID == $User->UserID || Gdn::session()->checkPermission('Garden.Users.Edit'))) {
        echo anchor(Wrap(t('Change Picture')), '/profile/picture?userid=' . $User->UserID, 'ChangePicture');
    }
    echo $Img;
    ?>
    </div>
<?php 
} else {
    if ($User->UserID == Gdn::session()->UserID || Gdn::session()->checkPermission('Garden.Users.Edit')) {
        ?>
    <div
        class="Photo"><?php 
        echo anchor(t('Add a Profile Picture'), '/profile/picture?userid=' . $User->UserID, 'AddPicture BigButton');
        ?>
示例#14
0
if (!defined('APPLICATION')) {
    exit;
}
?>
<h1><?php 
if ($this->Addon['File'] == '') {
    echo 'The requested addon could not be found';
} else {
    echo 'Downloading: ' . htmlspecialchars($this->Addon['Name']) . ' version ' . $this->Addon['Version'];
    ?>
</h1>
<div class="Box DownloadInfo">
    <strong>Your download should begin shortly</strong>
    <p>If your download does not begin right away, <a href="<?php 
    echo Gdn_Upload::url($this->Addon['File']);
    ?>
">click here to download now</a>.</p>

    <strong>Need help installing this addon?</strong>
    <p>There should be a readme file in the addon with more specific instructions on how to install it. If you are still having problems, <a href="//vanillaforums.org/discussions">ask for help on the community forums</a>.</p>

    <strong>Note</strong>
    <p>Vanilla Forums Inc cannot be held liable for issues that arise from the download or use of these addons.</p>

    <strong>Now what?</strong>
    <p>Head on back to the <a href="<?php 
    echo url('/addon/' . $this->Addon['AddonID']);
    ?>
"><?php 
    echo $this->Addon['Name'];
示例#15
0
 /**
  * Calculate the dynamic fields of a category.
  *
  * @param array &$category The category to calculate.
  */
 private static function calculate(&$category)
 {
     $category['CountAllDiscussions'] = $category['CountDiscussions'];
     $category['CountAllComments'] = $category['CountComments'];
     $category['Url'] = self::categoryUrl($category, false, '/');
     if (val('Photo', $category)) {
         $category['PhotoUrl'] = Gdn_Upload::url($category['Photo']);
     } else {
         $category['PhotoUrl'] = '';
     }
     self::calculateDisplayAs($category);
     if (!val('CssClass', $category)) {
         $category['CssClass'] = 'Category-' . $category['UrlCode'];
     }
     if (isset($category['AllowedDiscussionTypes']) && is_string($category['AllowedDiscussionTypes'])) {
         $category['AllowedDiscussionTypes'] = dbdecode($category['AllowedDiscussionTypes']);
     }
 }
示例#16
0
}
if (!$User) {
    return;
}
$Photo = $User->Photo;
if ($Photo) {
    if (!IsUrl($Photo)) {
        $Photo = Gdn_Upload::url(changeBasename($Photo, 'p%s'));
    }
} else {
    $Photo = UserModel::getDefaultAvatarUrl($User, 'profile');
}
if ($User->Banned) {
    $BannedPhoto = c('Garden.BannedPhoto', 'https://c3409409.ssl.cf0.rackcdn.com/images/banned_large.png');
    if ($BannedPhoto) {
        $Photo = Gdn_Upload::url($BannedPhoto);
    }
}
if ($Photo) {
    ?>
    <div class="Photo PhotoWrap PhotoWrapLarge <?php 
    echo val('_CssClass', $User);
    ?>
">
        <?php 
    $Img = img($Photo, array('class' => 'ProfilePhotoLarge'));
    if (!$User->Banned && c('Garden.Profile.EditPhotos', true) && (Gdn::session()->UserID == $User->UserID || Gdn::session()->checkPermission('Garden.Users.Edit'))) {
        echo anchor(Wrap(t('Change Picture')), '/profile/picture?userid=' . $User->UserID, 'ChangePicture');
    }
    echo $Img;
    ?>
示例#17
0
 /**
  * Calculate the dynamic fields of a category.
  *
  * @param array &$category The category to calculate.
  */
 private static function calculate(&$category)
 {
     $category['CountAllDiscussions'] = $category['CountDiscussions'];
     $category['CountAllComments'] = $category['CountComments'];
     $category['Url'] = self::categoryUrl($category, false, '/');
     $category['ChildIDs'] = array();
     if (val('Photo', $category)) {
         $category['PhotoUrl'] = Gdn_Upload::url($category['Photo']);
     } else {
         $category['PhotoUrl'] = '';
     }
     if ($category['DisplayAs'] == 'Default') {
         if ($category['Depth'] <= c('Vanilla.Categories.NavDepth', 0)) {
             $category['DisplayAs'] = 'Categories';
         } elseif ($category['Depth'] == c('Vanilla.Categories.NavDepth', 0) + 1 && c('Vanilla.Categories.DoHeadings')) {
             $category['DisplayAs'] = 'Heading';
         } else {
             $category['DisplayAs'] = 'Discussions';
         }
     }
     if (!val('CssClass', $category)) {
         $category['CssClass'] = 'Category-' . $category['UrlCode'];
     }
     if (isset($category['AllowedDiscussionTypes']) && is_string($category['AllowedDiscussionTypes'])) {
         $category['AllowedDiscussionTypes'] = dbdecode($category['AllowedDiscussionTypes']);
     }
 }
示例#18
0
 /**
  * Render the entire head module.
  */
 public function toString()
 {
     // Add the canonical Url if necessary.
     if (method_exists($this->_Sender, 'CanonicalUrl') && !c('Garden.Modules.NoCanonicalUrl', false)) {
         $CanonicalUrl = $this->_Sender->canonicalUrl();
         if (!isUrl($CanonicalUrl)) {
             $CanonicalUrl = Gdn::router()->ReverseRoute($CanonicalUrl);
         }
         $this->_Sender->canonicalUrl($CanonicalUrl);
         //            $CurrentUrl = url('', true);
         //            if ($CurrentUrl != $CanonicalUrl) {
         $this->addTag('link', array('rel' => 'canonical', 'href' => $CanonicalUrl));
         //            }
     }
     // Include facebook open-graph meta information.
     if ($FbAppID = c('Plugins.Facebook.ApplicationID')) {
         $this->addTag('meta', array('property' => 'fb:app_id', 'content' => $FbAppID));
     }
     $SiteName = c('Garden.Title', '');
     if ($SiteName != '') {
         $this->addTag('meta', array('property' => 'og:site_name', 'content' => $SiteName));
     }
     $Title = Gdn_Format::text($this->title('', true));
     if ($Title != '') {
         $this->addTag('meta', array('property' => 'og:title', 'itemprop' => 'name', 'content' => $Title));
     }
     if (isset($CanonicalUrl)) {
         $this->addTag('meta', array('property' => 'og:url', 'content' => $CanonicalUrl));
     }
     if ($Description = $this->_Sender->Description()) {
         $this->addTag('meta', array('name' => 'description', 'property' => 'og:description', 'itemprop' => 'description', 'content' => $Description));
     }
     // Default to the site logo if there were no images provided by the controller.
     if (count($this->_Sender->Image()) == 0) {
         $Logo = c('Garden.ShareImage', c('Garden.Logo', ''));
         if ($Logo != '') {
             // Fix the logo path.
             if (stringBeginsWith($Logo, 'uploads/')) {
                 $Logo = substr($Logo, strlen('uploads/'));
             }
             $Logo = Gdn_Upload::url($Logo);
             $this->addTag('meta', array('property' => 'og:image', 'itemprop' => 'image', 'content' => $Logo));
         }
     } else {
         foreach ($this->_Sender->Image() as $Img) {
             $this->addTag('meta', array('property' => 'og:image', 'itemprop' => 'image', 'content' => $Img));
         }
     }
     $this->fireEvent('BeforeToString');
     $Tags = $this->_Tags;
     // Make sure that css loads before js (for jquery)
     usort($this->_Tags, array('HeadModule', 'TagCmp'));
     // "link" comes before "script"
     $Tags2 = $this->_Tags;
     // Start with the title.
     $Head = '<title>' . Gdn_Format::text($this->title()) . "</title>\n";
     $TagStrings = array();
     // Loop through each tag.
     foreach ($this->_Tags as $Index => $Attributes) {
         $Tag = $Attributes[self::TAG_KEY];
         // Inline the content of the tag, if necessary.
         if (val('_hint', $Attributes) == 'inline') {
             $Path = val('_path', $Attributes);
             if (!stringBeginsWith($Path, 'http')) {
                 $Attributes[self::CONTENT_KEY] = file_get_contents($Path);
                 if (isset($Attributes['src'])) {
                     $Attributes['_src'] = $Attributes['src'];
                     unset($Attributes['src']);
                 }
                 if (isset($Attributes['href'])) {
                     $Attributes['_href'] = $Attributes['href'];
                     unset($Attributes['href']);
                 }
             }
         }
         // If we set an IE conditional AND a "Not IE" condition, we will need to make a second pass.
         do {
             // Reset tag string
             $TagString = '';
             // IE conditional? Validates condition.
             $IESpecific = isset($Attributes['_ie']) && preg_match('/((l|g)t(e)? )?IE [0-9\\.]/', $Attributes['_ie']);
             // Only allow $NotIE if we're not doing a conditional this loop.
             $NotIE = !$IESpecific && isset($Attributes['_notie']);
             // Open IE conditional tag
             if ($IESpecific) {
                 $TagString .= '<!--[if ' . $Attributes['_ie'] . ']>';
             }
             if ($NotIE) {
                 $TagString .= '<!--[if !IE]> -->';
             }
             // Build tag
             $TagString .= '  <' . $Tag . Attribute($Attributes, '_');
             if (array_key_exists(self::CONTENT_KEY, $Attributes)) {
                 $TagString .= '>' . $Attributes[self::CONTENT_KEY] . '</' . $Tag . '>';
             } elseif ($Tag == 'script') {
                 $TagString .= '></script>';
             } else {
                 $TagString .= ' />';
             }
             // Close IE conditional tag
             if ($IESpecific) {
                 $TagString .= '<![endif]-->';
             }
             if ($NotIE) {
                 $TagString .= '<!-- <![endif]-->';
             }
             // Cleanup (prevent infinite loop)
             if ($IESpecific) {
                 unset($Attributes['_ie']);
             }
             $TagStrings[] = $TagString;
         } while ($IESpecific && isset($Attributes['_notie']));
         // We need a second pass
     }
     //endforeach
     $Head .= implode("\n", array_unique($TagStrings));
     foreach ($this->_Strings as $String) {
         $Head .= $String;
         $Head .= "\n";
     }
     return $Head;
 }
示例#19
0
 /**
  * Create or update a comment.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $DiscussionID Unique ID to add the comment to. If blank, this method will throw an error.
  */
 public function comment($DiscussionID = '')
 {
     // Get $DiscussionID from RequestArgs if valid
     if ($DiscussionID == '' && count($this->RequestArgs)) {
         if (is_numeric($this->RequestArgs[0])) {
             $DiscussionID = $this->RequestArgs[0];
         }
     }
     // If invalid $DiscussionID, get from form.
     $this->Form->setModel($this->CommentModel);
     $DiscussionID = is_numeric($DiscussionID) ? $DiscussionID : $this->Form->getFormValue('DiscussionID', 0);
     // Set discussion data
     $this->DiscussionID = $DiscussionID;
     $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID);
     // Is this an embedded comment being posted to a discussion that doesn't exist yet?
     $vanilla_type = $this->Form->getFormValue('vanilla_type', '');
     $vanilla_url = $this->Form->getFormValue('vanilla_url', '');
     $vanilla_category_id = $this->Form->getFormValue('vanilla_category_id', '');
     $Attributes = array('ForeignUrl' => $vanilla_url);
     $vanilla_identifier = $this->Form->getFormValue('vanilla_identifier', '');
     $isEmbeddedComments = $vanilla_url != '' && $vanilla_identifier != '';
     // Only allow vanilla identifiers of 32 chars or less - md5 if larger
     if (strlen($vanilla_identifier) > 32) {
         $Attributes['vanilla_identifier'] = $vanilla_identifier;
         $vanilla_identifier = md5($vanilla_identifier);
     }
     if (!$Discussion && $isEmbeddedComments) {
         $Discussion = $Discussion = $this->DiscussionModel->getForeignID($vanilla_identifier, $vanilla_type);
         if ($Discussion) {
             $this->DiscussionID = $DiscussionID = $Discussion->DiscussionID;
             $this->Form->setValue('DiscussionID', $DiscussionID);
         }
     }
     // If so, create it!
     if (!$Discussion && $isEmbeddedComments) {
         // Add these values back to the form if they exist!
         $this->Form->addHidden('vanilla_identifier', $vanilla_identifier);
         $this->Form->addHidden('vanilla_type', $vanilla_type);
         $this->Form->addHidden('vanilla_url', $vanilla_url);
         $this->Form->addHidden('vanilla_category_id', $vanilla_category_id);
         $PageInfo = fetchPageInfo($vanilla_url);
         if (!($Title = $this->Form->getFormValue('Name'))) {
             $Title = val('Title', $PageInfo, '');
             if ($Title == '') {
                 $Title = t('Undefined discussion subject.');
                 if (!empty($PageInfo['Exception']) && $PageInfo['Exception'] === "Couldn't connect to host.") {
                     $Title .= ' ' . t('Page timed out.');
                 }
             }
         }
         $Description = val('Description', $PageInfo, '');
         $Images = val('Images', $PageInfo, array());
         $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here');
         if (!$Description && count($Images) == 0) {
             $Body = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
         } else {
             $Body = formatString('
         <div class="EmbeddedContent">{Image}<strong>{Title}</strong>
            <p>{Excerpt}</p>
            <p><a href="{Url}">{LinkText}</a></p>
            <div class="ClearFix"></div>
         </div>', array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? img(val(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $vanilla_url, 'LinkText' => $LinkText));
         }
         if ($Body == '') {
             $Body = $vanilla_url;
         }
         if ($Body == '') {
             $Body = t('Undefined discussion body.');
         }
         // Validate the CategoryID for inserting.
         $Category = CategoryModel::categories($vanilla_category_id);
         if (!$Category) {
             $vanilla_category_id = c('Vanilla.Embed.DefaultCategoryID', 0);
             if ($vanilla_category_id <= 0) {
                 // No default category defined, so grab the first non-root category and use that.
                 $vanilla_category_id = $this->DiscussionModel->SQL->select('CategoryID')->from('Category')->where('CategoryID >', 0)->get()->firstRow()->CategoryID;
                 // No categories in the db? default to 0
                 if (!$vanilla_category_id) {
                     $vanilla_category_id = 0;
                 }
             }
         } else {
             $vanilla_category_id = $Category['CategoryID'];
         }
         $EmbedUserID = c('Garden.Embed.UserID');
         if ($EmbedUserID) {
             $EmbedUser = Gdn::userModel()->getID($EmbedUserID);
         }
         if (!$EmbedUserID || !$EmbedUser) {
             $EmbedUserID = Gdn::userModel()->getSystemUserID();
         }
         $EmbeddedDiscussionData = array('InsertUserID' => $EmbedUserID, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime(), 'CategoryID' => $vanilla_category_id, 'ForeignID' => $vanilla_identifier, 'Type' => $vanilla_type, 'Name' => $Title, 'Body' => $Body, 'Format' => 'Html', 'Attributes' => dbencode($Attributes));
         $this->EventArguments['Discussion'] =& $EmbeddedDiscussionData;
         $this->fireEvent('BeforeEmbedDiscussion');
         $DiscussionID = $this->DiscussionModel->SQL->insert('Discussion', $EmbeddedDiscussionData);
         $ValidationResults = $this->DiscussionModel->validationResults();
         if (count($ValidationResults) == 0 && $DiscussionID > 0) {
             $this->Form->addHidden('DiscussionID', $DiscussionID);
             // Put this in the form so reposts won't cause new discussions.
             $this->Form->setFormValue('DiscussionID', $DiscussionID);
             // Put this in the form values so it is used when saving comments.
             $this->setJson('DiscussionID', $DiscussionID);
             $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => false));
             // Update the category discussion count
             if ($vanilla_category_id > 0) {
                 $this->DiscussionModel->updateDiscussionCount($vanilla_category_id, $DiscussionID);
             }
         }
     }
     // If no discussion was found, error out
     if (!$Discussion) {
         $this->Form->addError(t('Failed to find discussion for commenting.'));
     }
     /**
      * Special care is taken for embedded comments.  Since we don't currently use an advanced editor for these
      * comments, we may need to apply certain filters and fixes to the data to maintain its intended display
      * with the input format (e.g. maintaining newlines).
      */
     if ($isEmbeddedComments) {
         $inputFormatter = $this->Form->getFormValue('Format', c('Garden.InputFormatter'));
         switch ($inputFormatter) {
             case 'Wysiwyg':
                 $this->Form->setFormValue('Body', nl2br($this->Form->getFormValue('Body')));
                 break;
         }
     }
     $PermissionCategoryID = val('PermissionCategoryID', $Discussion);
     // Setup head
     $this->addJsFile('jquery.autosize.min.js');
     $this->addJsFile('autosave.js');
     $this->addJsFile('post.js');
     // Setup comment model, $CommentID, $DraftID
     $Session = Gdn::session();
     $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : '';
     $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : '';
     $this->EventArguments['CommentID'] = $CommentID;
     $this->EventArguments['DraftID'] = $DraftID;
     // Determine whether we are editing
     $Editing = $CommentID > 0 || $DraftID > 0;
     $this->EventArguments['Editing'] = $Editing;
     // If closed, cancel & go to discussion
     if ($Discussion && $Discussion->Closed == 1 && !$Editing && !$Session->checkPermission('Vanilla.Discussions.Close', true, 'Category', $PermissionCategoryID)) {
         redirect(DiscussionUrl($Discussion));
     }
     // Add hidden IDs to form
     $this->Form->addHidden('DiscussionID', $DiscussionID);
     $this->Form->addHidden('CommentID', $CommentID);
     $this->Form->addHidden('DraftID', $DraftID, true);
     // Check permissions
     if ($Discussion && $Editing) {
         // Permission to edit
         if ($this->Comment->InsertUserID != $Session->UserID) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure that content can (still) be edited.
         $EditContentTimeout = c('Garden.EditContentTimeout', -1);
         $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time();
         if (!$CanEdit) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure only moderators can edit closed things
         if ($Discussion->Closed) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         $this->Form->setFormValue('CommentID', $CommentID);
     } elseif ($Discussion) {
         // Permission to add
         $this->permission('Vanilla.Comments.Add', true, 'Category', $Discussion->PermissionCategoryID);
     }
     if ($this->Form->authenticatedPostBack()) {
         // Save as a draft?
         $FormValues = $this->Form->formValues();
         $FormValues = $this->CommentModel->filterForm($FormValues);
         if (!$Editing) {
             unset($FormValues['CommentID']);
         }
         if ($DraftID == 0) {
             $DraftID = $this->Form->getFormValue('DraftID', 0);
         }
         $Type = GetIncomingValue('Type');
         $Draft = $Type == 'Draft';
         $this->EventArguments['Draft'] = $Draft;
         $Preview = $Type == 'Preview';
         if ($Draft) {
             $DraftID = $this->DraftModel->save($FormValues);
             $this->Form->addHidden('DraftID', $DraftID, true);
             $this->Form->setValidationResults($this->DraftModel->validationResults());
         } elseif (!$Preview) {
             // Fix an undefined title if we can.
             if ($this->Form->getFormValue('Name') && val('Name', $Discussion) == t('Undefined discussion subject.')) {
                 $Set = array('Name' => $this->Form->getFormValue('Name'));
                 if (isset($vanilla_url) && $vanilla_url && strpos(val('Body', $Discussion), t('Undefined discussion subject.')) !== false) {
                     $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here');
                     $Set['Body'] = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
                 }
                 $this->DiscussionModel->setField(val('DiscussionID', $Discussion), $Set);
             }
             $Inserted = !$CommentID;
             $CommentID = $this->CommentModel->save($FormValues);
             // The comment is now half-saved.
             if (is_numeric($CommentID) && $CommentID > 0) {
                 if (in_array($this->deliveryType(), array(DELIVERY_TYPE_ALL, DELIVERY_TYPE_DATA))) {
                     $this->CommentModel->save2($CommentID, $Inserted, true, true);
                 } else {
                     $this->jsonTarget('', url("/post/comment2.json?commentid={$CommentID}&inserted={$Inserted}"), 'Ajax');
                 }
                 // $Discussion = $this->DiscussionModel->getID($DiscussionID);
                 $Comment = $this->CommentModel->getID($CommentID, DATASET_TYPE_OBJECT, array('Slave' => false));
                 $this->EventArguments['Discussion'] = $Discussion;
                 $this->EventArguments['Comment'] = $Comment;
                 $this->fireEvent('AfterCommentSave');
             } elseif ($CommentID === SPAM || $CommentID === UNAPPROVED) {
                 $this->StatusMessage = t('CommentRequiresApprovalStatus', 'Your comment will appear after it is approved.');
             }
             $this->Form->setValidationResults($this->CommentModel->validationResults());
             if ($CommentID > 0 && $DraftID > 0) {
                 $this->DraftModel->delete($DraftID);
             }
         }
         // Handle non-ajax requests first:
         if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
             if ($this->Form->errorCount() == 0) {
                 // Make sure that this form knows what comment we are editing.
                 if ($CommentID > 0) {
                     $this->Form->addHidden('CommentID', $CommentID);
                 }
                 // If the comment was not a draft
                 if (!$Draft) {
                     // Redirect to the new comment.
                     if ($CommentID > 0) {
                         redirect("discussion/comment/{$CommentID}/#Comment_{$CommentID}");
                     } elseif ($CommentID == SPAM) {
                         $this->setData('DiscussionUrl', DiscussionUrl($Discussion));
                         $this->View = 'Spam';
                     }
                 } elseif ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $this->Comment = new stdClass();
                     $this->Comment->InsertUserID = $Session->User->UserID;
                     $this->Comment->InsertName = $Session->User->Name;
                     $this->Comment->InsertPhoto = $Session->User->Photo;
                     $this->Comment->DateInserted = Gdn_Format::date();
                     $this->Comment->Body = val('Body', $FormValues, '');
                     $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
                     $this->addAsset('Content', $this->fetchView('preview'));
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
             }
         } else {
             // Handle ajax-based requests
             if ($this->Form->errorCount() > 0) {
                 // Return the form errors
                 $this->errorMessage($this->Form->errors());
             } else {
                 // Make sure that the ajax request form knows about the newly created comment or draft id
                 $this->setJson('CommentID', $CommentID);
                 $this->setJson('DraftID', $DraftID);
                 if ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $this->Comment = new stdClass();
                     $this->Comment->InsertUserID = $Session->User->UserID;
                     $this->Comment->InsertName = $Session->User->Name;
                     $this->Comment->InsertPhoto = $Session->User->Photo;
                     $this->Comment->DateInserted = Gdn_Format::date();
                     $this->Comment->Body = val('Body', $FormValues, '');
                     $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
                     $this->View = 'preview';
                 } elseif (!$Draft) {
                     // If the comment was not a draft
                     // If Editing a comment
                     if ($Editing) {
                         // Just reload the comment in question
                         $this->Offset = 1;
                         $Comments = $this->CommentModel->getIDData($CommentID, array('Slave' => false));
                         $this->setData('Comments', $Comments);
                         $this->setData('Discussion', $Discussion);
                         // Load the discussion
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         // Also define the discussion url in case this request came from the post screen and needs to be redirected to the discussion
                         $this->setJson('DiscussionUrl', DiscussionUrl($this->Discussion) . '#Comment_' . $CommentID);
                     } else {
                         // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments.
                         $OrderBy = valr('0.0', $this->CommentModel->orderBy());
                         //                     $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID'));
                         //							$DisplayNewCommentOnly = $this->Form->getFormValue('DisplayNewCommentOnly');
                         //                     if (!$Redirect) {
                         //                        // Otherwise load all new comments that the user hasn't seen yet
                         //                        $LastCommentID = $this->Form->getFormValue('LastCommentID');
                         //                        if (!is_numeric($LastCommentID))
                         //                           $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly
                         //
                         //                        // Don't reload the first comment if this new comment is the first one.
                         //                        $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID);
                         //                        // Do not load more than a single page of data...
                         //                        $Limit = c('Vanilla.Comments.PerPage', 30);
                         //
                         //                        // Redirect if the new new comment isn't on the same page.
                         //                        $Redirect |= !$DisplayNewCommentOnly && PageNumber($this->Offset, $Limit) != PageNumber($Discussion->CountComments - 1, $Limit);
                         //                     }
                         //                     if ($Redirect) {
                         //                        // The user posted a comment on a page other than the last one, so just redirect to the last page.
                         //                        $this->RedirectUrl = Gdn::request()->Url("discussion/comment/$CommentID/#Comment_$CommentID", true);
                         //                     } else {
                         //                        // Make sure to load all new comments since the page was last loaded by this user
                         //								if ($DisplayNewCommentOnly)
                         $this->Offset = $this->CommentModel->GetOffset($CommentID);
                         $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => false));
                         $this->setData('Comments', $Comments);
                         $this->setData('NewComments', true);
                         $this->ClassName = 'DiscussionController';
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         //                     }
                         // Make sure to set the user's discussion watch records
                         $CountComments = $this->CommentModel->getCount($DiscussionID);
                         $Limit = is_object($this->data('Comments')) ? $this->data('Comments')->numRows() : $Discussion->CountComments;
                         $Offset = $CountComments - $Limit;
                         $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments);
                     }
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
                 // And update the draft count
                 $UserModel = Gdn::userModel();
                 $CountDrafts = $UserModel->getAttribute($Session->UserID, 'CountDrafts', 0);
                 $this->setJson('MyDrafts', t('My Drafts'));
                 $this->setJson('CountDrafts', $CountDrafts);
             }
         }
     } elseif ($this->Request->isPostBack()) {
         throw new Gdn_UserException(t('Invalid CSRF token.', 'Invalid CSRF token. Please try again.'), 401);
     } else {
         // Load form
         if (isset($this->Comment)) {
             $this->Form->setData((array) $this->Comment);
         }
     }
     // Include data for FireEvent
     if (property_exists($this, 'Discussion')) {
         $this->EventArguments['Discussion'] = $this->Discussion;
     }
     if (property_exists($this, 'Comment')) {
         $this->EventArguments['Comment'] = $this->Comment;
     }
     $this->fireEvent('BeforeCommentRender');
     if ($this->deliveryType() == DELIVERY_TYPE_DATA) {
         if ($this->data('Comments') instanceof Gdn_DataSet) {
             $Comment = $this->data('Comments')->firstRow(DATASET_TYPE_ARRAY);
             if ($Comment) {
                 $Photo = $Comment['InsertPhoto'];
                 if (strpos($Photo, '//') === false) {
                     $Photo = Gdn_Upload::url(changeBasename($Photo, 'n%s'));
                 }
                 $Comment['InsertPhoto'] = $Photo;
             }
             $this->Data = array('Comment' => $Comment);
         }
         $this->RenderData($this->Data);
     } else {
         require_once $this->fetchViewLocation('helper_functions', 'Discussion');
         // Render default view.
         $this->render();
     }
 }
示例#20
0
 /**
  *
  *
  * @param string $Path
  * @param Gdn_Controller $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', htmlspecialchars($BodyIdentifier));
     //$Smarty->assign('Config', Gdn::Config());
     // Assign some information about the user.
     $Session = Gdn::session();
     if ($Session->isValid()) {
         $User = array('Name' => htmlspecialchars($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 {
             $Photo = UserModel::getDefaultAvatarUrl($Session->User);
         }
         $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('_', '-', Gdn::locale()->language(true)));
     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);
     // 2016-07-07 Linc: Request used to return blank for homepage.
     // Now it returns defaultcontroller. This restores BC behavior.
     $isHomepage = val('isHomepage', $Controller->Data);
     $Path = $isHomepage ? "" : Gdn::request()->path();
     $Smarty->assign('Path', $Path);
     $Smarty->assign('Homepage', $isHomepage);
     // true/false
     // Assign the controller data last so the controllers override any default data.
     $Smarty->assign($Controller->Data);
     $security = new SmartySecurityVanilla($Smarty);
     $security->php_handling = Smarty::PHP_REMOVE;
     $security->allow_constants = false;
     $security->allow_super_globals = false;
     $security->streams = null;
     $security->setPhpFunctions(array_merge($security->php_functions, ['array', 'category', 'checkPermission', 'inSection', 'inCategory', 'ismobile', 'multiCheckPermission', 'getValue', 'setValue', 'url', 'useragenttype']));
     $security->php_modifiers = array_merge($security->php_functions, array('sprintf'));
     $Smarty->enableSecurity($security);
 }
示例#21
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;
 }
 /**
  * Set user's photo (avatar).
  *
  * @since 2.0.0
  * @access public
  * @param mixed $UserReference Unique identifier, possible username or ID.
  * @param string $Username .
  */
 public function picture($UserReference = '', $Username = '', $UserID = '')
 {
     if (!Gdn::session()->checkRankedPermission(c('Garden.Profile.EditPhotos', true))) {
         throw forbiddenException('@Editing user photos has been disabled.');
     }
     // Permission checks
     $this->permission(array('Garden.Profiles.Edit', 'Moderation.Profiles.Edit', 'Garden.ProfilePicture.Edit'), false);
     $Session = Gdn::session();
     if (!$Session->isValid()) {
         $this->Form->addError('You must be authenticated in order to use this form.');
     }
     // Check ability to manipulate image
     $ImageManipOk = false;
     if (function_exists('gd_info')) {
         $GdInfo = gd_info();
         $GdVersion = preg_replace('/[a-z ()]+/i', '', $GdInfo['GD Version']);
         if ($GdVersion < 2) {
             throw new Exception(sprintf(t("This installation of GD is too old (v%s). Vanilla requires at least version 2 or compatible."), $GdVersion));
         }
     } else {
         throw new Exception(sprintf(t("Unable to detect PHP GD installed on this system. Vanilla requires GD version 2 or better.")));
     }
     // Get user data & prep form.
     if ($this->Form->authenticatedPostBack() && $this->Form->getFormValue('UserID')) {
         $UserID = $this->Form->getFormValue('UserID');
     }
     $this->getUserInfo($UserReference, $Username, $UserID, true);
     $this->Form->setModel($this->UserModel);
     if ($this->Form->authenticatedPostBack() === true) {
         $this->Form->setFormValue('UserID', $this->User->UserID);
         // Set user's Photo attribute to a URL, provided the current user has proper permission to do so.
         $photoUrl = $this->Form->getFormValue('Url', false);
         if ($photoUrl && Gdn::session()->checkPermission('Garden.Settings.Manage')) {
             if (isUrl($photoUrl) && filter_var($photoUrl, FILTER_VALIDATE_URL)) {
                 $UserPhoto = $photoUrl;
             } else {
                 $this->Form->addError('Invalid photo URL');
             }
         } else {
             $UploadImage = new Gdn_UploadImage();
             try {
                 // Validate the upload
                 $TmpImage = $UploadImage->ValidateUpload('Picture');
                 // Generate the target image name.
                 $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS, '', true);
                 $Basename = pathinfo($TargetImage, PATHINFO_BASENAME);
                 $Subdir = stringBeginsWith(dirname($TargetImage), PATH_UPLOADS . '/', false, true);
                 // Delete any previously uploaded image.
                 $UploadImage->delete(changeBasename($this->User->Photo, 'p%s'));
                 // Save the uploaded image in profile size.
                 $Props = $UploadImage->SaveImageAs($TmpImage, "userpics/{$Subdir}/p{$Basename}", c('Garden.Profile.MaxHeight', 1000), c('Garden.Profile.MaxWidth', 250), array('SaveGif' => c('Garden.Thumbnail.SaveGif')));
                 $UserPhoto = sprintf($Props['SaveFormat'], "userpics/{$Subdir}/{$Basename}");
                 //            // Save the uploaded image in preview size
                 //            $UploadImage->SaveImageAs(
                 //               $TmpImage,
                 //               'userpics/t'.$ImageBaseName,
                 //               Gdn::config('Garden.Preview.MaxHeight', 100),
                 //               Gdn::config('Garden.Preview.MaxWidth', 75)
                 //            );
                 // Save the uploaded image in thumbnail size
                 $ThumbSize = Gdn::config('Garden.Thumbnail.Size', 40);
                 $UploadImage->saveImageAs($TmpImage, "userpics/{$Subdir}/n{$Basename}", $ThumbSize, $ThumbSize, array('Crop' => true, 'SaveGif' => c('Garden.Thumbnail.SaveGif')));
             } catch (Exception $Ex) {
                 // Throw the exception on API calls.
                 if ($this->deliveryType() === DELIVERY_TYPE_DATA) {
                     throw $Ex;
                 }
                 $this->Form->addError($Ex);
             }
         }
         // If there were no errors, associate the image with the user
         if ($this->Form->errorCount() == 0) {
             if (!$this->UserModel->save(array('UserID' => $this->User->UserID, 'Photo' => $UserPhoto), array('CheckExisting' => true))) {
                 $this->Form->setValidationResults($this->UserModel->validationResults());
             } else {
                 $this->User->Photo = $UserPhoto;
                 setValue('Photo', $this->Data['Profile'], $UserPhoto);
                 setValue('PhotoUrl', $this->Data['Profile'], Gdn_Upload::url(changeBasename($UserPhoto, 'n%s')));
             }
         }
         // If there were no problems, redirect back to the user account
         if ($this->Form->errorCount() == 0 && $this->deliveryType() !== DELIVERY_TYPE_DATA) {
             $this->informMessage(sprite('Check', 'InformSprite') . t('Your changes have been saved.'), 'Dismissable AutoDismiss HasSprite');
             redirect($this->deliveryType() == DELIVERY_TYPE_VIEW ? userUrl($this->User) : userUrl($this->User, '', 'picture'));
         }
     }
     if ($this->Form->errorCount() > 0 && $this->deliveryType() !== DELIVERY_TYPE_DATA) {
         $this->deliveryType(DELIVERY_TYPE_ALL);
     }
     $this->title(t('Change Picture'));
     $this->_setBreadcrumbs(t('Change My Picture'), userUrl($this->User, '', 'picture'));
     $this->render();
 }
示例#23
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'));
 } elseif ($OpenCount > $CountRight) {
     // Or are we closing open list and list items?
     while ($OpenCount > $CountRight) {
         $OpenCount--;
         echo "</li>\n</ol>\n";
     }
     echo '</li>';
 } elseif ($Loop > 0) {
     // Or are we closing an open list item?
     echo "</li>";
 }
 echo "\n" . '<li id="list_' . $Category->CategoryID . '">';
 // DEBUG: echo wrap($Category->Name.' [countright: '.$CountRight.' lastcount: '.$LastRight.' opencount: '.$OpenCount.']', 'div');
 $CategoryUrl = CategoryUrl($Category);
 if ($Category->Photo) {
     $Photo = img(Gdn_Upload::url($Category->Photo), array('class' => 'CategoryPhoto'));
 } else {
     $Photo = '';
 }
 echo wrap('<table' . ($OpenCount > 0 ? ' class="Indented"' : '') . '>
    <tr>
       <td>
          ' . $Photo . '
          <strong>' . htmlspecialchars($Category->Name) . '</strong>
          ' . anchor(htmlspecialchars(rawurldecode($CategoryUrl)), $CategoryUrl) . '
          ' . Wrap($Category->Description, 'blockquote') . '
          ' . '
       </td>
       <td class="Buttons">' . anchor(t('Edit'), 'vanilla/settings/editcategory/' . $Category->CategoryID, 'SmallButton') . ($CanDelete ? anchor(t('Delete'), 'vanilla/settings/deletecategory/' . $Category->CategoryID, 'SmallButton') : '') . '</td>
    </tr>
 </table>', 'div');
示例#25
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');
 }
示例#26
0
 /**
  * Takes a user object, and writes out an anchor of the user's icon to the user's profile.
  *
  * @param object|array $User A user object or array.
  * @param array $Options
  */
 function userPhoto($User, $Options = array())
 {
     if (is_string($Options)) {
         $Options = array('LinkClass' => $Options);
     }
     if ($Px = val('Px', $Options)) {
         $User = userBuilder($User, $Px);
     } else {
         $User = (object) $User;
     }
     $LinkClass = concatSep(' ', val('LinkClass', $Options, ''), 'PhotoWrap');
     $ImgClass = val('ImageClass', $Options, 'ProfilePhoto');
     $Size = val('Size', $Options);
     if ($Size) {
         $LinkClass .= " PhotoWrap{$Size}";
         $ImgClass .= " {$ImgClass}{$Size}";
     } else {
         $ImgClass .= " {$ImgClass}Medium";
         // backwards compat
     }
     $FullUser = Gdn::userModel()->getID(val('UserID', $User), DATASET_TYPE_ARRAY);
     $UserCssClass = val('_CssClass', $FullUser);
     if ($UserCssClass) {
         $LinkClass .= ' ' . $UserCssClass;
     }
     $LinkClass = $LinkClass == '' ? '' : ' class="' . $LinkClass . '"';
     $Photo = val('Photo', $User, val('PhotoUrl', $User));
     $Name = val('Name', $User);
     $Title = htmlspecialchars(val('Title', $Options, $Name));
     if ($FullUser && $FullUser['Banned']) {
         $Photo = c('Garden.BannedPhoto', 'http://cdn.vanillaforums.com/images/banned_large.png');
         $Title .= ' (' . t('Banned') . ')';
     }
     if (!$Photo && function_exists('UserPhotoDefaultUrl')) {
         $Photo = userPhotoDefaultUrl($User, $ImgClass);
     }
     if ($Photo) {
         if (!isUrl($Photo)) {
             $PhotoUrl = Gdn_Upload::url(changeBasename($Photo, 'n%s'));
         } else {
             $PhotoUrl = $Photo;
         }
         $Href = url(userUrl($User));
         return '<a title="' . $Title . '" href="' . $Href . '"' . $LinkClass . '>' . img($PhotoUrl, array('alt' => $Name, 'class' => $ImgClass)) . '</a>';
     } else {
         return '';
     }
 }
示例#27
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);
 }
    /**
     *
     *
     * @param $bbcode
     * @param $action
     * @param $name
     * @param $default
     * @param $params
     * @param $content
     * @return string
     */
    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];
            $src = htmlspecialchars(Gdn_Upload::url(val('Path', $media)));
            $name = htmlspecialchars(val('Name', $media));
            if (val('ImageWidth', $media)) {
                return <<<EOT
<div class="Attachment Image"><img src="{$src}" alt="{$name}" /></div>
EOT;
            } else {
                return anchor($name, $src, 'Attachment File');
            }
        }
        return '';
    }
 /**
  * Attach image to each discussion or comment.
  *
  * It will first perform a single request against the Media table, then filter out the ones that
  * exist per discussion or comment.
  *
  * @param multiple $Controller The controller.
  * @param string $Type The type of row, either discussion or comment.
  * @param array|object $row The row of data being attached to.
  */
 protected function attachUploadsToComment($Sender, $Type = 'comment', $row = null)
 {
     $param = ucfirst($Type) . 'ID';
     $foreignId = val($param, val(ucfirst($Type), $Sender->EventArguments));
     // Get all media for the page.
     $mediaList = $this->mediaCache($Sender);
     if (is_array($mediaList)) {
         // Filter out the ones that don't match.
         $attachments = array_filter($mediaList, function ($attachment) use($foreignId, $Type) {
             if (isset($attachment['ForeignID']) && $attachment['ForeignID'] == $foreignId && $attachment['ForeignTable'] == $Type) {
                 return true;
             }
         });
         if (count($attachments)) {
             // Loop through the attachments and add a flag if they are found in the source or not.
             $body = Gdn_Format::to(val('Body', $row), val('Format', $row));
             foreach ($attachments as &$attachment) {
                 $src = Gdn_Upload::url($attachment['Path']);
                 $src = preg_replace('`^https?:?`i', '', $src);
                 $src = preg_quote($src);
                 $regex = '`src=["\'](https?:?)?' . $src . '["\']`i';
                 $inbody = (bool) preg_match($regex, $body);
                 $attachment['InBody'] = $inbody;
             }
             $Sender->setData('_attachments', $attachments);
             $Sender->setData('_editorkey', strtolower($param . $foreignId));
             echo $Sender->fetchView($this->getView('attachments.php'));
         }
     }
 }
示例#30
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 = val('DateMarkedRead', $Category);
             $Row = val($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) val('Archived', $Category) || (bool) val('Unfollow', $Row, false));
             $Categories[$ID]['Following'] = $Following;
             // Calculate the read field.
             if ($DoHeadings && $Category['Depth'] <= 1) {
                 $Categories[$ID]['Read'] = false;
             } elseif ($DateMarkedRead) {
                 if (val('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 (!empty($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']);
     }
     // Translate name and description
     foreach ($IDs as $ID) {
         $Code = $Categories[$ID]['UrlCode'];
         $Categories[$ID]['Name'] = TranslateContent("Categories." . $Code . ".Name", $Categories[$ID]['Name']);
         $Categories[$ID]['Description'] = TranslateContent("Categories." . $Code . ".Description", $Categories[$ID]['Description']);
     }
 }