/**
  *
  *
  * @param $Result
  * @param $PageWhere
  * @param $DiscussionID
  * @param $Page
  * @param null $Limit
  */
 public function cachePageWhere($Result, $PageWhere, $DiscussionID, $Page, $Limit = null)
 {
     if (!$this->pageCache || !empty($this->_Where) || $this->_OrderBy[0][0] != 'c.DateInserted' || $this->_OrderBy[0][1] == 'desc') {
         return;
     }
     if (count($Result) == 0) {
         return;
     }
     $ConfigLimit = c('Vanilla.Comments.PerPage', 30);
     if (!$Limit) {
         $Limit = $ConfigLimit;
     }
     if ($Limit != $ConfigLimit) {
         return;
     }
     if (is_array($PageWhere)) {
         $Curr = array_values($PageWhere);
     } else {
         $Curr = false;
     }
     $New = array(GetValueR('0.DateInserted', $Result));
     if (count($Result) >= $Limit) {
         $New[] = valr($Limit - 1 . '.DateInserted', $Result);
     }
     if ($Curr != $New) {
         trace('CommentModel->CachePageWhere()');
         $CacheKey = "Comment.Page.{$Limit}.{$DiscussionID}.{$Page}";
         Gdn::cache()->store($CacheKey, $New, array(Gdn_Cache::FEATURE_EXPIRY => 86400));
         trace($New, $CacheKey);
         //         Gdn::controller()->setData('_PageCacheStore', array($CacheKey, $New));
     }
 }
Example #2
0
 /**
  * Function for quick modify sorting for modules in configuration file.
  * See library/core/class.controller.php ~ L: 118
  * If $PositionItem is False (default) $ModuleName will be added to the edn of the list.
  * If $PositionItem is integer (positive or negative) ...
  * If $PositionItem is string ...
  * 
  * @param string $ModuleSortContainer, container name.
  * @param string $AssetName, asset name.
  * @param string $ModuleName, module name which need to add to config.
  * @param mixed $PositionItem.
  * @return bool. Return FALSE on failure.
  */
 function SetModuleSort($ModuleSortContainer, $AssetName, $ModuleName, $PositionItem = False)
 {
     $ModuleSort = Gdn::Config('Modules');
     $AssetSort = GetValueR("{$ModuleSortContainer}.{$AssetName}", $ModuleSort, array());
     if (!is_array($AssetSort)) {
         $AssetSort = array();
     }
     if ($PositionItem !== False) {
         if (!is_numeric($PositionItem)) {
             $Position = substr($PositionItem, 0, 1);
             if (in_array($Position, array('-', '+'))) {
                 $PositionItem = substr($PositionItem, 1);
             }
             $PositionItem = array_search($PositionItem, $AssetSort);
             if ($Position == '+') {
                 $PositionItem = (int) $PositionItem + 1;
             }
         }
         $PositionItem = (int) $PositionItem;
         array_splice($AssetSort, $PositionItem, 0, array($ModuleName));
     } else {
         array_push($AssetSort, $ModuleName);
     }
     $AssetSort = array_unique($AssetSort);
     // Make sure that we put in config strings only.
     $VarExport = create_function('$Value', 'return var_export(strval($Value), True);');
     $ModuleList = implode(', ', array_map($VarExport, $AssetSort));
     $PhpArrayCode = "\n\$Configuration['Modules']['{$ModuleSortContainer}']['{$AssetName}'] = array({$ModuleList});";
     $ConfigFile = PATH_CONF . '/config.php';
     $Result = file_put_contents($ConfigFile, $PhpArrayCode, FILE_APPEND | LOCK_EX);
     return $Result !== False;
 }
