to() public static method

Takes a mixed variable, formats it in the specified format type, and returns it.
public static to ( mixed $Mixed, string $FormatMethod ) : mixed
$Mixed mixed An object, array, or string to be formatted.
$FormatMethod string The method with which the variable should be formatted.
return mixed
Ejemplo n.º 1
0
 function formatBody($Object)
 {
     Gdn::controller()->fireEvent('BeforeCommentBody');
     $Object->FormatBody = Gdn_Format::to($Object->Body, $Object->Format);
     Gdn::controller()->fireEvent('AfterCommentFormat');
     return $Object->FormatBody;
 }
Ejemplo n.º 2
0
 /**
  * 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'));
         }
     }
 }
Ejemplo n.º 3
0
    /**
     *
     *
     * @param $Type
     * @param $ID
     * @param $QuoteData
     * @param bool $Format
     */
    protected function formatQuote($Type, $ID, &$QuoteData, $Format = false)
    {
        // Temporarily disable Emoji parsing (prevent double-parsing to HTML)
        $emojiEnabled = Emoji::instance()->enabled;
        Emoji::instance()->enabled = false;
        if (!$Format) {
            $Format = c('Garden.InputFormatter');
        }
        $Type = strtolower($Type);
        $Model = false;
        switch ($Type) {
            case 'comment':
                $Model = new CommentModel();
                break;
            case 'discussion':
                $Model = new DiscussionModel();
                break;
            default:
                break;
        }
        //$QuoteData = array();
        if ($Model) {
            $Data = $Model->getID($ID);
            $NewFormat = $Format;
            if ($NewFormat == 'Wysiwyg') {
                $NewFormat = 'Html';
            }
            $QuoteFormat = $Data->Format;
            if ($QuoteFormat == 'Wysiwyg') {
                $QuoteFormat = 'Html';
            }
            // Perform transcoding if possible
            $NewBody = $Data->Body;
            if ($QuoteFormat != $NewFormat) {
                if (in_array($NewFormat, array('Html', 'Wysiwyg'))) {
                    $NewBody = Gdn_Format::to($NewBody, $QuoteFormat);
                } elseif ($QuoteFormat == 'Html' && $NewFormat == 'BBCode') {
                    $NewBody = Gdn_Format::text($NewBody, false);
                } elseif ($QuoteFormat == 'Text' && $NewFormat == 'BBCode') {
                    $NewBody = Gdn_Format::text($NewBody, false);
                } else {
                    $NewBody = Gdn_Format::plainText($NewBody, $QuoteFormat);
                }
                if (!in_array($NewFormat, array('Html', 'Wysiwyg'))) {
                    Gdn::controller()->informMessage(sprintf(t('The quote had to be converted from %s to %s.', 'The quote had to be converted from %s to %s. Some formatting may have been lost.'), htmlspecialchars($QuoteFormat), htmlspecialchars($NewFormat)));
                }
            }
            $Data->Body = $NewBody;
            // Format the quote according to the format.
            switch ($Format) {
                case 'Html':
                    // HTML
                    $Quote = '<blockquote class="Quote" rel="' . htmlspecialchars($Data->InsertName) . '">' . $Data->Body . '</blockquote>' . "\n";
                    break;
                case 'BBCode':
                    $Author = htmlspecialchars($Data->InsertName);
                    if ($ID) {
                        $IDString = ';' . htmlspecialchars($ID);
                    }
                    $QuoteBody = $Data->Body;
                    // TODO: Strip inner quotes...
                    //                  $QuoteBody = trim(preg_replace('`(\[quote.*/quote\])`si', '', $QuoteBody));
                    $Quote = <<<BQ
[quote="{$Author}{$IDString}"]{$QuoteBody}[/quote]

BQ;
                    break;
                case 'Markdown':
                case 'Display':
                case 'Text':
                    $QuoteBody = $Data->Body;
                    // Strip inner quotes and mentions...
                    $QuoteBody = self::_stripMarkdownQuotes($QuoteBody);
                    $QuoteBody = self::_stripMentions($QuoteBody);
                    $Quote = '> ' . sprintf(t('%s said:'), '@' . $Data->InsertName) . "\n" . '> ' . str_replace("\n", "\n> ", $QuoteBody) . "\n";
                    break;
                case 'Wysiwyg':
                    $Attribution = sprintf(t('%s said:'), userAnchor($Data, null, array('Px' => 'Insert')));
                    $QuoteBody = $Data->Body;
                    // TODO: Strip inner quotes...
                    //                  $QuoteBody = trim(preg_replace('`(<blockquote.*/blockquote>)`si', '', $QuoteBody));
                    $Quote = <<<BLOCKQUOTE
<blockquote class="Quote">
  <div class="QuoteAuthor">{$Attribution}</div>
  <div class="QuoteText">{$QuoteBody}</div>
</blockquote>

BLOCKQUOTE;
                    break;
            }
            $QuoteData = array_merge($QuoteData, array('status' => 'success', 'body' => $Quote, 'format' => $Format, 'authorid' => $Data->InsertUserID, 'authorname' => $Data->InsertName, 'type' => $Type, 'typeid' => $ID));
        }
        // Undo Emoji disable.
        Emoji::instance()->enabled = $emojiEnabled;
    }
Ejemplo n.º 4
0
 /**
  * Format the resultset with the given method.
  *
  * @param string $FormatMethod The method to use with Gdn_Format::To().
  * @return Gdn_Dataset $this pointer for chaining.
  */
 public function format($FormatMethod)
 {
     $Result =& $this->result();
     foreach ($Result as $Index => $Value) {
         $Result[$Index] = Gdn_Format::to($Value, $FormatMethod);
     }
     return $this;
 }
 /**
  * Re-fetch a discussion's content based on its foreign url.
  * @param type $DiscussionID
  */
 public function refetchPageInfo($DiscussionID)
 {
     // Make sure we are posting back.
     if (!$this->Request->isAuthenticatedPostBack(true)) {
         throw permissionException('Javascript');
     }
     // Grab the discussion.
     $Discussion = $this->DiscussionModel->getID($DiscussionID);
     if (!$Discussion) {
         throw notFoundException('Discussion');
     }
     // Make sure the user has permission to edit this discussion.
     $this->permission('Vanilla.Discussions.Edit', true, 'Category', $Discussion->PermissionCategoryID);
     $ForeignUrl = valr('Attributes.ForeignUrl', $Discussion);
     if (!$ForeignUrl) {
         throw new Gdn_UserException(t("This discussion isn't associated with a url."));
     }
     $Stub = $this->DiscussionModel->fetchPageInfo($ForeignUrl, true);
     // Save the stub.
     $this->DiscussionModel->setField($DiscussionID, (array) $Stub);
     // Send some of the stuff back.
     if (isset($Stub['Name'])) {
         $this->jsonTarget('.PageTitle h1', Gdn_Format::text($Stub['Name']));
     }
     if (isset($Stub['Body'])) {
         $this->jsonTarget("#Discussion_{$DiscussionID} .Message", Gdn_Format::to($Stub['Body'], $Stub['Format']));
     }
     $this->informMessage('The page was successfully fetched.');
     $this->render('Blank', 'Utility', 'Dashboard');
 }
Ejemplo n.º 6
0
 /**
  * Format some text in a way suitable for passing into an rss/atom feed.
  * @since 2.1
  * @param string $Text The text to format.
  * @param string $Format The current format of the text.
  * @return string
  */
 public static function rssHtml($Text, $Format = 'Html')
 {
     if (!in_array($Text, array('Html', 'Raw'))) {
         $Text = Gdn_Format::to($Text, $Format);
     }
     if (function_exists('FormatRssHtmlCustom')) {
         return FormatRssHtmlCustom($Text);
     } else {
         return Gdn_Format::html($Text);
     }
 }