Example #3
0
 function GoogleTranslate($Text, $Options = False)
 {
     static $LanguageCode;
     if (is_null($LanguageCode)) {
         $LanguageCode = LocaleLanguageCode();
     }
     $ResetCache = ArrayValue('ResetCache', $Options, False);
     $From = ArrayValue('From', $Options, $LanguageCode);
     $To = ArrayValue('To', $Options, $LanguageCode);
     $String = rawurlencode($Text);
     if (!LoadExtension('curl')) {
         throw new Exception('You need to load/activate the cURL extension (http://www.php.net/cURL).');
     }
     $Resource = curl_init();
     $HTTPS = GetValue('HTTPS', $_SERVER, '');
     $Protocol = strlen($HTTPS) || GetValue('SERVER_PORT', $_SERVER) == 443 ? 'https://' : 'http://';
     $Host = GetValue('HTTP_HOST', $_SERVER, 'google.com');
     $Referer = $Protocol . $Host;
     curl_setopt($Resource, CURLOPT_URL, "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={$String}&langpair={$From}%7C{$To}");
     curl_setopt($Resource, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($Resource, CURLOPT_REFERER, $Referer);
     $Body = curl_exec($Resource);
     curl_close($Resource);
     $TranslatedText = GetValueR('responseData.translatedText', json_decode($Body));
     $TranslatedText = html_entity_decode($TranslatedText, ENT_QUOTES, 'utf-8');
     return $TranslatedText;
 }
Example #4
0
/**
 * A placeholder for future menu items.
 *
 * @param array The parameters passed into the function. This currently takes no parameters.
 * @param Smarty The smarty object rendering the template.
 * @return
 */
function smarty_function_custom_menu($Params, &$Smarty)
{
    $Controller = $Smarty->Controller;
    if (is_object($Menu = GetValue('Menu', $Controller))) {
        $Format = GetValue('format', $Params, Wrap('<a href="%url" class="%class">%text</a>', GetValue('wrap', $Params, 'li')));
        $Result = '';
        foreach ($Menu->Items as $Group) {
            foreach ($Group as $Item) {
                // Make sure the item is a custom item.
                if (GetValueR('Attributes.Standard', $Item)) {
                    continue;
                }
                // Make sure the user has permission for the item.
                if ($Permission = GetValue('Permission', $Item)) {
                    if (!Gdn::Session()->CheckPermission($Permission)) {
                        continue;
                    }
                }
                if (($Url = GetValue('Url', $Item)) && ($Text = GetValue('Text', $Item))) {
                    $Result .= Gdn_Theme::Link($Url, $Text, $Format);
                }
            }
        }
        return $Result;
    }
    return '';
}
 /**
  *
  *
  * @param null $Name
  * @param string $Default
  * @return array|mixed
  */
 public function data($Name = null, $Default = '')
 {
     if ($Name == null) {
         $Result = $this->Data;
     } else {
         $Result = GetValueR($Name, $this->Data, $Default);
     }
     return $Result;
 }
Example #6
0
 public function AddWarnLevel($Sender, &$Args)
 {
     if (Gdn::Session()->CheckPermission('Garden.Moderation.Manage') || Gdn::Session()->Isvalid() && GetValueR('Author.UserID', $Args) == Gdn::Session()->User->UserID) {
         $WarnLevel = GetValueR('Author.Attributes.WarnLevel', $Args);
         if ($WarnLevel && $WarnLevel != 'None') {
             echo "<span class=\"WarnLevel WarnLevel{$WarnLevel}\">" . T('Warning.Level.' . $WarnLevel, $WarnLevel) . '</span>';
         }
     }
 }
Example #7
0
 protected function _AddCreatePageModule($Sender)
 {
     if (Gdn::Session()->CheckPermission('Candy.Pages.Add')) {
         $Router = Gdn::Router();
         $Default404 = GetValueR('Routes.Default404.Destination', $Router);
         if ($Default404 == $Sender->SelfUrl) {
             $Sender->AddModule(new CreatePageModule($Sender, 'candy'));
         }
     }
 }
Example #8
0
 public function SetAjarData($SectionPath = False)
 {
     $SectionModel = Gdn::Factory('SectionModel');
     if ($SectionPath === False) {
         $SectionPath = GetValueR('SectionID', $this->_Sender);
     } elseif (is_object($SectionPath) && $SectionPath instanceof StdClass) {
         $SectionPath = $SectionPath->SectionID;
     }
     if ($SectionPath) {
         $this->SetData('Items', $SectionModel->Ajar($SectionPath, '', False));
     }
 }
 /**
  * Returns longtintude and latitude of $Address.
  * @param string $Address Adress which need to get coordinates.
  */
 function YmapGeoCoordinates($Address, $Options = FALSE)
 {
     $Raw = $Options === TRUE;
     $Data = array();
     $Data['geocode'] = $Address;
     $Url = 'http://geocode-maps.yandex.ru/1.x/?' . http_build_query($Data);
     $Content = simplexml_load_string(file_get_contents($Url));
     $Result = json_decode(json_encode($Content), TRUE);
     if ($Raw) {
         return $Result;
     }
     $Result = GetValueR('GeoObjectCollection.featureMember', $Result);
     $Result = GetValueR('GeoObject.Point.pos', $Result);
     return $Result;
 }
Example #10
0
 /**
  * Gets GeoCoords by calling the Google Maps geoencoding API. 
  * 
  * @param mixed $Address.
  * @param mixed $Name.
  * @return mixed $Result.
  */
 function GetGeoCoords($Address, $Name = False)
 {
     //$Address = utf8_encode($Address);
     // call geoencoding api with param json for output
     $GeoCodeURL = "http://maps.google.com/maps/api/geocode/json?address=" . urlencode($Address) . "&sensor=false";
     $Result = json_decode(file_get_contents($GeoCodeURL));
     $Status = $Result->status;
     if ($Status == 'OK') {
         $Result = $Result->results[0];
     }
     if ($Name !== False) {
         $Result = GetValueR($Name, $Result);
     }
     return $Result;
 }
 function GoogleTranslate($Text, $Options = False)
 {
     static $LanguageCode;
     if (is_null($LanguageCode)) {
         $LanguageCode = LocaleLanguageCode();
     }
     $ResetCache = ArrayValue('ResetCache', $Options, False);
     $From = ArrayValue('From', $Options, $LanguageCode);
     $To = ArrayValue('To', $Options, $LanguageCode);
     $String = rawurlencode($Text);
     $Result = False;
     if (!LoadExtension('curl')) {
         throw new Exception('You need to load/activate the cURL extension (http://www.php.net/cURL).');
     }
     $Resource = curl_init();
     $HTTPS = GetValue('HTTPS', $_SERVER, '');
     $Protocol = strlen($HTTPS) || GetValue('SERVER_PORT', $_SERVER) == 443 ? 'https://' : 'http://';
     $Host = GetValue('HTTP_HOST', $_SERVER, 'google.com');
     $Referer = $Protocol . $Host;
     curl_setopt($Resource, CURLOPT_URL, "http://translate.google.com/translate_a/t?client=t&text={$String}&sl={$From}&tl={$To}&ie=UTF-8");
     curl_setopt($Resource, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($Resource, CURLOPT_REFERER, $Referer);
     $Body = curl_exec($Resource);
     // Detect response encoding.
     $ContentType = curl_getinfo($Resource, CURLINFO_CONTENT_TYPE);
     if ($ContentType) {
         preg_match('/charset\\=(.+)/', $ContentType, $Match);
         $Charset = $Match[1];
         if ($Charset) {
             $Body = mb_convert_encoding($Body, 'utf-8', $Charset);
         }
     }
     curl_close($Resource);
     $Pos = strpos($Body, ']]');
     if ($Pos !== False) {
         $Body = substr($Body, 1, $Pos + 1);
         $Json = json_decode($Body);
         if ($ErrorMessage = LastJsonErrorMessage()) {
             trigger_error($ErrorMessage);
         }
         $Result = GetValueR('0.0', $Json);
         $Result = html_entity_decode($Result, ENT_QUOTES, 'utf-8');
     }
     return $Result;
 }
 public function Base_BeforeRenderAsset_Handler($Sender)
 {
     $AssetName = GetValueR('EventArguments.AssetName', $Sender);
     if (InSection("DiscussionList")) {
         if (C('Plugin.PrestigeSlider.RenderCondition') == 'all' or C('Plugin.PrestigeSlider.RenderCondition') == 'DiscussionList') {
             if ($AssetName == "Content") {
                 echo $Sender->FetchView($this->GetView('slider.php'));
             }
         }
     }
     if (InSection("CategoryList")) {
         if (C('Plugin.PrestigeSlider.RenderCondition') == 'all' or C('Plugin.PrestigeSlider.RenderCondition') == 'CategoryList') {
             if ($AssetName == "Content") {
                 echo $Sender->FetchView($this->GetView('slider.php'));
             }
         }
     }
 }
Example #13
0
function writeConnection($Row)
{
    $c = Gdn::controller();
    $Connected = val('Connected', $Row);
    ?>
    <li id="<?php 
    echo "Provider_{$Row['ProviderKey']}";
    ?>
" class="Item">
        <div class="Connection-Header">
         <span class="IconWrap">
            <?php 
    echo img(val('Icon', $Row, Asset('/applications/dashboard/design/images/connection-64.png')));
    ?>
         </span>
         <span class="Connection-Name">
            <?php 
    echo val('Name', $Row, t('Unknown'));
    if ($Connected) {
        echo ' <span class="Gloss Connected">';
        if ($Photo = valr('Profile.Photo', $Row)) {
            echo ' ' . Img($Photo, array('class' => 'ProfilePhoto ProfilePhotoSmall'));
        }
        echo ' ' . htmlspecialchars(GetValueR('Profile.Name', $Row)) . '</span>';
    }
    ?>
         </span>
         <span class="Connection-Connect">
            <?php 
    echo ConnectButton($Row);
    ?>
         </span>
        </div>
        <!--      <div class="Connection-Body">
         <?php 
    //         if (Debug()) {
    //            decho(val($Row['ProviderKey'], $c->User->Attributes), 'Attributes');
    //         }
    ?>
      </div>-->
    </li>
<?php 
}
Example #14
0
 public function DiscussionsController_AfterRenderAsset_Handler($Sender)
 {
     $AssetName = GetValueR('EventArguments.AssetName', $Sender);
     if ($AssetName != "Content") {
         return;
     }
     $CurTime = time();
     $LastTime = Gdn::Get('TimeCheck', $LastTime);
     $SFVcount = Gdn::Get('ViewCount', $SFVcount);
     $SFUcount = Gdn::Get('UserCount', $SFUcount);
     $SFDcount = Gdn::Get('DiscussionCount', $SFDcount);
     $SFCcount = Gdn::Get('CommentCount', $SFCcount);
     // refresh counts every 60 seconds unless config is set
     //   e.g. $Configuration['Plugins']['StatisticsFooter']['Refresh'] = '90';
     $IncSec = C('Plugins.StatisticsFooter.Refresh', 60);
     if ($CurTime > $LastTime) {
         $LastTime = time() + $IncSec;
         Gdn::Set('TimeCheck', $LastTime);
         $SFVcount = $this->GetViewCount();
         Gdn::Set('ViewCount', $SFVcount);
         $SFUcount = $this->GetUserCount();
         Gdn::Set('UserCount', $SFUcount);
         $SFDcount = $this->GetDiscussionCount();
         Gdn::Set('DiscussionCount', $SFDcount);
         $SFCcount = $this->GetCommentCount();
         Gdn::Set('CommentCount', $SFCcount);
     }
     $SFPcount = $SFDcount + $SFCcount;
     $ShowMe = C('Plugins.StatisticsFooter.Show');
     if (strpos($ShowMe, "v") !== FALSE) {
         echo Wrap(Wrap(T('View Count')) . Gdn_Format::BigNumber($SFVcount), 'div', array('class' => 'SFBox SFVCBox'));
     }
     if (strpos($ShowMe, "u") !== FALSE) {
         echo Wrap(Wrap(T('User Count')) . Gdn_Format::BigNumber($SFUcount), 'div', array('class' => 'SFBox SFUBox'));
     }
     if (strpos($ShowMe, "t") !== FALSE) {
         echo Wrap(Wrap(T('Topic Count')) . Gdn_Format::BigNumber($SFDcount), 'div', array('class' => 'SFBox SFTBox'));
     }
     if (strpos($ShowMe, "c") !== FALSE) {
         echo Wrap(Wrap(T('Post Count')) . Gdn_Format::BigNumber($SFPcount), 'div', array('class' => 'SFBox SFPBox'));
     }
 }
 protected function GetUserEmails($FormValues)
 {
     $SQL = Gdn::SQL();
     $UserModel = Gdn::UserModel();
     if (ArrayValue('SendMeOnly', $FormValues)) {
         $Session = Gdn::Session();
         $UserID = GetValueR('User.UserID', $Session);
         $User = $UserModel->Get($UserID);
         $Result[$User->Email] = $User->Name;
         return $Result;
     }
     $Roles = ArrayValue('Roles', $FormValues);
     if (is_array($Roles) && count($Roles) > 0) {
         $DataSet = $SQL->Select('u.Name, u.Email')->From('UserRole r')->Join('User u', 'u.UserID = r.UserID')->WhereIn('r.RoleID', $Roles)->Get();
     } else {
         $DataSet = $SQL->Select('u.Name, u.Email')->From('User u')->Get();
     }
     $Result = ConsolidateArrayValuesByKey($DataSet->ResultArray(), 'Email', 'Name');
     return $Result;
 }
Example #16
0
 /**
  * 
  */
 protected static function GetOptions()
 {
     $DS = DIRECTORY_SEPARATOR;
     $Options = array();
     $Defaults = array('read' => True, 'write' => False, 'rm' => False);
     $DefaultOptions = array('root' => Null, 'tmbDir' => '.thumbnails', 'defaults' => $Defaults, 'perms' => array());
     // TODO: $CustomPermissions
     // $All = array('read'  => True, 'write' => True, 'rm' => True);
     /*		$NowYear = date('Y');
     		$CustomPermissions = array(
     			"~$NowYear{$DS}.*~" => $All
     		);*/
     $Session = Gdn::Session();
     if ($Session->CheckPermission('Plugins.ElRte.Wysiwyg.Allow')) {
         $Options['defaults'] = $Defaults;
         $Names = array('Read', 'Write', 'Remove');
         $Names = array_merge(array_combine($Names, $Names), array('Remove' => 'rm'));
         foreach ($Names as $Name => $Perm) {
             $Check = $Session->CheckPermission('Plugins.ElRte.FileManager.Files.' . $Name);
             $Options['defaults'][strtolower($Perm)] = (bool) $Check;
         }
         if ($Session->CheckPermission('Plugins.ElRte.FileManager.Root')) {
             $Options['root'] = 'uploads';
             $Options['URL'] = Url('uploads') . '/';
         } elseif ($Session->CheckPermission('Plugins.ElRte.FileManager.Allow')) {
             $UserID = GetValueR('User.UserID', $Session, 0);
             if (!$UserID || $UserID <= 0) {
                 throw new Exception('UserID is none.');
             }
             $Folder = 'uploads/userfiles/' . $UserID;
             if (!is_dir($Folder)) {
                 mkdir($Folder, 0777, True);
             }
             $Options['root'] = $Folder;
             $Options['URL'] = Url($Folder) . '/';
         }
     }
     $Options = array_merge($DefaultOptions, $Options);
     return $Options;
 }
Example #17
0
 public function CachePageWhere($Result, $PageWhere, $DiscussionID, $Page, $Limit = NULL)
 {
     if (!Gdn::Cache()->ActiveEnabled() || $this->_OrderBy[0][0] != 'c.DateInserted') {
         return;
     }
     if (!$Limit) {
         $Limit = C('Vanilla.Comments.PerPage', 30);
     }
     if (is_array($PageWhere)) {
         $Curr = array_values($PageWhere);
     } else {
         $Curr = FALSE;
     }
     $New = array(GetValueR('0.DateInserted', $Result));
     if (count($Result) >= $Limit) {
         $New[] = GetValueR(count($Result) - 1 . '.DateInserted', $Result);
     }
     if ($Curr != $New) {
         $CacheKey = "Comment.Page.{$DiscussionID}.{$Page}";
         Gdn::Cache()->Store($CacheKey, $New, array(Gdn_Cache::FEATURE_EXPIRY => 86400));
     }
 }
 /**
  * @param PostController $Sender
  * @param array $Args
  * @return mixed
  */
 public function PostController_Comment_Create($Sender, $Args = array())
 {
     if ($Sender->Form->AuthenticatedPostBack()) {
         $Sender->Form->SetModel($Sender->CommentModel);
         // Grab the discussion for use later.
         $DiscussionID = $Sender->Form->GetFormValue('DiscussionID');
         $DiscussionModel = new DiscussionModel();
         $Discussion = $DiscussionModel->GetID($DiscussionID);
         // Check to see if the discussion is supposed to be in private...
         $WhisperConversationID = GetValueR('Attributes.WhisperConversationID', $Discussion);
         if ($WhisperConversationID === TRUE) {
             // There isn't a conversation so we want to create one.
             $Sender->Form->SetFormValue('Whisper', TRUE);
             $WhisperUserIDs = GetValueR('Attributes.WhisperUserIDs', $Discussion);
             $Sender->Form->SetFormValue('RecipientUserID', $WhisperUserIDs);
         } elseif ($WhisperConversationID) {
             // There is already a conversation.
             $Sender->Form->SetFormValue('Whisper', TRUE);
             $Sender->Form->SetFormValue('ConversationID', $WhisperConversationID);
         }
         $Whisper = $Sender->Form->GetFormValue('Whisper') && GetIncomingValue('Type') != 'Draft';
         $WhisperTo = trim($Sender->Form->GetFormValue('To'));
         $ConversationID = $Sender->Form->GetFormValue('ConversationID');
         // If this isn't a whisper then post as normal.
         if (!$Whisper) {
             return call_user_func_array(array($Sender, 'Comment'), $Args);
         }
         $ConversationModel = new ConversationModel();
         $ConversationMessageModel = new ConversationMessageModel();
         if ($ConversationID > 0) {
             $Sender->Form->SetModel($ConversationMessageModel);
         } else {
             // We have to remove the blank conversation ID or else the model won't validate.
             $FormValues = $Sender->Form->FormValues();
             unset($FormValues['ConversationID']);
             $FormValues['Subject'] = GetValue('Name', $Discussion);
             $Sender->Form->FormValues($FormValues);
             $Sender->Form->SetModel($ConversationModel);
             $ConversationModel->Validation->ApplyRule('DiscussionID', 'Required');
         }
         $ID = $Sender->Form->Save($ConversationMessageModel);
         if ($Sender->Form->ErrorCount() > 0) {
             $Sender->ErrorMessage($Sender->Form->Errors());
         } else {
             if ($WhisperConversationID === TRUE) {
                 $Discussion->Attributes['WhisperConversationID'] = $ID;
                 $DiscussionModel->SetProperty($DiscussionID, 'Attributes', serialize($Discussion->Attributes));
             }
             $LastCommentID = GetValue('LastCommentID', $Discussion);
             $MessageID = GetValue('LastMessageID', $ConversationMessageModel, FALSE);
             // Randomize the querystring to force the browser to refresh.
             $Rand = mt_rand(10000, 99999);
             if ($LastCommentID) {
                 // Link to the last comment.
                 $HashID = $MessageID ? 'w' . $MessageID : $LastCommentID;
                 $Sender->RedirectUrl = Url("discussion/comment/{$LastCommentID}?rand={$Rand}#Comment_{$HashID}", TRUE);
             } else {
                 // Link to the discussion.
                 $Hash = $MessageID ? "Comment_w{$MessageID}" : 'Item_1';
                 $Name = rawurlencode(GetValue('Name', $Discussion, 'x'));
                 $Sender->RedirectUrl = Url("discussion/{$DiscussionID}/{$Name}?rand={$Rand}#{$Hash}", TRUE);
             }
         }
         $Sender->Render();
     } else {
         return call_user_func_array(array($Sender, 'Comment'), $Args);
     }
 }
Example #19
0
function _FormatStringCallback($Match, $SetArgs = FALSE)
{
    static $Args = array();
    if ($SetArgs) {
        $Args = $Match;
        return;
    }
    $Match = $Match[1];
    if ($Match == '{') {
        return $Match;
    }
    // Parse out the field and format.
    $Parts = explode(',', $Match);
    $Field = trim($Parts[0]);
    $Format = trim(GetValue(1, $Parts, ''));
    $SubFormat = strtolower(trim(GetValue(2, $Parts, '')));
    $FormatArgs = GetValue(3, $Parts, '');
    if (in_array($Format, array('currency', 'integer', 'percent'))) {
        $FormatArgs = $SubFormat;
        $SubFormat = $Format;
        $Format = 'number';
    } elseif (is_numeric($SubFormat)) {
        $FormatArgs = $SubFormat;
        $SubFormat = '';
    }
    $Value = GetValueR($Field, $Args, '');
    if ($Value == '' && !in_array($Format, array('url', 'exurl'))) {
        $Result = '';
    } else {
        switch (strtolower($Format)) {
            case 'date':
                switch ($SubFormat) {
                    case 'short':
                        $Result = Gdn_Format::Date($Value, '%d/%m/%Y');
                        break;
                    case 'medium':
                        $Result = Gdn_Format::Date($Value, '%e %b %Y');
                        break;
                    case 'long':
                        $Result = Gdn_Format::Date($Value, '%e %B %Y');
                        break;
                    default:
                        $Result = Gdn_Format::Date($Value);
                        break;
                }
                break;
            case 'html':
            case 'htmlspecialchars':
                $Result = htmlspecialchars($Value);
                break;
            case 'number':
                if (!is_numeric($Value)) {
                    $Result = $Value;
                } else {
                    switch ($SubFormat) {
                        case 'currency':
                            $Result = '$' . number_format($Value, is_numeric($FormatArgs) ? $FormatArgs : 2);
                        case 'integer':
                            $Result = (string) round($Value);
                            if (is_numeric($FormatArgs) && strlen($Result) < $FormatArgs) {
                                $Result = str_repeat('0', $FormatArgs - strlen($Result)) . $Result;
                            }
                            break;
                        case 'percent':
                            $Result = round($Value * 100, is_numeric($FormatArgs) ? $FormatArgs : 0);
                            break;
                        default:
                            $Result = number_format($Value, is_numeric($FormatArgs) ? $FormatArgs : 0);
                            break;
                    }
                }
                break;
            case 'plural':
                if (is_array($Value)) {
                    $Value = count($Value);
                } elseif (StringEndsWith($Field, 'UserID', TRUE)) {
                    $Value = 1;
                }
                if (!is_numeric($Value)) {
                    $Result = $Value;
                } else {
                    if (!$SubFormat) {
                        $SubFormat = rtrim("%s {$Field}", 's');
                    }
                    if (!$FormatArgs) {
                        $FormatArgs = $SubFormat . 's';
                    }
                    $Result = Plural($Value, $SubFormat, $FormatArgs);
                }
                break;
            case 'rawurlencode':
                $Result = rawurlencode($Value);
                break;
            case 'text':
                $Result = Gdn_Format::Text($Value, FALSE);
                break;
            case 'time':
                $Result = Gdn_Format::Date($Value, '%l:%M%p');
                break;
            case 'url':
                if (strpos($Field, '/') !== FALSE) {
                    $Value = $Field;
                }
                $Result = Url($Value, $SubFormat == 'domain');
                break;
            case 'exurl':
                if (strpos($Field, '/') !== FALSE) {
                    $Value = $Field;
                }
                $Result = ExternalUrl($Value);
                break;
            case 'urlencode':
                $Result = urlencode($Value);
                break;
            case 'gender':
                // Format in the form of FieldName,gender,male,female,unknown
                if (is_array($Value) && count($Value) == 1) {
                    $Value = array_shift($Value);
                }
                $Gender = 'u';
                if (!is_array($Value)) {
                    $User = Gdn::UserModel()->GetID($Value);
                    if ($User) {
                        $Gender = $User->Gender;
                    }
                }
                switch ($Gender) {
                    case 'm':
                        $Result = $SubFormat;
                        break;
                    case 'f':
                        $Result = $FormatArgs;
                        break;
                    default:
                        $Result = GetValue(4, $Parts);
                }
                break;
            case 'user':
            case 'you':
            case 'his':
            case 'her':
            case 'your':
                $Result = print_r($Value, TRUE);
                $ArgsBak = $Args;
                if (is_array($Value) && count($Value) == 1) {
                    $Value = array_shift($Value);
                }
                if (is_array($Value)) {
                    $Max = C('Garden.FormatUsername.Max', 5);
                    $Count = count($Value);
                    $Result = '';
                    for ($i = 0; $i < $Count; $i++) {
                        if ($i >= $Max && $Count > $Max + 1) {
                            $Others = $Count - $i;
                            $Result .= ' ' . T('sep and', 'and') . ' ' . Plural($Others, '%s other', '%s others');
                            break;
                        }
                        $ID = $Value[$i];
                        if (is_array($ID)) {
                            continue;
                        }
                        if ($i == $Count - 1) {
                            $Result .= ' ' . T('sep and', 'and') . ' ';
                        } elseif ($i > 0) {
                            $Result .= ', ';
                        }
                        $Special = array(-1 => T('everyone'), -2 => T('moderators'), -3 => T('administrators'));
                        if (isset($Special[$ID])) {
                            $Result .= $Special[$ID];
                        } else {
                            $User = Gdn::UserModel()->GetID($ID);
                            $User->Name = FormatUsername($User, $Format, Gdn::Session()->UserID);
                            $Result .= UserAnchor($User);
                        }
                    }
                } else {
                    $User = Gdn::UserModel()->GetID($Value);
                    $User->Name = FormatUsername($User, $Format, Gdn::Session()->UserID);
                    $Result = UserAnchor($User);
                }
                $Args = $ArgsBak;
                break;
            default:
                $Result = $Value;
                break;
        }
    }
    return $Result;
}
 /**
  * Render the poll admin form on the add/edit discussion page in 2.x
  * @param VanillaController $Sender PostController
  */
 public function PostController_DiscussionFormOptions_Handler($Sender)
 {
     $Session = Gdn::Session();
     // Make sure we can add/manage polls
     if (!$Session->CheckPermission(array('Plugins.DiscussionPolls.Add', 'Plugins.DiscussionPolls.Manage'), FALSE)) {
         // don't render poll form at all
         return;
     }
     // render check box
     $Sender->EventArguments['Options'] .= '<li>' . $Sender->Form->CheckBox('DP_Attach', T('Attach Poll'), array('value' => '1', 'checked' => TRUE)) . '</li>';
     // Load up existing poll data
     if (GetValueR('Discussion.DiscussionID', $Sender)) {
         $DID = $Sender->Discussion->DiscussionID;
     } else {
         $DID = NULL;
     }
     $DPModel = new DiscussionPollsModel();
     $DiscussionPoll = $DPModel->GetByDiscussionID($DID);
     // If there is existing poll data, disable editing
     // Editing will be in a future release
     if (!empty($DiscussionPoll->PollID)) {
         $Closed = TRUE;
         $Disabled = array('disabled' => 'true');
         echo Wrap(T('Plugins.DiscussionPolls.PollClosedToEdits', 'You cannot edit a poll. You <em>may</em> delete this poll by unchecking the Attach Poll checkbox.'), 'div', array('class' => 'Messages Warning'));
     } else {
         $Disabled = array();
         $Closed = FALSE;
     }
     $Sender->AddDefinition('DP_Closed', $Closed);
     // The opening of the form
     $Sender->Form->SetValue('DP_Title', $DiscussionPoll->Title);
     //render form
     DPRenderQuestionForm($Sender->Form, $DiscussionPoll, $Disabled, $Closed);
 }
Example #21
0
 /**
  * Generates a multi-field form from a schema.
  * @param array $Schema An array where each item of the array is a row that identifies a form field with the following information:
  *  - Name: The name of the form field.
  *  - Control: The type of control used for the field. This is one of the control methods on the Gdn_Form object.
  *  - LabelCode: The translation code for the label. Optional.
  *  - Description: An optional description for the field.
  *  - Items: If the control is a list control then its items are specified here.
  *  - Options: Additional options to be passed into the control.
  * @param type $Options Additional options to pass into the form.
  *  - Wrap: A two item array specifying the text to wrap the form in.
  *  - ItemWrap: A two item array specifying the text to wrap each form item in.
  */
 public function Simple($Schema, $Options = array())
 {
     $Result = GetValueR('Wrap.0', $Options, '<ul>');
     $ItemWrap = GetValue('ItemWrap', $Options, array("<li>\n  ", "\n</li>\n"));
     foreach ($Schema as $Index => $Row) {
         if (is_string($Row)) {
             $Row = array('Name' => $Index, 'Control' => $Row);
         }
         if (!isset($Row['Name'])) {
             $Row['Name'] = $Index;
         }
         if (!isset($Row['Options'])) {
             $Row['Options'] = array();
         }
         $Result .= $ItemWrap[0];
         $LabelCode = self::LabelCode($Row);
         $Description = GetValue('Description', $Row, '');
         if ($Description) {
             $Description = '<div class="Info">' . $Description . '</div>';
         }
         TouchValue('Control', $Row, 'TextBox');
         switch (strtolower($Row['Control'])) {
             case 'categorydropdown':
                 $Result .= $this->Label($LabelCode, $Row['Name']) . $Description . $this->CategoryDropDown($Row['Name'], $Row['Options']);
                 break;
             case 'checkbox':
                 $Result .= $Description . $this->CheckBox($Row['Name'], T($LabelCode));
                 break;
             case 'dropdown':
                 $Result .= $this->Label($LabelCode, $Row['Name']) . $Description . $this->DropDown($Row['Name'], $Row['Items'], $Row['Options']);
                 break;
             case 'radiolist':
                 $Result .= $Description . $this->RadioList($Row['Name'], $Row['Items'], $Row['Options']);
                 break;
             case 'checkboxlist':
                 $Result .= $this->Label($LabelCode, $Row['Name']) . $Description . $this->CheckBoxList($Row['Name'], $Row['Items'], NULL, $Row['Options']);
                 break;
             case 'textbox':
                 $Result .= $this->Label($LabelCode, $Row['Name']) . $Description . $this->TextBox($Row['Name'], $Row['Options']);
                 break;
             case 'callback':
                 $Row['DescriptionHtml'] = $Description;
                 $Row['LabelCode'] = $LabelCode;
                 $Result .= call_user_func($Row['Callback'], $this, $Row);
                 break;
             default:
                 $Result .= "Error a control type of {$Row['Control']} is not supported.";
                 break;
         }
         $Result .= $ItemWrap[1];
     }
     $Result .= GetValueR('Wrap.1', $Options, '</ul>');
     return $Result;
 }
Example #22
0
 public function History($UpdateFields = TRUE, $InsertFields = FALSE)
 {
     $UserID = GetValueR('User.UserID', Gdn::Session(), Gdn::Session()->UserID);
     if ($InsertFields) {
         $this->Set('DateInserted', Gdn_Format::ToDateTime())->Set('InsertUserID', $UserID);
     }
     if ($UpdateFields) {
         $this->Set('DateUpdated', Gdn_Format::ToDateTime())->Set('UpdateUserID', $UserID);
     }
     return $this;
 }
Example #23
0
function _FormatStringCallback($Match, $SetArgs = FALSE)
{
    static $Args = array();
    if ($SetArgs) {
        $Args = $Match;
        return;
    }
    $Match = $Match[1];
    if ($Match == '{') {
        return $Match;
    }
    // Parse out the field and format.
    $Parts = explode(',', $Match);
    $Field = trim($Parts[0]);
    $Format = strtolower(trim(GetValue(1, $Parts, '')));
    $SubFormat = strtolower(trim(GetValue(2, $Parts, '')));
    $FomatArgs = GetValue(3, $Parts, '');
    if (in_array($Format, array('currency', 'integer', 'percent'))) {
        $FormatArgs = $SubFormat;
        $SubFormat = $Format;
        $Format = 'number';
    } elseif (is_numeric($SubFormat)) {
        $FormatArgs = $SubFormat;
        $SubFormat = '';
    }
    $Value = GetValueR($Field, $Args, '');
    if ($Value == '' && !in_array($Format, array('url', 'exurl'))) {
        $Result = '';
    } else {
        switch (strtolower($Format)) {
            case 'date':
                switch ($SubFormat) {
                    case 'short':
                        $Result = Gdn_Format::Date($Value, '%d/%m/%Y');
                        break;
                    case 'medium':
                        $Result = Gdn_Format::Date($Value, '%e %b %Y');
                        break;
                    case 'long':
                        $Result = Gdn_Format::Date($Value, '%e %B %Y');
                        break;
                    default:
                        $Result = Gdn_Format::Date($Value);
                        break;
                }
                break;
            case 'html':
            case 'htmlspecialchars':
                $Result = htmlspecialchars($Value);
                break;
            case 'number':
                if (!is_numeric($Value)) {
                    $Result = $Value;
                } else {
                    switch ($SubFormat) {
                        case 'currency':
                            $Result = '$' . number_format($Value, is_numeric($FormatArgs) ? $FormatArgs : 2);
                        case 'integer':
                            $Result = (string) round($Value);
                            if (is_numeric($FormatArgs) && strlen($Result) < $FormatArgs) {
                                $Result = str_repeat('0', $FormatArgs - strlen($Result)) . $Result;
                            }
                            break;
                        case 'percent':
                            $Result = round($Value * 100, is_numeric($FormatArgs) ? $FormatArgs : 0);
                            break;
                        default:
                            $Result = number_format($Value, is_numeric($FormatArgs) ? $FormatArgs : 0);
                            break;
                    }
                }
                break;
            case 'rawurlencode':
                $Result = rawurlencode($Value);
                break;
            case 'time':
                $Result = Gdn_Format::Date($Value, '%l:%M%p');
                break;
            case 'url':
                if (strpos($Field, '/') !== FALSE) {
                    $Value = $Field;
                }
                $Result = Url($Value, $SubFormat == 'domain');
                break;
            case 'exurl':
                if (strpos($Field, '/') !== FALSE) {
                    $Value = $Field;
                }
                $Result = ExternalUrl($Value);
                break;
            case 'urlencode':
                $Result = urlencode($Value);
                break;
            default:
                $Result = $Value;
                break;
        }
    }
    return $Result;
}
Example #24
0
 /**
  * Adds 'Discussions' tab to profiles and adds CSS & JS files to their head.
  * 
  * @since 2.0.0
  * @package Vanilla
  * 
  * @param object $Sender ProfileController.
  */
 public function ProfileController_AddProfileTabs_Handler($Sender)
 {
     if (is_object($Sender->User) && $Sender->User->UserID > 0) {
         $UserID = $Sender->User->UserID;
         // Add the discussion tab
         $DiscussionsLabel = Sprite('SpDiscussions') . ' ' . T('Discussions');
         $CommentsLabel = Sprite('SpComments') . ' ' . T('Comments');
         if (C('Vanilla.Profile.ShowCounts', TRUE)) {
             $DiscussionsLabel .= '<span class="Aside">' . CountString(GetValueR('User.CountDiscussions', $Sender, NULL), "/profile/count/discussions?userid={$UserID}") . '</span>';
             $CommentsLabel .= '<span class="Aside">' . CountString(GetValueR('User.CountComments', $Sender, NULL), "/profile/count/comments?userid={$UserID}") . '</span>';
         }
         $Sender->AddProfileTab(T('Discussions'), 'profile/discussions/' . $Sender->User->UserID . '/' . rawurlencode($Sender->User->Name), 'Discussions', $DiscussionsLabel);
         $Sender->AddProfileTab(T('Comments'), 'profile/comments/' . $Sender->User->UserID . '/' . rawurlencode($Sender->User->Name), 'Comments', $CommentsLabel);
         // Add the discussion tab's CSS and Javascript.
         $Sender->AddJsFile('jquery.gardenmorepager.js');
         $Sender->AddJsFile('discussions.js');
     }
 }
Example #25
0
 /**
  * Saves the category tree based on a provided tree array. We are using the
  * Nested Set tree model.
  * 
  * @ref http://articles.sitepoint.com/article/hierarchical-data-database/2
  * @ref http://en.wikipedia.org/wiki/Nested_set_model
  *
  * @since 2.0.16
  * @access public
  *
  * @param array $TreeArray A fully defined nested set model of the category tree. 
  */
 public function SaveTree($TreeArray)
 {
     /*
       TreeArray comes in the format:
     '0' ...
       'item_id' => "root"
       'parent_id' => "none"
       'depth' => "0"
       'left' => "1"
       'right' => "34"
     '1' ...
       'item_id' => "1"
       'parent_id' => "root"
       'depth' => "1"
       'left' => "2"
       'right' => "3"
     etc...
     */
     // Grab all of the categories so that permissions can be properly saved.
     $PermTree = $this->SQL->Select('CategoryID, PermissionCategoryID, TreeLeft, TreeRight, Depth, Sort, ParentCategoryID')->From('Category')->Get();
     $PermTree = $PermTree->Index($PermTree->ResultArray(), 'CategoryID');
     // The tree must be walked in order for the permissions to save properly.
     usort($TreeArray, array('CategoryModel', '_TreeSort'));
     $Saves = array();
     foreach ($TreeArray as $I => $Node) {
         $CategoryID = GetValue('item_id', $Node);
         if ($CategoryID == 'root') {
             $CategoryID = -1;
         }
         $ParentCategoryID = GetValue('parent_id', $Node);
         if (in_array($ParentCategoryID, array('root', 'none'))) {
             $ParentCategoryID = -1;
         }
         $PermissionCategoryID = GetValueR("{$CategoryID}.PermissionCategoryID", $PermTree, 0);
         $PermCatChanged = FALSE;
         if ($PermissionCategoryID != $CategoryID) {
             // This category does not have custom permissions so must inherit its parent's permissions.
             $PermissionCategoryID = GetValueR("{$ParentCategoryID}.PermissionCategoryID", $PermTree, 0);
             if ($CategoryID != -1 && !GetValueR("{$ParentCategoryID}.Touched", $PermTree)) {
                 throw new Exception("Category {$ParentCategoryID} not touched before touching {$CategoryID}.");
             }
             if ($PermTree[$CategoryID]['PermissionCategoryID'] != $PermissionCategoryID) {
                 $PermCatChanged = TRUE;
             }
             $PermTree[$CategoryID]['PermissionCategoryID'] = $PermissionCategoryID;
         }
         $PermTree[$CategoryID]['Touched'] = TRUE;
         // Only update if the tree doesn't match the database.
         $Row = $PermTree[$CategoryID];
         if ($Node['left'] != $Row['TreeLeft'] || $Node['right'] != $Row['TreeRight'] || $Node['depth'] != $Row['Depth'] || $ParentCategoryID != $Row['ParentCategoryID'] || $Node['left'] != $Row['Sort'] || $PermCatChanged) {
             $Set = array('TreeLeft' => $Node['left'], 'TreeRight' => $Node['right'], 'Depth' => $Node['depth'], 'Sort' => $Node['left'], 'ParentCategoryID' => $ParentCategoryID, 'PermissionCategoryID' => $PermissionCategoryID);
             $this->SQL->Update('Category', $Set, array('CategoryID' => $CategoryID))->Put();
             $Saves[] = array_merge(array('CategoryID' => $CategoryID), $Set);
         }
     }
     self::ClearCache();
     return $Saves;
 }
 public function Base_CommentInfo_Handler($Sender, $Args)
 {
     $Type = GetValue('Type', $Args);
     if ($Type != 'Comment') {
         return;
     }
     $QnA = GetValueR('Comment.QnA', $Args);
     if ($QnA && ($QnA == 'Accepted' || Gdn::Session()->CheckPermission('Garden.Moderation.Manage'))) {
         $Title = T("QnA {$QnA} Answer", "{$QnA} Answer");
         echo ' <span class="Tag QnA-Box QnA-' . $QnA . '" title="' . htmlspecialchars($Title) . '"><span>' . $Title . '</span></span> ';
     }
 }
/**
 * A custom error handler that displays much more, very useful information when
 * errors are encountered in Garden.
 *	@param Exception $Exception The exception that was thrown.
 */
function Gdn_ExceptionHandler($Exception)
{
    try {
        $ErrorNumber = $Exception->getCode();
        $Message = $Exception->getMessage();
        $File = $Exception->getFile();
        $Line = $Exception->getLine();
        if (method_exists($Exception, 'getContext')) {
            $Arguments = $Exception->getContext();
        } else {
            $Arguments = '';
        }
        $Backtrace = $Exception->getTrace();
        // Clean the output buffer in case an error was encountered in-page.
        @ob_end_clean();
        // prevent headers already sent error
        if (!headers_sent()) {
            header('Content-Type: text/html; charset=utf-8');
        }
        $SenderMessage = $Message;
        $SenderObject = 'PHP';
        $SenderMethod = 'Gdn_ErrorHandler';
        $SenderCode = FALSE;
        $SenderTrace = $Backtrace;
        $MessageInfo = explode('|', $Message);
        $MessageCount = count($MessageInfo);
        if ($MessageCount == 4) {
            list($SenderMessage, $SenderObject, $SenderMethod, $SenderCode) = $MessageInfo;
        } else {
            if ($MessageCount == 3) {
                list($SenderMessage, $SenderObject, $SenderMethod) = $MessageInfo;
            } elseif (function_exists('GetValueR')) {
                $IsError = GetValueR('0.function', $SenderTrace) == 'Gdn_ErrorHandler';
                // not exception
                $N = $IsError ? '1' : '0';
                $SenderMethod = GetValueR($N . '.function', $SenderTrace, $SenderMethod);
                $SenderObject = GetValueR($N . '.class', $SenderTrace, $SenderObject);
            }
        }
        $SenderMessage = strip_tags($SenderMessage);
        $Master = FALSE;
        // The parsed master view
        $CssPath = FALSE;
        // The web-path to the css file
        $ErrorLines = FALSE;
        // The lines near the error's line #
        $DeliveryType = defined('DELIVERY_TYPE_ALL') ? DELIVERY_TYPE_ALL : 'ALL';
        if (array_key_exists('DeliveryType', $_POST)) {
            $DeliveryType = $_POST['DeliveryType'];
        } else {
            if (array_key_exists('DeliveryType', $_GET)) {
                $DeliveryType = $_GET['DeliveryType'];
            }
        }
        // Make sure all of the required custom functions and variables are defined.
        $PanicError = FALSE;
        // Should we just dump a message and forget about the master view?
        if (!defined('DS')) {
            $PanicError = TRUE;
        }
        if (!defined('PATH_ROOT')) {
            $PanicError = TRUE;
        }
        if (!defined('APPLICATION')) {
            define('APPLICATION', 'Garden');
        }
        if (!defined('APPLICATION_VERSION')) {
            define('APPLICATION_VERSION', 'Unknown');
        }
        $WebRoot = '';
        // Try and rollback a database transaction.
        if (class_exists('Gdn', FALSE)) {
            $Database = Gdn::Database();
            if (is_object($Database)) {
                $Database->RollbackTransaction();
            }
        }
        if ($PanicError === FALSE) {
            // See if we can get the file that caused the error
            if (is_string($File) && is_numeric($ErrorNumber)) {
                $ErrorLines = @file($File);
            }
            // If this error was encountered during an ajax request, don't bother gettting the css or theme files
            if ($DeliveryType == DELIVERY_TYPE_ALL) {
                $CssPaths = array();
                // Potential places where the css can be found in the filesystem.
                $MasterViewPaths = array();
                $MasterViewName = 'error.master.php';
                $MasterViewCss = 'error.css';
                if (class_exists('Gdn', FALSE)) {
                    $CurrentTheme = '';
                    // The currently selected theme
                    $CurrentTheme = Gdn::Config('Garden.Theme', '');
                    $MasterViewName = Gdn::Config('Garden.Errors.MasterView', $MasterViewName);
                    $MasterViewCss = substr($MasterViewName, 0, strpos($MasterViewName, '.'));
                    if ($MasterViewCss == '') {
                        $MasterViewCss = 'error';
                    }
                    $MasterViewCss .= '.css';
                    if ($CurrentTheme != '') {
                        // Look for CSS in the theme folder:
                        $CssPaths[] = PATH_THEMES . DS . $CurrentTheme . DS . 'design' . DS . $MasterViewCss;
                        // Look for Master View in the theme folder:
                        $MasterViewPaths[] = PATH_THEMES . DS . $CurrentTheme . DS . 'views' . DS . $MasterViewName;
                    }
                }
                // Look for CSS in the dashboard design folder.
                $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $MasterViewCss;
                // Look for Master View in the dashboard view folder.
                $MasterViewPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'views' . DS . $MasterViewName;
                $CssPath = FALSE;
                $Count = count($CssPaths);
                for ($i = 0; $i < $Count; ++$i) {
                    if (file_exists($CssPaths[$i])) {
                        $CssPath = $CssPaths[$i];
                        break;
                    }
                }
                if ($CssPath !== FALSE) {
                    $CssPath = str_replace(array(PATH_ROOT, DS), array('', '/'), $CssPath);
                    $CssPath = ($WebRoot == '' ? '' : '/' . $WebRoot) . $CssPath;
                }
                $MasterViewPath = FALSE;
                $Count = count($MasterViewPaths);
                for ($i = 0; $i < $Count; ++$i) {
                    if (file_exists($MasterViewPaths[$i])) {
                        $MasterViewPath = $MasterViewPaths[$i];
                        break;
                    }
                }
                if ($MasterViewPath !== FALSE) {
                    include $MasterViewPath;
                    $Master = TRUE;
                }
            }
        }
        if ($DeliveryType != DELIVERY_TYPE_ALL) {
            // This is an ajax request, so dump an error that is more eye-friendly in the debugger
            echo '<h1>FATAL ERROR IN: ', $SenderObject, '.', $SenderMethod, "();</h1>\n<div class=\"AjaxError\">\"" . $SenderMessage . "\"\n";
            if ($SenderCode != '') {
                echo htmlentities($SenderCode, ENT_COMPAT, 'UTF-8') . "\n";
            }
            if (is_array($ErrorLines) && $Line > -1) {
                echo "LOCATION: ", $File, "\n";
            }
            $LineCount = count($ErrorLines);
            $Padding = strlen($Line + 5);
            for ($i = 0; $i < $LineCount; ++$i) {
                if ($i > $Line - 6 && $i < $Line + 4) {
                    if ($i == $Line - 1) {
                        echo '>>';
                    }
                    echo '> ' . str_pad($i + 1, $Padding, " ", STR_PAD_LEFT), ': ', str_replace(array("\n", "\r"), array('', ''), $ErrorLines[$i]), "\n";
                }
            }
            if (is_array($Backtrace)) {
                echo "BACKTRACE:\n";
                $BacktraceCount = count($Backtrace);
                for ($i = 0; $i < $BacktraceCount; ++$i) {
                    if (array_key_exists('file', $Backtrace[$i])) {
                        $File = $Backtrace[$i]['file'] . ' ' . $Backtrace[$i]['line'];
                    }
                    echo '[' . $File . ']', ' ', array_key_exists('class', $Backtrace[$i]) ? $Backtrace[$i]['class'] : 'PHP', array_key_exists('type', $Backtrace[$i]) ? $Backtrace[$i]['type'] : '::', $Backtrace[$i]['function'], '();', "\n";
                }
            }
            echo '</div>';
        } else {
            // If the master view wasn't found, assume a panic state and dump the error.
            if ($Master === FALSE) {
                echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-ca">
   <head>
      <title>Fatal Error</title>
   </head>
   <body>
      <h1>Fatal Error in ', $SenderObject, '.', $SenderMethod, '();</h1>
      <h2>', $SenderMessage, "</h2>\n";
                if ($SenderCode != '') {
                    echo '<code>', htmlentities($SenderCode, ENT_COMPAT, 'UTF-8'), "</code>\n";
                }
                if (is_array($ErrorLines) && $Line > -1) {
                    echo '<h3><strong>The error occurred on or near:</strong> ', $File, '</h3>
         <pre>';
                    $LineCount = count($ErrorLines);
                    $Padding = strlen($Line + 4);
                    for ($i = 0; $i < $LineCount; ++$i) {
                        if ($i > $Line - 6 && $i < $Line + 4) {
                            echo str_pad($i, $Padding, " ", STR_PAD_LEFT), ': ', htmlentities($ErrorLines[$i], ENT_COMPAT, 'UTF-8');
                        }
                    }
                    echo "</pre>\n";
                }
                echo '<h2>Need Help?</h2>
      <p>If you are a user of this website, you can report this message to a website administrator.</p>
      <p>If you are an administrator of this website, you can get help at the <a href="http://vanillaforums.org/discussions/" target="_blank">Vanilla Community Forums</a>.</p>
      <h2>Additional information for support personnel:</h2>
      <ul>
         <li><strong>Application:</strong> ', APPLICATION, '</li>
         <li><strong>Application Version:</strong> ', APPLICATION_VERSION, '</li>
         <li><strong>PHP Version:</strong> ', PHP_VERSION, '</li>
         <li><strong>Operating System:</strong> ', PHP_OS, "</li>\n";
                if (array_key_exists('SERVER_SOFTWARE', $_SERVER)) {
                    echo '<li><strong>Server Software:</strong> ', $_SERVER['SERVER_SOFTWARE'], "</li>\n";
                }
                if (array_key_exists('HTTP_REFERER', $_SERVER)) {
                    echo '<li><strong>Referer:</strong> ', $_SERVER['HTTP_REFERER'], "</li>\n";
                }
                if (array_key_exists('HTTP_USER_AGENT', $_SERVER)) {
                    echo '<li><strong>User Agent:</strong> ', $_SERVER['HTTP_USER_AGENT'], "</li>\n";
                }
                if (array_key_exists('REQUEST_URI', $_SERVER)) {
                    echo '<li><strong>Request Uri:</strong> ', $_SERVER['REQUEST_URI'], "</li>\n";
                }
                echo '</ul>
   </body>
   </html>';
            }
        }
        // Attempt to log an error message no matter what.
        LogMessage($File, $Line, $SenderObject, $SenderMethod, $SenderMessage, $SenderCode);
    } catch (Exception $e) {
        print get_class($e) . " thrown within the exception handler.<br/>Message: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine();
        exit;
    }
}
Example #28
0
 /**
  * Undocumented method.
  *
  * @todo Method RenderMaster() needs a description.
  */
 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)) {
             if (ArrayHasValue($this->_CssFiles, 'style.css')) {
                 $this->AddCssFile('custom.css');
             }
             if (ArrayHasValue($this->_CssFiles, 'admin.css')) {
                 $this->AddCssFile('customadmin.css');
             }
             $this->EventArguments['CssFiles'] =& $this->_CssFiles;
             $this->FireEvent('BeforeAddCss');
             // And now search for/add all css files
             foreach ($this->_CssFiles as $CssInfo) {
                 $CssFile = $CssInfo['FileName'];
                 if (strpos($CssFile, '/') !== FALSE) {
                     // A direct path to the file was given.
                     $CssPaths = array(CombinePaths(array(PATH_ROOT, str_replace('/', DS, $CssFile))));
                 } else {
                     $CssGlob = preg_replace('/(.*)(\\.css)/', '\\1*\\2', $CssFile);
                     $AppFolder = $CssInfo['AppFolder'];
                     if ($AppFolder == '') {
                         $AppFolder = $this->ApplicationFolder;
                     }
                     // CSS comes from one of four places:
                     $CssPaths = array();
                     if ($this->Theme) {
                         // 1. Application-specific css. eg. root/themes/theme_name/app_name/design/
                         // $CssPaths[] = PATH_THEMES . DS . $this->Theme . DS . $AppFolder . DS . 'design' . DS . $CssGlob;
                         // 2. Theme-wide theme view. eg. root/themes/theme_name/design/
                         // a) Check to see if a customized version of the css is there.
                         if ($this->ThemeOptions) {
                             $Filenames = GetValueR('Styles.Value', $this->ThemeOptions);
                             if (is_string($Filenames) && $Filenames != '%s') {
                                 $CssPaths[] = PATH_THEMES . DS . $this->Theme . DS . 'design' . DS . ChangeBasename($CssFile, $Filenames);
                             }
                         }
                         // b) Use the default filename.
                         $CssPaths[] = PATH_THEMES . DS . $this->Theme . DS . 'design' . DS . $CssFile;
                     }
                     // 3. Application or plugin.
                     if (StringBeginsWith($AppFolder, 'plugins/')) {
                         // The css is coming from a plugin.
                         $AppFolder = substr($AppFolder, strlen('plugins/'));
                         $CssPaths[] = PATH_PLUGINS . "/{$AppFolder}/design/{$CssFile}";
                         $CssPaths[] = PATH_PLUGINS . "/{$AppFolder}/{$CssFile}";
                     } else {
                         // Application default. eg. root/applications/app_name/design/
                         $CssPaths[] = PATH_APPLICATIONS . DS . $AppFolder . DS . 'design' . DS . $CssFile;
                     }
                     // 4. Garden default. eg. root/applications/dashboard/design/
                     $CssPaths[] = PATH_APPLICATIONS . DS . 'dashboard' . DS . 'design' . DS . $CssFile;
                 }
                 // Find the first file that matches the path.
                 $CssPath = FALSE;
                 foreach ($CssPaths as $Glob) {
                     $Paths = SafeGlob($Glob);
                     if (is_array($Paths) && count($Paths) > 0) {
                         $CssPath = $Paths[0];
                         break;
                     }
                 }
                 // Check to see if there is a CSS cacher.
                 $CssCacher = Gdn::Factory('CssCacher');
                 if (!is_null($CssCacher)) {
                     $CssPath = $CssCacher->Get($CssPath, $AppFolder);
                 }
                 if ($CssPath !== FALSE) {
                     $CssPath = substr($CssPath, strlen(PATH_ROOT));
                     $CssPath = str_replace(DS, '/', $CssPath);
                     $this->Head->AddCss($CssPath, 'all', TRUE, $CssInfo['Options']);
                 }
             }
             // Add a custom js file.
             if (ArrayHasValue($this->_CssFiles, 'style.css')) {
                 $this->AddJsFile('custom.js');
             }
             // only to non-admin pages.
             // And now search for/add all JS files
             foreach ($this->_JsFiles as $Index => $JsInfo) {
                 $JsFile = $JsInfo['FileName'];
                 if (strpos($JsFile, '//') !== FALSE) {
                     // This is a link to an external file.
                     $this->Head->AddScript($JsFile);
                     continue;
                 }
                 if (strpos($JsFile, '/') !== FALSE) {
                     // A direct path to the file was given.
                     $JsPaths = array(CombinePaths(array(PATH_ROOT, str_replace('/', DS, $JsFile)), DS));
                 } else {
                     $AppFolder = $JsInfo['AppFolder'];
                     if ($AppFolder == '') {
                         $AppFolder = $this->ApplicationFolder;
                     }
                     // JS can come from a theme, an any of the application folder, or it can come from the global js folder:
                     $JsPaths = array();
                     if ($this->Theme) {
                         // 1. Application-specific js. eg. root/themes/theme_name/app_name/design/
                         $JsPaths[] = PATH_THEMES . DS . $this->Theme . DS . $AppFolder . DS . 'js' . DS . $JsFile;
                         // 2. Garden-wide theme view. eg. root/themes/theme_name/design/
                         $JsPaths[] = PATH_THEMES . DS . $this->Theme . DS . 'js' . DS . $JsFile;
                     }
                     // 3. The application or plugin folder.
                     if (StringBeginsWith(trim($AppFolder, '/'), 'plugins/')) {
                         $JsPaths[] = PATH_PLUGINS . strstr($AppFolder, '/') . "/js/{$JsFile}";
                         $JsPaths[] = PATH_PLUGINS . strstr($AppFolder, '/') . "/{$JsFile}";
                     } else {
                         $JsPaths[] = PATH_APPLICATIONS . "/{$AppFolder}/js/{$JsFile}";
                     }
                     // 4. Global JS folder. eg. root/js/
                     $JsPaths[] = PATH_ROOT . DS . 'js' . DS . $JsFile;
                     // 5. Global JS library folder. eg. root/js/library/
                     $JsPaths[] = PATH_ROOT . DS . 'js' . DS . 'library' . DS . $JsFile;
                 }
                 // Find the first file that matches the path.
                 $JsPath = FALSE;
                 foreach ($JsPaths as $Glob) {
                     $Paths = SafeGlob($Glob);
                     if (is_array($Paths) && count($Paths) > 0) {
                         $JsPath = $Paths[0];
                         break;
                     }
                 }
                 if ($JsPath !== FALSE) {
                     $JsSrc = str_replace(array(PATH_ROOT, DS), array('', '/'), $JsPath);
                     $Options = (array) $JsInfo['Options'];
                     $Options['path'] = $JsPath;
                     $Version = GetValue('Version', $JsInfo);
                     if ($Version) {
                         TouchValue('version', $Options, $Version);
                     }
                     $this->Head->AddScript($JsSrc, 'text/javascript', $Options);
                 }
             }
         }
         // Add the favicon
         $this->Head->SetFavIcon(C('Garden.FavIcon', Asset('themes/' . $this->Theme . '/design/favicon.png')));
         // 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. Application default. eg. root/app_name/views/
         $MasterViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, $this->ApplicationFolder, 'views', $this->MasterView . '.master*'));
         // 4. 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);
     }
 }
 public function LocalInfileSupported()
 {
     $Sql = "show variables like 'local_infile'";
     $Data = $this->Query($Sql)->ResultArray();
     if (strcasecmp(GetValueR('0.Value', $Data), 'ON') == 0) {
         return TRUE;
     } else {
         return FALSE;
     }
 }