Ejemplo n.º 7
0
<?php 
foreach ($this->DiscussionData->Result() as $Discussion) {
    ?>
    <item>
        <title><?php 
    echo Gdn_Format::text($Discussion->Name);
    ?>
</title>
        <link><?php 
    echo htmlspecialchars(url('/discussion/' . $Discussion->DiscussionID . '/' . Gdn_Format::url($Discussion->Name), true));
    ?>
</link>
        <pubDate><?php 
    echo date(DATE_RSS, Gdn_Format::ToTimeStamp($Discussion->DateInserted));
    ?>
</pubDate>
        <dc:creator><?php 
    echo Gdn_Format::text($Discussion->FirstName);
    ?>
</dc:creator>
        <guid isPermaLink="false"><?php 
    echo $Discussion->DiscussionID . '@' . Url('/discussions');
    ?>
</guid>
        <description><![CDATA[<?php 
    echo Gdn_Format::to($Discussion->Body, $Discussion->Format);
    ?>
]]></description>
    </item>
<?php 
}
 /**
  *
  *
  * @param $Search
  * @param int $Offset
  * @param int $Limit
  * @return array|null
  * @throws Exception
  */
 public function search($Search, $Offset = 0, $Limit = 20)
 {
     // If there are no searches then return an empty array.
     if (trim($Search) == '') {
         return array();
     }
     // Figure out the exact search mode.
     if ($this->ForceSearchMode) {
         $SearchMode = $this->ForceSearchMode;
     } else {
         $SearchMode = strtolower(c('Garden.Search.Mode', 'matchboolean'));
     }
     if ($SearchMode == 'matchboolean') {
         if (strpos($Search, '+') !== false || strpos($Search, '-') !== false) {
             $SearchMode = 'boolean';
         } else {
             $SearchMode = 'match';
         }
     } else {
         $this->_SearchMode = $SearchMode;
     }
     if ($ForceDatabaseEngine = c('Database.ForceStorageEngine')) {
         if (strcasecmp($ForceDatabaseEngine, 'myisam') != 0) {
             $SearchMode = 'like';
         }
     }
     if (strlen($Search) <= 4) {
         $SearchMode = 'like';
     }
     $this->_SearchMode = $SearchMode;
     $this->EventArguments['Search'] = $Search;
     $this->fireEvent('Search');
     if (count($this->_SearchSql) == 0) {
         return array();
     }
     // Perform the search by unioning all of the sql together.
     $Sql = $this->SQL->select()->from('_TBL_ s')->orderBy('s.DateInserted', 'desc')->limit($Limit, $Offset)->GetSelect();
     $Sql = str_replace($this->Database->DatabasePrefix . '_TBL_', "(\n" . implode("\nunion all\n", $this->_SearchSql) . "\n)", $Sql);
     $this->fireEvent('AfterBuildSearchQuery');
     if ($this->_SearchMode == 'like') {
         $Search = '%' . $Search . '%';
     }
     foreach ($this->_Parameters as $Key => $Value) {
         $this->_Parameters[$Key] = $Search;
     }
     $Parameters = $this->_Parameters;
     $this->reset();
     $this->SQL->reset();
     $Result = $this->Database->query($Sql, $Parameters)->resultArray();
     foreach ($Result as $Key => $Value) {
         if (isset($Value['Summary'])) {
             $Value['Summary'] = Condense(Gdn_Format::to($Value['Summary'], $Value['Format']));
             $Result[$Key] = $Value;
         }
         switch ($Value['RecordType']) {
             case 'Discussion':
                 $Discussion = arrayTranslate($Value, array('PrimaryID' => 'DiscussionID', 'Title' => 'Name', 'CategoryID'));
                 $Result[$Key]['Url'] = DiscussionUrl($Discussion, 1);
                 break;
         }
     }
     return $Result;
 }
Ejemplo n.º 9
0
<?php

if (!defined('APPLICATION')) {
    exit;
}
$this->fireEvent('BeforeCommentPreviewFormat');
$this->Comment->Body = Gdn_Format::to($this->Comment->Body, val('Format', $this->Comment, c('Garden.InputFormatter')));
$this->fireEvent('AfterCommentPreviewFormat');
?>
<div class="Preview">
    <div class="Message"><?php 
echo $this->Comment->Body;
?>
</div>
</div>
Ejemplo n.º 10
0
        <div id="Item_<?php 
    echo $CurrentOffset;
    ?>
" class="ConversationMessage">
            <div class="Meta">
         <span class="Author">
            <?php 
    echo userPhoto($Author, 'Photo');
    echo userAnchor($Author, 'Name');
    ?>
         </span>
                <span class="MItem DateCreated"><?php 
    echo Gdn_Format::date($Message->DateInserted, 'html');
    ?>
</span>
                <?php 
    $this->fireEvent('AfterConversationMessageDate');
    ?>
            </div>
            <div class="Message">
                <?php 
    $this->fireEvent('BeforeConversationMessageBody');
    echo Gdn_Format::to($Message->Body, $Format);
    $this->EventArguments['Message'] =& $Message;
    $this->fireEvent('AfterConversationMessageBody');
    ?>
            </div>
        </div>
    </li>