Example #30
0
 function GetDiscussionOptions($Discussion = NULL)
 {
     $Options = array();
     $Sender = Gdn::Controller();
     $Session = Gdn::Session();
     if ($Discussion == NULL) {
         $Discussion = $Sender->Data('Discussion');
     }
     $CategoryID = GetValue('CategoryID', $Discussion);
     if (!$CategoryID && property_exists($Sender, 'Discussion')) {
         $CategoryID = GetValue('CategoryID', $Sender->Discussion);
     }
     $PermissionCategoryID = GetValue('PermissionCategoryID', $Discussion, GetValue('PermissionCategoryID', $Sender->Discussion));
     // Determine if we still have time to edit
     $EditContentTimeout = C('Garden.EditContentTimeout', -1);
     $CanEdit = $EditContentTimeout == -1 || strtotime($Discussion->DateInserted) + $EditContentTimeout > time();
     $CanEdit = $CanEdit && $Session->UserID == $Discussion->InsertUserID || $Session->CheckPermission('Vanilla.Discussions.Edit', TRUE, 'Category', $PermissionCategoryID);
     $TimeLeft = '';
     if ($CanEdit && $EditContentTimeout > 0 && !$Session->CheckPermission('Vanilla.Discussions.Edit', TRUE, 'Category', $PermissionCategoryID)) {
         $TimeLeft = strtotime($Discussion->DateInserted) + $EditContentTimeout - time();
         $TimeLeft = $TimeLeft > 0 ? ' (' . Gdn_Format::Seconds($TimeLeft) . ')' : '';
     }
     // Build the $Options array based on current user's permission.
     // Can the user edit the discussion?
     if ($CanEdit) {
         $Options['EditDiscussion'] = array('Label' => T('Edit') . ' ' . $TimeLeft, 'Url' => '/vanilla/post/editdiscussion/' . $Discussion->DiscussionID);
     }
     // Can the user announce?
     if ($Session->CheckPermission('Vanilla.Discussions.Announce', TRUE, 'Category', $PermissionCategoryID)) {
         $Options['AnnounceDiscussion'] = array('Label' => T('Announce...'), 'Url' => 'vanilla/discussion/announce?discussionid=' . $Discussion->DiscussionID . '&Target=' . urlencode($Sender->SelfUrl . '#Head'), 'Class' => 'Popup');
     }
     // Can the user sink?
     if ($Session->CheckPermission('Vanilla.Discussions.Sink', TRUE, 'Category', $PermissionCategoryID)) {
         $Options['SinkDiscussion'] = array('Label' => T($Discussion->Sink ? 'Unsink' : 'Sink'), 'Url' => 'vanilla/discussion/sink/' . $Discussion->DiscussionID . '/' . $Session->TransientKey() . '?Target=' . urlencode($Sender->SelfUrl . '#Head'), 'Class' => 'Hijack');
     }
     // Can the user close?
     if ($Session->CheckPermission('Vanilla.Discussions.Close', TRUE, 'Category', $PermissionCategoryID)) {
         $Options['CloseDiscussion'] = array('Label' => T($Discussion->Closed ? 'Reopen' : 'Close'), 'Url' => 'vanilla/discussion/close/' . $Discussion->DiscussionID . '/' . $Session->TransientKey() . '?Target=' . urlencode($Sender->SelfUrl . '#Head'), 'Class' => 'Hijack');
     }
     if ($CanEdit && GetValueR('Attributes.ForeignUrl', $Discussion)) {
         $Options['RefetchPage'] = array('Label' => T('Refetch Page'), 'Url' => '/discussion/refetchpageinfo.json?discussionid=' . $Discussion->DiscussionID, 'Class' => 'Hijack');
     }
     // Can the user delete?
     if ($Session->CheckPermission('Vanilla.Discussions.Delete', TRUE, 'Category', $PermissionCategoryID)) {
         $Options['DeleteDiscussion'] = array('Label' => T('Delete Discussion'), 'Url' => 'vanilla/discussion/delete/' . $Discussion->DiscussionID . '/' . $Session->TransientKey());
     }
     // DEPRECATED (as of 2.1)
     $Sender->EventArguments['Type'] = 'Discussion';
     // Allow plugins to add options.
     $Sender->EventArguments['DiscussionOptions'] =& $Options;
     $Sender->EventArguments['Discussion'] = $Discussion;
     $Sender->FireEvent('DiscussionOptions');
     return $Options;
 }