<?php 
}
Ejemplo n.º 11
0
}
foreach ($this->data('Comments') as $Comment) {
    $Permalink = '/discussion/comment/' . $Comment->CommentID . '/#Comment_' . $Comment->CommentID;
    $User = UserBuilder($Comment, 'Insert');
    $this->EventArguments['User'] = $User;
    ?>
    <li id="<?php 
    echo 'Comment_' . $Comment->CommentID;
    ?>
" class="Item">
        <?php 
    $this->fireEvent('BeforeItemContent');
    ?>
        <div class="ItemContent">
            <div class="Message"><?php 
    echo SliceString(Gdn_Format::text(Gdn_Format::to($Comment->Body, $Comment->Format), false), 250);
    ?>
</div>
            <div class="Meta">
                <span class="MItem"><?php 
    echo t('Comment in', 'in') . ' ';
    ?>
                    <b><?php 
    echo anchor(Gdn_Format::text($Comment->DiscussionName), $Permalink);
    ?>
</b></span>
                <span class="MItem"><?php 
    printf(t('Comment by %s'), userAnchor($User));
    ?>
</span>
                <span class="MItem"><?php 
Ejemplo n.º 12
0
 /**
  * Check requirements and publish new discussion to Twitter.
  *
  * @param object $sender DiscussionModel.
  * @param array $args EventArguments.
  * @return void.
  * @package TwitterBot
  * @since 0.1
  */
 public function discussionModel_afterSaveDiscussion_handler($sender, $args)
 {
     $discussion = $args['Discussion'];
     // Exit if this discussion has already been twittered.
     if ($discussion->Attributes['TwitterBot'] == true) {
         return;
     }
     // Exit if discussions from this category shouldn't be twittered
     if (!in_array($discussion->CategoryID, Gdn::config('TwitterBot.CategoryIDs'))) {
         return;
     }
     // Exit if the current user hasn't the permission to twitter
     $roleIds = array_keys(Gdn::userModel()->getRoles($discussion->InsertUserID));
     if (array_intersect($roles, Gdn::config('TwitterBot.RoleIDs'))) {
         return;
     }
     // Exit if only announcements shall be twittered and this is no announcements
     if (Gdn::config('TwitterBot.AnnouncementsOnly') && !$discussion->Announce) {
         return;
     }
     // Exit if checkbox is shown and not ticked
     if (Gdn::config('TwitterBot.ShowCheckbox') && !$args['FormPostValues']['TwitterBot']) {
         return;
     }
     // Exit if plugin is not configured
     $consumerKey = Gdn::config('TwitterBot.ConsumerKey');
     $consumerSecret = Gdn::config('TwitterBot.ConsumerSecret');
     $oAuthAccessToken = Gdn::config('TwitterBot.OAuthAccessToken');
     $oAuthAccessTokenSecret = Gdn::config('TwitterBot.OAuthAccessTokenSecret');
     if (!$consumerKey || !$consumerSecret || !$oAuthAccessToken || !$oAuthAccessTokenSecret) {
         return;
     }
     $title = $discussion->Name;
     $body = Gdn_Format::to($discussion->Body, $discussion->Format);
     $author = $discussion->InsertName;
     $date = $discussion->DateInserted;
     $category = $discussion->Category;
     $url = $discussion->Url;
     $tweet = '"' . $title . '" by ' . $author;
     require_once __DIR__ . '/library/vendors/twitter-api-php/TwitterAPIExchange.php';
     $settings = array('oauth_access_token' => $oAuthAccessToken, 'oauth_access_token_secret' => $oAuthAccessTokenSecret, 'consumer_key' => $consumerKey, 'consumer_secret' => $consumerSecret);
     $twitter = new TwitterAPIExchange($settings);
     $response = $twitter->buildOauth('https://api.twitter.com/1.1/statuses/update.json', 'POST')->setPostfields(array('status' => $tweet))->performRequest();
     $response = json_decode($response, true);
     if (isset($response['created_at'])) {
         // Gdn::controller()->informMessage('This discussion has been published on Twitter', 'Dismissable');
         Gdn::discussionModel()->saveToSerializedColumn('Attributes', $discussion->DiscussionID, 'TwitterBot', true);
     }
 }
Ejemplo n.º 13
0
    function writeActivityComment($Comment, $Activity)
    {
        $Session = Gdn::session();
        $Author = UserBuilder($Comment, 'Insert');
        $PhotoAnchor = userPhoto($Author, 'Photo');
        $CssClass = 'Item ActivityComment ActivityComment';
        if ($PhotoAnchor != '') {
            $CssClass .= ' HasPhoto';
        }
        ?>
        <li id="ActivityComment_<?php 
        echo $Comment['ActivityCommentID'];
        ?>
" class="<?php 
        echo $CssClass;
        ?>
">
            <?php 
        if ($PhotoAnchor != '') {
            ?>
                <div class="Author Photo"><?php 
            echo $PhotoAnchor;
            ?>
</div>
            <?php 
        }
        ?>
            <div class="ItemContent ActivityComment">
                <?php 
        echo userAnchor($Author, 'Title Name');
        ?>
                <div class="Excerpt"><?php 
        echo Gdn_Format::to($Comment['Body'], $Comment['Format']);
        ?>
</div>
                <div class="Meta">
                    <span class="DateCreated"><?php 
        echo Gdn_Format::date($Comment['DateInserted'], 'html');
        ?>
</span>
                    <?php 
        if (ActivityModel::canDelete($Activity)) {
            echo anchor(t('Delete'), "dashboard/activity/deletecomment?id={$Comment['ActivityCommentID']}&tk=" . $Session->TransientKey() . '&target=' . urlencode(Gdn_Url::Request()), 'DeleteComment');
        }
        ?>
                </div>
            </div>
        </li>
    <?php 
    }
Ejemplo n.º 14
0
 /**
  *
  *
  * @param null $Data
  * @return mixed|string
  * @throws Exception
  */
 public function toString($Data = NULL)
 {
     static $Plugin;
     if (!isset($Plugin)) {
         $Plugin = Gdn::pluginManager()->getPluginInstance('PocketsPlugin', Gdn_PluginManager::ACCESS_CLASSNAME);
     }
     $Plugin->EventArguments['Pocket'] = $this;
     $Plugin->fireEvent('ToString');
     if (strcasecmp($this->Format, 'raw') == 0) {
         return $this->Body;
     } else {
         return Gdn_Format::to($this->Body, $this->Format);
     }
 }
Ejemplo n.º 15
0
            <?php 
    foreach ($this->data('Conversations') as $Row) {
        ?>
                <li id="Conversation_<?php 
        echo $Row['ConversationID'];
        ?>
" class="Item">
                    <?php 
        $JumpToItem = $Row['CountMessages'] - $Row['CountNewMessages'];
        $Url = "/messages/{$Row['ConversationID']}/#Item_{$JumpToItem}";
        if ($SubjectsVisible && $Row['Subject']) {
            $Message = htmlspecialchars($Row['Title']);
        } elseif ($Row['Format'] == 'Text') {
            $Message = sliceString(Gdn_Format::to($Row['LastMessage'], $Conversation['Format']), 100);
        } else {
            $Message = sliceString(Gdn_Format::text(Gdn_Format::to($Row['LastMessage'], $Row['Format']), false), 100);
        }
        if (stringIsNullOrEmpty(trim($Message))) {
            $Message = t('Blank Message');
        }
        echo anchor($Message, $Url, 'ConversationLink');
        ?>
                    <div class="Meta">
            <span class="MItem Participants">
               <?php 
        $First = TRUE;
        foreach ($Row['Participants'] as $User) {
            if ($First) {
                $First = FALSE;
            } else {
                echo ', ';
Ejemplo n.º 16
0
    /**
     * Generates html output of $Content array
     *
     * @param array|object $Content
     * @param PromotedContentModule $Sender
     */
    function writePromotedContent($Content, $Sender)
    {
        static $UserPhotoFirst = NULL;
        if ($UserPhotoFirst === null) {
            $UserPhotoFirst = c('Vanilla.Comment.UserPhotoFirst', true);
        }
        $ContentType = val('RecordType', $Content);
        $ContentID = val("{$ContentType}ID", $Content);
        $Author = val('Author', $Content);
        $ContentURL = val('Url', $Content);
        $Sender->EventArguments['Content'] =& $Content;
        $Sender->EventArguments['ContentUrl'] =& $ContentURL;
        ?>
        <div id="<?php 
        echo "Promoted_{$ContentType}_{$ContentID}";
        ?>
" class="<?php 
        echo CssClass($Content);
        ?>
">
            <div class="AuthorWrap">
         <span class="Author">
            <?php 
        if ($UserPhotoFirst) {
            echo userPhoto($Author);
            echo userAnchor($Author, 'Username');
        } else {
            echo userAnchor($Author, 'Username');
            echo userPhoto($Author);
        }
        $Sender->fireEvent('AuthorPhoto');
        ?>
         </span>
         <span class="AuthorInfo">
            <?php 
        echo ' ' . WrapIf(htmlspecialchars(val('Title', $Author)), 'span', array('class' => 'MItem AuthorTitle'));
        echo ' ' . WrapIf(htmlspecialchars(val('Location', $Author)), 'span', array('class' => 'MItem AuthorLocation'));
        $Sender->fireEvent('AuthorInfo');
        ?>
         </span>
            </div>
            <div class="Meta CommentMeta CommentInfo">
         <span class="MItem DateCreated">
            <?php 
        echo anchor(Gdn_Format::date($Content['DateInserted'], 'html'), $ContentURL, 'Permalink', array('rel' => 'nofollow'));
        ?>
         </span>
                <?php 
        // Include source if one was set
        if ($Source = val('Source', $Content)) {
            echo wrap(sprintf(t('via %s'), t($Source . ' Source', $Source)), 'span', array('class' => 'MItem Source'));
        }
        $Sender->fireEvent('ContentInfo');
        ?>
            </div>
            <div
                class="Title"><?php 
        echo anchor(Gdn_Format::text(sliceString($Content['Name'], $Sender->TitleLimit), false), $ContentURL, 'DiscussionLink');
        ?>
</div>
            <div class="Body">
                <?php 
        echo anchor(strip_tags(Gdn_Format::to(sliceString($Content['Body'], $Sender->BodyLimit), $Content['Format'])), $ContentURL, 'BodyLink');
        $Sender->fireEvent('AfterPromotedBody');
        // separate event to account for less space.
        ?>
            </div>
        </div>
    <?php 
    }