text() public static method

Takes a mixed variable, formats it for display on the screen as plain text.
public static text ( mixed $mixed, $addBreaks = true ) : string
$mixed mixed An object, array, or string to be formatted.
return string
Ejemplo n.º 1
0
 /**
  * Output markup for extended profile fields.
  *
  * @param array $profileFields Formatted profile fields.
  * @param array $allFields Extended profile field data.
  * @param array $magicLabels "Magic" labels configured on the Profile Extender plug-in class.
  */
 function extendedProfileFields($profileFields, $allFields, $magicLabels = [])
 {
     foreach ($profileFields as $name => $value) {
         // Skip empty and hidden fields.
         if (!$value || !val('OnProfile', $allFields[$name])) {
             continue;
         }
         // Non-magic fields must be plain text, but we'll auto-link
         if (!in_array($name, $magicLabels)) {
             $value = Gdn_Format::links(Gdn_Format::text($value));
         }
         $class = 'Profile' . Gdn_Format::alphaNumeric($name);
         $label = Gdn_Format::text($allFields[$name]['Label']);
         $filteredVal = Gdn_Format::htmlFilter($value);
         echo " <dt class=\"ProfileExtend {$class}\">{$label}</dt> ";
         echo " <dd class=\"ProfileExtend {$class}\">{$filteredVal}</dd> ";
     }
 }
Ejemplo n.º 2
0
 /**
  * Renders a plaintext email.
  *
  * @return string A plaintext email.
  */
 protected function plainTextEmail()
 {
     return Gdn_Format::plainText(Gdn_Format::text($this->getMessage()));
 }
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
 /**
  * Autocomplete a username.
  *
  * @since 2.0.0
  * @access public
  */
 public function autoComplete()
 {
     $this->deliveryType(DELIVERY_TYPE_NONE);
     $Q = getIncomingValue('q');
     $UserModel = new UserModel();
     $Data = $UserModel->getLike(array('u.Name' => $Q), 'u.Name', 'asc', 10, 0);
     foreach ($Data->result() as $User) {
         echo htmlspecialchars($User->Name) . '|' . Gdn_Format::text($User->UserID) . "\n";
     }
     $this->render();
 }
Ejemplo n.º 5
0
 /**
  * The callback helper for {@link formatString()}.
  *
  * @param array $Match Either the array of arguments or the regular expression match.
  * @param bool $SetArgs Whether this is a call to initialize the arguments or a matching callback.
  * @return mixed Returns the matching string or nothing when setting the arguments.
  * @access private
  */
 function _formatStringCallback($Match, $SetArgs = false)
 {
     static $Args = array(), $ContextUserID = null;
     if ($SetArgs) {
         $Args = $Match;
         if (isset($Args['_ContextUserID'])) {
             $ContextUserID = $Args['_ContextUserID'];
         } else {
             $ContextUserID = Gdn::session() && Gdn::session()->isValid() ? Gdn::session()->UserID : null;
         }
         return '';
     }
     $Match = $Match[1];
     if ($Match == '{') {
         return $Match;
     }
     // Parse out the field and format.
     $Parts = explode(',', $Match);
     $Field = trim($Parts[0]);
     $Format = trim(val(1, $Parts, ''));
     $SubFormat = strtolower(trim(val(2, $Parts, '')));
     $FormatArgs = val(3, $Parts, '');
     if (in_array($Format, array('currency', 'integer', 'percent'))) {
         $FormatArgs = $SubFormat;
         $SubFormat = $Format;
         $Format = 'number';
     } elseif (is_numeric($SubFormat)) {
         $FormatArgs = $SubFormat;
         $SubFormat = '';
     }
     $Value = valr($Field, $Args, null);
     if ($Value === null && !in_array($Format, array('url', 'exurl', 'number', 'plural'))) {
         $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);
                             break;
                         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[,plural]
                 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;
                     }
                 } else {
                     $Gender = 'p';
                 }
                 switch ($Gender) {
                     case 'm':
                         $Result = $SubFormat;
                         break;
                     case 'f':
                         $Result = $FormatArgs;
                         break;
                     case 'p':
                         $Result = val(5, $Parts, val(4, $Parts));
                         break;
                     case 'u':
                     default:
                         $Result = val(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)) {
                     if (isset($Value['UserID'])) {
                         $User = $Value;
                         $User['Name'] = formatUsername($User, $Format, $ContextUserID);
                         $Result = userAnchor($User);
                     } else {
                         $Max = c('Garden.FormatUsername.Max', 5);
                         // See if there is another count.
                         $ExtraCount = valr($Field . '_Count', $Args, 0);
                         $Count = count($Value);
                         $Result = '';
                         for ($i = 0; $i < $Count; $i++) {
                             if ($i >= $Max && $Count > $Max + 1) {
                                 $Others = $Count - $i + $ExtraCount;
                                 $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);
                                 if ($User) {
                                     $User->Name = formatUsername($User, $Format, $ContextUserID);
                                     $Result .= userAnchor($User);
                                 }
                             }
                         }
                     }
                 } else {
                     $User = Gdn::userModel()->getID($Value);
                     if ($User) {
                         // Store this name separately because of special 'You' case.
                         $Name = formatUsername($User, $Format, $ContextUserID);
                         // Manually build instead of using userAnchor() because of special 'You' case.
                         $Result = anchor(htmlspecialchars($Name), userUrl($User));
                     } else {
                         $Result = '';
                     }
                 }
                 $Args = $ArgsBak;
                 break;
             default:
                 $Result = $Value;
                 break;
         }
     }
     return $Result;
 }
Ejemplo n.º 6
0
    exit;
}
?>
<div class="Box BoxDrafts">
    <?php 
echo panelHeading(t('My Drafts'));
?>
    <ul class="PanelInfo PanelDiscussions">
        <?php 
foreach ($this->Data->result() as $Draft) {
    $EditUrl = !is_numeric($Draft->DiscussionID) || $Draft->DiscussionID <= 0 ? '/post/editdiscussion/0/' . $Draft->DraftID : '/post/editcomment/0/' . $Draft->DraftID;
    ?>
            <li>
                <strong><?php 
    echo anchor($Draft->Name, $EditUrl);
    ?>
</strong>
                <?php 
    echo anchor(sliceString(Gdn_Format::text($Draft->Body), 200), $EditUrl, 'DraftCommentLink');
    ?>
            </li>
        <?php 
}
?>
        <li class="ShowAll"><?php 
echo anchor(t('↳ Show All'), 'drafts');
?>
</li>
    </ul>
</div>
 /**
  * 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.º 8
0
 /**
  *
  *
  * @param $Data
  * @param null $CategoryID
  * @return bool
  */
 public static function joinRecentPosts(&$Data, $CategoryID = null)
 {
     $DiscussionIDs = array();
     $CommentIDs = array();
     $Joined = false;
     foreach ($Data as &$Row) {
         if (!is_null($CategoryID) && $Row['CategoryID'] != $CategoryID) {
             continue;
         }
         if (isset($Row['LastTitle']) && $Row['LastTitle']) {
             continue;
         }
         if ($Row['LastDiscussionID']) {
             $DiscussionIDs[] = $Row['LastDiscussionID'];
         }
         if ($Row['LastCommentID']) {
             $CommentIDs[] = $Row['LastCommentID'];
         }
         $Joined = true;
     }
     // Create a fresh copy of the Sql object so as not to pollute.
     $Sql = clone Gdn::sql();
     $Sql->reset();
     $Discussions = null;
     // Grab the discussions.
     if (count($DiscussionIDs) > 0) {
         $Discussions = $Sql->whereIn('DiscussionID', $DiscussionIDs)->get('Discussion')->resultArray();
         $Discussions = Gdn_DataSet::Index($Discussions, array('DiscussionID'));
     }
     if (count($CommentIDs) > 0) {
         $Comments = $Sql->whereIn('CommentID', $CommentIDs)->get('Comment')->resultArray();
         $Comments = Gdn_DataSet::Index($Comments, array('CommentID'));
     }
     foreach ($Data as &$Row) {
         if (!is_null($CategoryID) && $Row['CategoryID'] != $CategoryID) {
             continue;
         }
         $Discussion = val($Row['LastDiscussionID'], $Discussions);
         $NameUrl = 'x';
         if ($Discussion) {
             $Row['LastTitle'] = Gdn_Format::text($Discussion['Name']);
             $Row['LastUserID'] = $Discussion['InsertUserID'];
             $Row['LastDiscussionUserID'] = $Discussion['InsertUserID'];
             $Row['LastDateInserted'] = $Discussion['DateInserted'];
             $NameUrl = Gdn_Format::text($Discussion['Name'], true);
             $Row['LastUrl'] = DiscussionUrl($Discussion, false, '/') . '#latest';
         }
         if (!empty($Comments) && ($Comment = val($Row['LastCommentID'], $Comments))) {
             $Row['LastUserID'] = $Comment['InsertUserID'];
             $Row['LastDateInserted'] = $Comment['DateInserted'];
             $Row['DateLastComment'] = $Comment['DateInserted'];
         } else {
             $Row['NoComment'] = true;
         }
         touchValue('LastTitle', $Row, '');
         touchValue('LastUserID', $Row, null);
         touchValue('LastDiscussionUserID', $Row, null);
         touchValue('LastDateInserted', $Row, null);
         touchValue('LastUrl', $Row, null);
     }
     return $Joined;
 }
Ejemplo n.º 9
0
        }
        ?>
                    <div>
                        <strong><?php 
        echo $Message->Enabled == '1' ? t('Enabled') : t('Disabled');
        ?>
</strong>
                        <?php 
        echo anchor(t('Edit'), '/dashboard/message/edit/' . $Message->MessageID, 'EditMessage SmallButton');
        echo anchor(t('Delete'), '/dashboard/message/delete/' . $Message->MessageID . '/' . $Session->TransientKey(), 'DeleteMessage SmallButton');
        ?>
                    </div>
                </td>
                <td class="Alt">
                    <div
                        class="Message <?php 
        echo $Message->CssClass;
        ?>
"><?php 
        echo Gdn_Format::text($Message->Content);
        ?>
</div>
                </td>
            </tr>
        <?php 
    }
    ?>
        </tbody>
    </table>
<?php 
}
Ejemplo n.º 10
0
 /**
  * Add a method to the ModerationController to handle splitting comments out to a new discussion.
  */
 public function moderationController_splitComments_create($Sender)
 {
     $Session = Gdn::session();
     $Sender->Form = new Gdn_Form();
     $Sender->title(t('Split Comments'));
     $Sender->Category = false;
     $DiscussionID = val('0', $Sender->RequestArgs, '');
     if (!is_numeric($DiscussionID)) {
         return;
     }
     $DiscussionModel = new DiscussionModel();
     $Discussion = $DiscussionModel->getID($DiscussionID);
     if (!$Discussion) {
         return;
     }
     // Verify that the user has permission to perform the split
     $Sender->permission('Vanilla.Discussions.Edit', true, 'Category', $Discussion->PermissionCategoryID);
     $CheckedComments = Gdn::userModel()->getAttribute($Session->User->UserID, 'CheckedComments', array());
     if (!is_array($CheckedComments)) {
         $CheckedComments = array();
     }
     $CommentIDs = array();
     foreach ($CheckedComments as $DiscID => $Comments) {
         foreach ($Comments as $Comment) {
             if ($DiscID == $DiscussionID) {
                 $CommentIDs[] = str_replace('Comment_', '', $Comment);
             }
         }
     }
     // Load category data.
     $Sender->ShowCategorySelector = (bool) c('Vanilla.Categories.Use');
     $CountCheckedComments = count($CommentIDs);
     $Sender->setData('CountCheckedComments', $CountCheckedComments);
     // Perform the split
     if ($Sender->Form->authenticatedPostBack()) {
         // Create a new discussion record
         $Data = $Sender->Form->formValues();
         $Data['Body'] = sprintf(t('This discussion was created from comments split from: %s.'), anchor(Gdn_Format::text($Discussion->Name), 'discussion/' . $Discussion->DiscussionID . '/' . Gdn_Format::url($Discussion->Name) . '/'));
         $Data['Format'] = 'Html';
         $Data['Type'] = 'Discussion';
         $NewDiscussionID = $DiscussionModel->save($Data);
         $Sender->Form->setValidationResults($DiscussionModel->validationResults());
         if ($Sender->Form->errorCount() == 0 && $NewDiscussionID > 0) {
             // Re-assign the comments to the new discussion record
             $DiscussionModel->SQL->update('Comment')->set('DiscussionID', $NewDiscussionID)->whereIn('CommentID', $CommentIDs)->put();
             // Update counts on both discussions
             $CommentModel = new CommentModel();
             $CommentModel->updateCommentCount($DiscussionID);
             //            $CommentModel->UpdateUserCommentCounts($DiscussionID);
             $CommentModel->updateCommentCount($NewDiscussionID);
             $CommentModel->removePageCache($DiscussionID, 1);
             // Clear selections
             unset($CheckedComments[$DiscussionID]);
             Gdn::userModel()->saveAttribute($Session->UserID, 'CheckedComments', $CheckedComments);
             ModerationController::informCheckedComments($Sender);
             $Sender->RedirectUrl = url('discussion/' . $NewDiscussionID . '/' . Gdn_Format::url($Data['Name']));
         }
     } else {
         $Sender->Form->setValue('CategoryID', val('CategoryID', $Discussion));
     }
     $Sender->render($this->getView('splitcomments.php'));
 }
Ejemplo n.º 11
0
 /**
  * Build the user profile.
  *
  * Set the page title, add data to page modules, add modules to assets,
  * add tabs to tab menu. $this->User must be defined, or this method will throw an exception.
  *
  * @since 2.0.0
  * @access public
  * @return bool Always true.
  */
 public function buildProfile()
 {
     if (!is_object($this->User)) {
         throw new Exception(t('Cannot build profile information if user is not defined.'));
     }
     $Session = Gdn::session();
     if (strpos($this->CssClass, 'Profile') === false) {
         $this->CssClass .= ' Profile';
     }
     $this->title(Gdn_Format::text($this->User->Name));
     if ($this->_DeliveryType != DELIVERY_TYPE_VIEW) {
         // Javascript needed
         // see note above about jcrop
         $this->addJsFile('jquery.jcrop.min.js');
         $this->addJsFile('profile.js');
         $this->addJsFile('jquery.gardenmorepager.js');
         $this->addJsFile('activity.js');
         // Build activity URL
         $ActivityUrl = 'profile/activity/';
         if ($this->User->UserID != $Session->UserID) {
             $ActivityUrl = userUrl($this->User, '', 'activity');
         }
         // Show activity?
         if (c('Garden.Profile.ShowActivities', true)) {
             $this->addProfileTab(t('Activity'), $ActivityUrl, 'Activity', sprite('SpActivity') . ' ' . t('Activity'));
         }
         // Show notifications?
         if ($this->User->UserID == $Session->UserID) {
             $Notifications = t('Notifications');
             $NotificationsHtml = sprite('SpNotifications') . ' ' . $Notifications;
             $CountNotifications = $Session->User->CountNotifications;
             if (is_numeric($CountNotifications) && $CountNotifications > 0) {
                 $NotificationsHtml .= ' <span class="Aside"><span class="Count">' . $CountNotifications . '</span></span>';
             }
             $this->addProfileTab($Notifications, 'profile/notifications', 'Notifications', $NotificationsHtml);
         }
         // Show invitations?
         if (c('Garden.Registration.Method') == 'Invitation') {
             $this->addProfileTab(t('Invitations'), 'profile/invitations', 'InvitationsLink', sprite('SpInvitations') . ' ' . t('Invitations'));
         }
         $this->fireEvent('AddProfileTabs');
     }
     return true;
 }
Ejemplo n.º 12
0
    $discussionID = val('DiscussionID', $Draft);
    $excerpt = sliceString(Gdn_Format::text(val('Body', $Draft)), 200);
    $isDiscussion = !is_numeric($discussionID) || $discussionID <= 0;
    $orphaned = !val('DiscussionExists', $Draft);
    $editUrl = $isDiscussion || $orphaned ? '/post/editdiscussion/0/' . $draftID : '/discussion/' . $discussionID . '/' . $Offset . '/#Form_Comment';
    $deleteUrl = 'vanilla/drafts/delete/' . $draftID . '/' . Gdn::session()->transientKey() . '?Target=' . urlencode($this->SelfUrl);
    ?>
    <li class="Item Draft">
        <div
            class="Options"><?php 
    echo anchor(t('Draft.Delete', 'Delete'), $deleteUrl, 'Delete');
    ?>
</div>
        <div class="ItemContent">
            <?php 
    echo anchor(Gdn_Format::text(val('Name', $Draft), false), $editUrl, 'Title DraftLink');
    ?>
            <?php 
    if ($excerpt) {
        ?>
                <div class="Excerpt">
                    <?php 
        echo anchor($excerpt, $editUrl);
        ?>
                </div>
            <?php 
    }
    ?>
        </div>
    </li>
<?php 
Ejemplo n.º 13
0
                        </div>
                    </div>
                    <?php 
                if ($NumComplaintsInThread > 1) {
                    echo '<div class="OtherComplaints">' . "\n";
                }
            } else {
                ?>
                    <div class="FlaggedOtherCell">
                        <div
                            class="FlaggedItemInfo"><?php 
                echo t('On') . ' ' . $Flag['DateInserted'] . ', <strong>' . anchor($Flag['InsertName'], "profile/{$Flag['InsertUserID']}/{$Flag['InsertName']}") . '</strong> ' . t('said:');
                ?>
</div>
                        <div class="FlaggedItemComment">"<?php 
                echo Gdn_Format::text($Flag['Comment']);
                ?>
"</div>
                    </div>
                <?php 
            }
        }
        if ($NumComplaintsInThread > 1) {
            echo "</div>\n";
        }
        ?>
        </div>
    <?php 
    }
}
?>
Ejemplo n.º 14
0
    function writeEmbedCommentForm()
    {
        $Session = Gdn::session();
        $Controller = Gdn::controller();
        $Discussion = $Controller->data('Discussion');
        if ($Discussion && $Discussion->Closed == '1') {
            ?>
            <div class="Foot Closed">
                <div class="Note Closed"><?php 
            echo t('This discussion has been closed.');
            ?>
</div>
            </div>
        <?php 
        } else {
            ?>
            <h2><?php 
            echo t('Leave a comment');
            ?>
</h2>
            <div class="MessageForm CommentForm EmbedCommentForm">
                <?php 
            echo $Controller->Form->open(array('id' => 'Form_Comment'));
            echo $Controller->Form->errors();
            echo $Controller->Form->Hidden('Name');
            echo wrap($Controller->Form->textBox('Body', array('MultiLine' => TRUE)), 'div', array('class' => 'TextBoxWrapper'));
            echo "<div class=\"Buttons\">\n";
            $AllowSigninPopup = c('Garden.SignIn.Popup');
            $Attributes = array('tabindex' => '-1', 'target' => '_top');
            // If we aren't ajaxing this call then we need to target the url of the parent frame.
            $ReturnUrl = $Controller->data('ForeignSource.vanilla_url', Gdn::request()->PathAndQuery());
            if ($Session->isValid()) {
                $AuthenticationUrl = Gdn::authenticator()->SignOutUrl($ReturnUrl);
                echo wrap(sprintf(t('Commenting as %1$s (%2$s)', 'Commenting as %1$s <span class="SignOutWrap">(%2$s)</span>'), Gdn_Format::text($Session->User->Name), anchor(t('Sign Out'), $AuthenticationUrl, 'SignOut', $Attributes)), 'div', array('class' => 'Author'));
                echo $Controller->Form->button('Post Comment', array('class' => 'Button CommentButton'));
            } else {
                $AuthenticationUrl = url(SignInUrl($ReturnUrl), true);
                if ($AllowSigninPopup) {
                    $CssClass = 'SignInPopup Button Stash';
                } else {
                    $CssClass = 'Button Stash';
                }
                echo anchor(t('Comment As ...'), $AuthenticationUrl, $CssClass, $Attributes);
            }
            echo "</div>\n";
            echo $Controller->Form->close();
            ?>
            </div>
        <?php 
        }
    }
Ejemplo n.º 15
0
 /**
  * Render the entire head module.
  */
 public function toString()
 {
     // Add the canonical Url if necessary.
     if (method_exists($this->_Sender, 'CanonicalUrl') && !c('Garden.Modules.NoCanonicalUrl', false)) {
         $CanonicalUrl = $this->_Sender->canonicalUrl();
         if (!isUrl($CanonicalUrl)) {
             $CanonicalUrl = Gdn::router()->ReverseRoute($CanonicalUrl);
         }
         $this->_Sender->canonicalUrl($CanonicalUrl);
         //            $CurrentUrl = url('', true);
         //            if ($CurrentUrl != $CanonicalUrl) {
         $this->addTag('link', array('rel' => 'canonical', 'href' => $CanonicalUrl));
         //            }
     }
     // Include facebook open-graph meta information.
     if ($FbAppID = c('Plugins.Facebook.ApplicationID')) {
         $this->addTag('meta', array('property' => 'fb:app_id', 'content' => $FbAppID));
     }
     $SiteName = c('Garden.Title', '');
     if ($SiteName != '') {
         $this->addTag('meta', array('property' => 'og:site_name', 'content' => $SiteName));
     }
     $Title = Gdn_Format::text($this->title('', true));
     if ($Title != '') {
         $this->addTag('meta', array('property' => 'og:title', 'itemprop' => 'name', 'content' => $Title));
     }
     if (isset($CanonicalUrl)) {
         $this->addTag('meta', array('property' => 'og:url', 'content' => $CanonicalUrl));
     }
     if ($Description = $this->_Sender->Description()) {
         $this->addTag('meta', array('name' => 'description', 'property' => 'og:description', 'itemprop' => 'description', 'content' => $Description));
     }
     // Default to the site logo if there were no images provided by the controller.
     if (count($this->_Sender->Image()) == 0) {
         $Logo = c('Garden.ShareImage', c('Garden.Logo', ''));
         if ($Logo != '') {
             // Fix the logo path.
             if (stringBeginsWith($Logo, 'uploads/')) {
                 $Logo = substr($Logo, strlen('uploads/'));
             }
             $Logo = Gdn_Upload::url($Logo);
             $this->addTag('meta', array('property' => 'og:image', 'itemprop' => 'image', 'content' => $Logo));
         }
     } else {
         foreach ($this->_Sender->Image() as $Img) {
             $this->addTag('meta', array('property' => 'og:image', 'itemprop' => 'image', 'content' => $Img));
         }
     }
     $this->fireEvent('BeforeToString');
     $Tags = $this->_Tags;
     // Make sure that css loads before js (for jquery)
     usort($this->_Tags, array('HeadModule', 'TagCmp'));
     // "link" comes before "script"
     $Tags2 = $this->_Tags;
     // Start with the title.
     $Head = '<title>' . Gdn_Format::text($this->title()) . "</title>\n";
     $TagStrings = array();
     // Loop through each tag.
     foreach ($this->_Tags as $Index => $Attributes) {
         $Tag = $Attributes[self::TAG_KEY];
         // Inline the content of the tag, if necessary.
         if (val('_hint', $Attributes) == 'inline') {
             $Path = val('_path', $Attributes);
             if (!stringBeginsWith($Path, 'http')) {
                 $Attributes[self::CONTENT_KEY] = file_get_contents($Path);
                 if (isset($Attributes['src'])) {
                     $Attributes['_src'] = $Attributes['src'];
                     unset($Attributes['src']);
                 }
                 if (isset($Attributes['href'])) {
                     $Attributes['_href'] = $Attributes['href'];
                     unset($Attributes['href']);
                 }
             }
         }
         // If we set an IE conditional AND a "Not IE" condition, we will need to make a second pass.
         do {
             // Reset tag string
             $TagString = '';
             // IE conditional? Validates condition.
             $IESpecific = isset($Attributes['_ie']) && preg_match('/((l|g)t(e)? )?IE [0-9\\.]/', $Attributes['_ie']);
             // Only allow $NotIE if we're not doing a conditional this loop.
             $NotIE = !$IESpecific && isset($Attributes['_notie']);
             // Open IE conditional tag
             if ($IESpecific) {
                 $TagString .= '<!--[if ' . $Attributes['_ie'] . ']>';
             }
             if ($NotIE) {
                 $TagString .= '<!--[if !IE]> -->';
             }
             // Build tag
             $TagString .= '  <' . $Tag . Attribute($Attributes, '_');
             if (array_key_exists(self::CONTENT_KEY, $Attributes)) {
                 $TagString .= '>' . $Attributes[self::CONTENT_KEY] . '</' . $Tag . '>';
             } elseif ($Tag == 'script') {
                 $TagString .= '></script>';
             } else {
                 $TagString .= ' />';
             }
             // Close IE conditional tag
             if ($IESpecific) {
                 $TagString .= '<![endif]-->';
             }
             if ($NotIE) {
                 $TagString .= '<!-- <![endif]-->';
             }
             // Cleanup (prevent infinite loop)
             if ($IESpecific) {
                 unset($Attributes['_ie']);
             }
             $TagStrings[] = $TagString;
         } while ($IESpecific && isset($Attributes['_notie']));
         // We need a second pass
     }
     //endforeach
     $Head .= implode("\n", array_unique($TagStrings));
     foreach ($this->_Strings as $String) {
         $Head .= $String;
         $Head .= "\n";
     }
     return $Head;
 }
Ejemplo n.º 16
0
        echo anchor($User->Email, 'mailto:' . $User->Email);
        ?>
</div>
                        </div>
                    </td>
                    <td>
                        <?php 
        // Output a definition list if a plugin passed us ordered data.
        if (count($this->EventArguments['ApplicantMeta'])) {
            foreach ($this->EventArguments['ApplicantMeta'] as $label => $value) {
                echo '<dt>' . htmlspecialchars($label) . '</dt><dd>' . htmlspecialchars($value) . '</dd>';
            }
        }
        // Only make a blockquote if we got a reason.
        if ($User->DiscoveryText) {
            echo Gdn_Format::text($User->DiscoveryText);
        }
        // Opportunity for plugins to do arbitrary appending.
        $this->fireEvent("AppendApplicantInfo");
        ?>
                    </td>
                    <td><?php 
        echo ipAnchor($User->InsertIPAddress);
        ?>
</td>
                    <td><?php 
        echo Gdn_Format::date($User->DateInserted);
        ?>
</td>
                    <td class="options">
                        <div class="btn-group">
Ejemplo n.º 17
0
Archivo: all.php Proyecto: R-J/vanilla
               <div class="ItemContent Category"><div class="Options">' . getOptions($Category, $this) . '</div>' . Gdn_Format::text($Category->Name) . '</div>
            </li>';
                $Alt = FALSE;
            } else {
                $LastComment = UserBuilder($Category, 'Last');
                $AltCss = $Alt ? ' Alt' : '';
                $Alt = !$Alt;
                $CatList .= '<li id="Category_' . $CategoryID . '" class="' . $CssClass . '">
               <div class="ItemContent Category">' . '<div class="Options">' . getOptions($Category, $this) . '</div>' . CategoryPhoto($Category) . '<div class="TitleWrap">' . anchor(Gdn_Format::text($Category->Name), CategoryUrl($Category), 'Title') . '</div>
                  <div class="CategoryDescription">' . $Category->Description . '</div>
                  <div class="Meta">
                     <span class="MItem RSS">' . anchor(img('applications/dashboard/design/images/rss.gif', array('alt' => T('RSS Feed'))), '/categories/' . $Category->UrlCode . '/feed.rss', '', array('title' => T('RSS Feed'))) . '</span>
                     <span class="MItem DiscussionCount">' . sprintf(PluralTranslate($Category->CountDiscussions, '%s discussion html', '%s discussions html', t('%s discussion'), t('%s discussions')), BigPlural($Category->CountDiscussions, '%s discussion')) . '</span>
                     <span class="MItem CommentCount">' . sprintf(PluralTranslate($Category->CountComments, '%s comment html', '%s comments html', t('%s comment'), t('%s comments')), BigPlural($Category->CountComments, '%s comment')) . '</span>';
                if ($Category->LastTitle != '') {
                    $CatList .= '<span class="MItem LastDiscussionTitle">' . sprintf(t('Most recent: %1$s by %2$s'), anchor(Gdn_Format::text(sliceString($Category->LastTitle, 40)), $Category->LastUrl), userAnchor($LastComment)) . '</span>' . '<span class="MItem LastCommentDate">' . Gdn_Format::date($Category->LastDateInserted) . '</span>';
                }
                // If this category is one level above the max display depth, and it
                // has children, add a replacement string for them.
                if ($MaxDisplayDepth > 0 && $Category->Depth == $MaxDisplayDepth - 1 && $Category->TreeRight - $Category->TreeLeft > 1) {
                    $CatList .= '{ChildCategories}';
                }
                $CatList .= '</div>
               </div>
            </li>';
            }
        }
    }
}
// If there are any remaining child categories that have been collected, do
// the replacement one last time.
Ejemplo n.º 18
0
    <entry>
        <title type="html"><![CDATA[<?php 
    echo Gdn_Format::RssHtml($Discussion->Name);
    ?>
]]></title>
        <link href="<?php 
    echo $Discussion->Url;
    ?>
"/>
        <id><?php 
    echo $Discussion->DiscussionID . '@' . Url('/discussions');
    ?>
</id>
        <author>
            <name><?php 
    echo Gdn_Format::text($Discussion->FirstName);
    ?>
</name>
            <uri><?php 
    echo htmlspecialchars(url('/profile/' . $Discussion->InsertUserID . '/' . $Discussion->FirstName, true));
    ?>
</uri>
        </author>
        <updated><?php 
    echo date('c', Gdn_Format::ToTimeStamp($Discussion->DateLastComment));
    ?>
</updated>
        <summary><![CDATA[<?php 
    echo Gdn_Format::RssHtml($Discussion->Body, $Discussion->Format);
    ?>
]]></summary>
Ejemplo n.º 19
0
 /**
  * Create or update a discussion.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $CategoryID Unique ID of the category to add the discussion to.
  */
 public function discussion($CategoryUrlCode = '')
 {
     // Override CategoryID if categories are disabled
     $UseCategories = $this->ShowCategorySelector = (bool) c('Vanilla.Categories.Use');
     if (!$UseCategories) {
         $CategoryUrlCode = '';
     }
     // Setup head
     $this->addJsFile('jquery.autosize.min.js');
     $this->addJsFile('autosave.js');
     $this->addJsFile('post.js');
     $Session = Gdn::session();
     Gdn_Theme::section('PostDiscussion');
     // Set discussion, draft, and category data
     $DiscussionID = isset($this->Discussion) ? $this->Discussion->DiscussionID : '';
     $DraftID = isset($this->Draft) ? $this->Draft->DraftID : 0;
     $Category = false;
     $CategoryModel = new CategoryModel();
     if (isset($this->Discussion)) {
         $this->CategoryID = $this->Discussion->CategoryID;
         $Category = CategoryModel::categories($this->CategoryID);
     } elseif ($CategoryUrlCode != '') {
         $Category = CategoryModel::categories($CategoryUrlCode);
         if ($Category) {
             $this->CategoryID = val('CategoryID', $Category);
         }
     }
     if ($Category) {
         $this->Category = (object) $Category;
         $this->setData('Category', $Category);
         $this->Form->addHidden('CategoryID', $this->Category->CategoryID);
         if (val('DisplayAs', $this->Category) == 'Discussions' && !$DraftID) {
             $this->ShowCategorySelector = false;
         } else {
             // Get all our subcategories to add to the category if we are in a Header or Categories category.
             $this->Context = CategoryModel::getSubtree($this->CategoryID);
         }
     } else {
         $this->CategoryID = 0;
         $this->Category = null;
     }
     $CategoryData = $this->ShowCategorySelector ? CategoryModel::categories() : false;
     // Check permission
     if (isset($this->Discussion)) {
         // Make sure that content can (still) be edited.
         $CanEdit = DiscussionModel::canEdit($this->Discussion);
         if (!$CanEdit) {
             throw permissionException('Vanilla.Discussions.Edit');
         }
         // Make sure only moderators can edit closed things
         if ($this->Discussion->Closed) {
             $this->permission('Vanilla.Discussions.Edit', true, 'Category', $this->Category->PermissionCategoryID);
         }
         $this->Form->setFormValue('DiscussionID', $this->Discussion->DiscussionID);
         $this->title(t('Edit Discussion'));
         if ($this->Discussion->Type) {
             $this->setData('Type', $this->Discussion->Type);
         } else {
             $this->setData('Type', 'Discussion');
         }
     } else {
         // Permission to add.
         if ($this->Category) {
             $this->permission('Vanilla.Discussions.Add', true, 'Category', $this->Category->PermissionCategoryID);
         } else {
             $this->permission('Vanilla.Discussions.Add');
         }
         $this->title(t('New Discussion'));
     }
     touchValue('Type', $this->Data, 'Discussion');
     // See if we should hide the category dropdown.
     if ($this->ShowCategorySelector) {
         $AllowedCategories = CategoryModel::getByPermission('Discussions.Add', $this->Form->getValue('CategoryID', $this->CategoryID), ['Archived' => 0, 'AllowDiscussions' => 1], ['AllowedDiscussionTypes' => $this->Data['Type']]);
         if (count($AllowedCategories) == 1) {
             $AllowedCategory = array_pop($AllowedCategories);
             $this->ShowCategorySelector = false;
             $this->Form->addHidden('CategoryID', $AllowedCategory['CategoryID']);
             if ($this->Form->isPostBack() && !$this->Form->getFormValue('CategoryID')) {
                 $this->Form->setFormValue('CategoryID', $AllowedCategory['CategoryID']);
             }
         }
     }
     // Set the model on the form
     $this->Form->setModel($this->DiscussionModel);
     if (!$this->Form->isPostBack()) {
         // Prep form with current data for editing
         if (isset($this->Discussion)) {
             $this->Form->setData($this->Discussion);
         } elseif (isset($this->Draft)) {
             $this->Form->setData($this->Draft);
         } else {
             if ($this->Category !== null) {
                 $this->Form->setData(array('CategoryID' => $this->Category->CategoryID));
             }
             $this->populateForm($this->Form);
         }
     } elseif ($this->Form->authenticatedPostBack()) {
         // Form was submitted
         // Save as a draft?
         $FormValues = $this->Form->formValues();
         $FormValues = $this->DiscussionModel->filterForm($FormValues);
         $this->deliveryType(Gdn::request()->getValue('DeliveryType', $this->_DeliveryType));
         if ($DraftID == 0) {
             $DraftID = $this->Form->getFormValue('DraftID', 0);
         }
         $Draft = $this->Form->buttonExists('Save_Draft') ? true : false;
         $Preview = $this->Form->buttonExists('Preview') ? true : false;
         if (!$Preview) {
             if (!is_object($this->Category) && is_array($CategoryData) && isset($FormValues['CategoryID'])) {
                 $this->Category = val($FormValues['CategoryID'], $CategoryData);
             }
             if (is_object($this->Category)) {
                 // Check category permissions.
                 if ($this->Form->getFormValue('Announce', '') && !$Session->checkPermission('Vanilla.Discussions.Announce', true, 'Category', $this->Category->PermissionCategoryID)) {
                     $this->Form->addError('You do not have permission to announce in this category', 'Announce');
                 }
                 if ($this->Form->getFormValue('Close', '') && !$Session->checkPermission('Vanilla.Discussions.Close', true, 'Category', $this->Category->PermissionCategoryID)) {
                     $this->Form->addError('You do not have permission to close in this category', 'Close');
                 }
                 if ($this->Form->getFormValue('Sink', '') && !$Session->checkPermission('Vanilla.Discussions.Sink', true, 'Category', $this->Category->PermissionCategoryID)) {
                     $this->Form->addError('You do not have permission to sink in this category', 'Sink');
                 }
                 if (!isset($this->Discussion) && (!$Session->checkPermission('Vanilla.Discussions.Add', true, 'Category', $this->Category->PermissionCategoryID) || !$this->Category->AllowDiscussions)) {
                     $this->Form->addError('You do not have permission to start discussions in this category', 'CategoryID');
                 }
             }
             $isTitleValid = true;
             $Name = trim($this->Form->getFormValue('Name', ''));
             if (!$Draft) {
                 // Let's be super aggressive and disallow titles with no word characters in them!
                 $hasWordCharacter = preg_match('/\\w/u', $Name) === 1;
                 if (!$hasWordCharacter || $Name != '' && Gdn_Format::text($Name) == '') {
                     $this->Form->addError(t('You have entered an invalid discussion title'), 'Name');
                     $isTitleValid = false;
                 }
             }
             if ($isTitleValid) {
                 // Trim the name.
                 $FormValues['Name'] = $Name;
                 $this->Form->setFormValue('Name', $Name);
             }
             if ($this->Form->errorCount() == 0) {
                 if ($Draft) {
                     $DraftID = $this->DraftModel->save($FormValues);
                     $this->Form->setValidationResults($this->DraftModel->validationResults());
                 } else {
                     $DiscussionID = $this->DiscussionModel->save($FormValues);
                     $this->Form->setValidationResults($this->DiscussionModel->validationResults());
                     if ($DiscussionID > 0) {
                         if ($DraftID > 0) {
                             $this->DraftModel->delete($DraftID);
                         }
                     }
                     if ($DiscussionID == SPAM || $DiscussionID == UNAPPROVED) {
                         $this->StatusMessage = t('DiscussionRequiresApprovalStatus', 'Your discussion will appear after it is approved.');
                         // Clear out the form so that a draft won't save.
                         $this->Form->formValues(array());
                         $this->render('Spam');
                         return;
                     }
                 }
             }
         } else {
             // If this was a preview click, create a discussion/comment shell with the values for this comment
             $this->Discussion = new stdClass();
             $this->Discussion->Name = $this->Form->getValue('Name', '');
             $this->Comment = new stdClass();
             $this->Comment->InsertUserID = $Session->User->UserID;
             $this->Comment->InsertName = $Session->User->Name;
             $this->Comment->InsertPhoto = $Session->User->Photo;
             $this->Comment->DateInserted = Gdn_Format::date();
             $this->Comment->Body = val('Body', $FormValues, '');
             $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
             $this->EventArguments['Discussion'] =& $this->Discussion;
             $this->EventArguments['Comment'] =& $this->Comment;
             $this->fireEvent('BeforeDiscussionPreview');
             if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
                 $this->addAsset('Content', $this->fetchView('preview'));
             } else {
                 $this->View = 'preview';
             }
         }
         if ($this->Form->errorCount() > 0) {
             // Return the form errors
             $this->errorMessage($this->Form->errors());
         } elseif ($DiscussionID > 0 || $DraftID > 0) {
             // Make sure that the ajax request form knows about the newly created discussion or draft id
             $this->setJson('DiscussionID', $DiscussionID);
             $this->setJson('DraftID', $DraftID);
             if (!$Preview) {
                 // If the discussion was not a draft
                 if (!$Draft) {
                     // Redirect to the new discussion
                     $Discussion = $this->DiscussionModel->getID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => false));
                     $this->setData('Discussion', $Discussion);
                     $this->EventArguments['Discussion'] = $Discussion;
                     $this->fireEvent('AfterDiscussionSave');
                     if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
                         redirect(discussionUrl($Discussion, 1)) . '?new=1';
                     } else {
                         $this->RedirectUrl = discussionUrl($Discussion, 1, true) . '?new=1';
                     }
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
             }
         }
     }
     // Add hidden fields for editing
     $this->Form->addHidden('DiscussionID', $DiscussionID);
     $this->Form->addHidden('DraftID', $DraftID, true);
     $this->fireEvent('BeforeDiscussionRender');
     if ($this->CategoryID) {
         $Breadcrumbs = CategoryModel::getAncestors($this->CategoryID);
     } else {
         $Breadcrumbs = array();
     }
     $Breadcrumbs[] = array('Name' => $this->data('Title'), 'Url' => val('AddUrl', val($this->data('Type'), DiscussionModel::discussionTypes()), '/post/discussion'));
     $this->setData('Breadcrumbs', $Breadcrumbs);
     $this->setData('_AnnounceOptions', $this->announceOptions());
     // Render view (posts/discussion.php or post/preview.php)
     $this->render();
 }
Ejemplo n.º 20
0
    ?>
    <item>
        <title><?php 
    echo Gdn_Format::text(val('Headline', $Activity));
    ?>
</title>
        <link><?php 
    echo url(userUrl($Author, '', 'activity'), true);
    ?>
</link>
        <pubDate><?php 
    echo date('r', Gdn_Format::ToTimeStamp(val('DateUpdated', $Activity)));
    ?>
</pubDate>
        <dc:creator><?php 
    echo Gdn_Format::text($Author->Name);
    ?>
</dc:creator>
        <guid
            isPermaLink="false"><?php 
    echo val('ActivityID', $Activity) . '@' . Url(userUrl($Author, '', 'activity'));
    ?>
</guid>
        <?php 
    if ($Story = val('Story', $Activity)) {
        ?>
            <description><![CDATA[<?php 
        echo Gdn_Format::RssHtml($Story, val('Format', $Activity));
        ?>
]]>
            </description>
Ejemplo n.º 21
0
 /**
  * Registration that requires approval.
  *
  * Events: RegistrationPending
  *
  * @access private
  * @since 2.0.0
  */
 private function registerApproval()
 {
     Gdn::userModel()->addPasswordStrength($this);
     // If the form has been posted back...
     if ($this->Form->isPostBack()) {
         // Add validation rules that are not enforced by the model
         $this->UserModel->defineSchema();
         $this->UserModel->Validation->applyRule('Name', 'Username', $this->UsernameError);
         $this->UserModel->Validation->applyRule('TermsOfService', 'Required', t('You must agree to the terms of service.'));
         $this->UserModel->Validation->applyRule('Password', 'Required');
         $this->UserModel->Validation->applyRule('Password', 'Strength');
         $this->UserModel->Validation->applyRule('Password', 'Match');
         $this->UserModel->Validation->applyRule('DiscoveryText', 'Required', 'Tell us why you want to join!');
         // $this->UserModel->Validation->applyRule('DateOfBirth', 'MinimumAge');
         $this->fireEvent('RegisterValidation');
         try {
             $Values = $this->Form->formValues();
             $Values = $this->UserModel->filterForm($Values, true);
             unset($Values['Roles']);
             $AuthUserID = $this->UserModel->register($Values);
             $this->setData('UserID', $AuthUserID);
             if (!$AuthUserID) {
                 $this->Form->setValidationResults($this->UserModel->validationResults());
             } else {
                 // The user has been created successfully, so sign in now.
                 Gdn::session()->start($AuthUserID);
                 if ($this->Form->getFormValue('RememberMe')) {
                     Gdn::authenticator()->SetIdentity($AuthUserID, true);
                 }
                 // Notification text
                 $Label = t('NewApplicantEmail', 'New applicant:');
                 $Story = anchor(Gdn_Format::text($Label . ' ' . $Values['Name']), ExternalUrl('dashboard/user/applicants'));
                 $this->EventArguments['AuthUserID'] = $AuthUserID;
                 $this->EventArguments['Story'] =& $Story;
                 $this->fireEvent('RegistrationPending');
                 $this->View = "RegisterThanks";
                 // Tell the user their application will be reviewed by an administrator.
                 // Grab all of the users that need to be notified.
                 $Data = Gdn::database()->sql()->getWhere('UserMeta', array('Name' => 'Preferences.Email.Applicant'))->resultArray();
                 $ActivityModel = new ActivityModel();
                 foreach ($Data as $Row) {
                     $ActivityModel->add($AuthUserID, 'Applicant', $Story, $Row['UserID'], '', '/dashboard/user/applicants', 'Only');
                 }
             }
         } catch (Exception $Ex) {
             $this->Form->addError($Ex);
         }
         $this->render();
     } else {
         $this->render();
     }
 }
Ejemplo n.º 22
0
 /**
  * Default search functionality.
  *
  * @since 2.0.0
  * @access public
  * @param int $Page Page number.
  */
 public function index($Page = '')
 {
     $this->addJsFile('search.js');
     $this->title(t('Search'));
     saveToConfig('Garden.Format.EmbedSize', '160x90', false);
     Gdn_Theme::section('SearchResults');
     list($Offset, $Limit) = offsetLimit($Page, c('Garden.Search.PerPage', 20));
     $this->setData('_Limit', $Limit);
     $Search = $this->Form->getFormValue('Search');
     $Mode = $this->Form->getFormValue('Mode');
     if ($Mode) {
         $this->SearchModel->ForceSearchMode = $Mode;
     }
     try {
         $ResultSet = $this->SearchModel->search($Search, $Offset, $Limit);
     } catch (Gdn_UserException $Ex) {
         $this->Form->addError($Ex);
         $ResultSet = array();
     } catch (Exception $Ex) {
         LogException($Ex);
         $this->Form->addError($Ex);
         $ResultSet = array();
     }
     Gdn::userModel()->joinUsers($ResultSet, array('UserID'));
     // Fix up the summaries.
     $SearchTerms = explode(' ', Gdn_Format::text($Search));
     foreach ($ResultSet as &$Row) {
         $Row['Summary'] = searchExcerpt(htmlspecialchars(Gdn_Format::plainText($Row['Summary'], $Row['Format'])), $SearchTerms);
         $Row['Summary'] = Emoji::instance()->translateToHtml($Row['Summary']);
         $Row['Format'] = 'Html';
     }
     $this->setData('SearchResults', $ResultSet, true);
     $this->setData('SearchTerm', Gdn_Format::text($Search), true);
     $this->setData('_CurrentRecords', count($ResultSet));
     $this->canonicalUrl(url('search', true));
     $this->render();
 }
Ejemplo n.º 23
0
    ?>
</th>
            <th class="options"></th>
        </tr>
        </thead>
        <tbody>
            <?php 
    foreach ($this->FlaggedItems as $URL => $FlaggedList) {
        ksort($FlaggedList, SORT_STRING);
        $numComplaintsInThread = sizeof($FlaggedList);
        $multipleReportsString = '<div class="info italic">' . sprintf(t('Flagged by %s users.'), $numComplaintsInThread) . '</div>';
        $flaggedBy = $numComplaintsInThread > 1 ? $multipleReportsString : '';
        foreach ($FlaggedList as $FlagIndex => $Flag) {
            $type = ucfirst($Flag['ForeignType']);
            $flaggedBy .= sprintf(t('<strong>%s</strong> on %s'), anchor($Flag['InsertName'], "profile/{$Flag['InsertUserID']}/{$Flag['InsertName']}"), $Flag['DateInserted']) . ' ' . t('said:');
            $flaggedBy .= '<div class="FlaggedReason">' . Gdn_Format::text($Flag['Comment']) . '</div>';
        }
        $options = anchor(t('Take Action'), $Flag['ForeignURL'], 'btn btn-primary');
        $options .= anchor(t('Dismiss'), 'plugin/flagging/dismiss/' . $Flag['EncodedURL'], 'btn btn-primary js-modal-confirm js-hijack', ['data-body' => t('Are you sure you want to dismiss this flag?')]);
        ?>
                <tr>
                    <td class="FlaggedType"><?php 
        echo $type;
        ?>
</td>
                    <td class="FlaggedBy"><?php 
        echo $flaggedBy;
        ?>
</td>
                    <td class="options">
                        <div class="btn-group">
Ejemplo n.º 24
0
 /**
  * Takes a mixed variable, formats it in the specified format type, and
  * returns it.
  *
  * @param mixed $Mixed An object, array, or string to be formatted.
  * @param string $FormatMethod The method with which the variable should be formatted.
  * @return mixed
  */
 public static function to($Mixed, $FormatMethod)
 {
     // Process $Mixed based on its type.
     if (is_string($Mixed)) {
         if (in_array(strtolower($FormatMethod), self::$SanitizedFormats) && method_exists('Gdn_Format', $FormatMethod)) {
             $Mixed = self::$FormatMethod($Mixed);
         } elseif (function_exists('format' . $FormatMethod)) {
             $FormatMethod = 'format' . $FormatMethod;
             $Mixed = $FormatMethod($Mixed);
         } elseif ($Formatter = Gdn::factory($FormatMethod . 'Formatter')) {
             $Mixed = $Formatter->format($Mixed);
         } else {
             $Mixed = Gdn_Format::text($Mixed);
         }
     } elseif (is_array($Mixed)) {
         foreach ($Mixed as $Key => $Val) {
             $Mixed[$Key] = self::to($Val, $FormatMethod);
         }
     } elseif (is_object($Mixed)) {
         foreach (get_object_vars($Mixed) as $Prop => $Val) {
             $Mixed->{$Prop} = self::to($Val, $FormatMethod);
         }
     }
     return $Mixed;
 }
Ejemplo n.º 25
0
 /**
  * Convert tags from stored format to user-presentable format.
  *
  * @since 2.1
  * @access protected
  *
  * @param string Serialized array.
  * @return string Comma-separated tags.
  */
 protected function formatTags($Tags)
 {
     // Don't bother if there aren't any tags
     if (!$Tags) {
         return '';
     }
     // Get the array
     $TagsArray = Gdn_Format::Unserialize($Tags);
     // Compensate for deprecated space-separated format
     if (is_string($TagsArray) && $TagsArray == $Tags) {
         $TagsArray = explode(' ', $Tags);
     }
     // Safe format
     $TagsArray = Gdn_Format::text($TagsArray);
     // Send back an comma-separated string
     return is_array($TagsArray) ? implode(',', $TagsArray) : '';
 }
 /**
  * Default search functionality.
  *
  * @since 2.0.0
  * @access public
  * @param int $Page Page number.
  */
 public function index($Page = '')
 {
     $this->addJsFile('search.js');
     $this->title(t('Search'));
     saveToConfig('Garden.Format.EmbedSize', '160x90', false);
     Gdn_Theme::section('SearchResults');
     list($Offset, $Limit) = offsetLimit($Page, c('Garden.Search.PerPage', 20));
     $this->setData('_Limit', $Limit);
     $Search = $this->Form->getFormValue('Search');
     $Mode = $this->Form->getFormValue('Mode');
     if ($Mode) {
         $this->SearchModel->ForceSearchMode = $Mode;
     }
     try {
         $ResultSet = $this->SearchModel->Search($Search, $Offset, $Limit);
     } catch (Gdn_UserException $Ex) {
         $this->Form->addError($Ex);
         $ResultSet = array();
     } catch (Exception $Ex) {
         LogException($Ex);
         $this->Form->addError($Ex);
         $ResultSet = array();
     }
     Gdn::userModel()->joinUsers($ResultSet, array('UserID'));
     // Fix up the summaries.
     $SearchTerms = explode(' ', Gdn_Format::text($Search));
     foreach ($ResultSet as &$Row) {
         $Row['Summary'] = SearchExcerpt(Gdn_Format::plainText($Row['Summary'], $Row['Format']), $SearchTerms);
         $Row['Summary'] = Emoji::instance()->translateToHtml($Row['Summary']);
         $Row['Format'] = 'Html';
     }
     $this->setData('SearchResults', $ResultSet, true);
     $this->setData('SearchTerm', Gdn_Format::text($Search), true);
     if ($ResultSet) {
         $NumResults = count($ResultSet);
     } else {
         $NumResults = 0;
     }
     if ($NumResults == $Offset + $Limit) {
         $NumResults++;
     }
     // Build a pager
     $PagerFactory = new Gdn_PagerFactory();
     $this->Pager = $PagerFactory->GetPager('MorePager', $this);
     $this->Pager->MoreCode = 'More Results';
     $this->Pager->LessCode = 'Previous Results';
     $this->Pager->ClientID = 'Pager';
     $this->Pager->configure($Offset, $Limit, $NumResults, 'dashboard/search/%1$s/%2$s/?Search=' . Gdn_Format::url($Search));
     //		if ($this->_DeliveryType != DELIVERY_TYPE_ALL) {
     //         $this->setJson('LessRow', $this->Pager->toString('less'));
     //         $this->setJson('MoreRow', $this->Pager->toString('more'));
     //         $this->View = 'results';
     //      }
     $this->canonicalUrl(url('search', true));
     $this->render();
 }
Ejemplo n.º 27
0
    function writeTableRow($Row, $Depth = 1)
    {
        $Children = $Row['Children'];
        $WriteChildren = FALSE;
        if (!empty($Children)) {
            if ($Depth + 1 >= c('Vanilla.Categories.MaxDisplayDepth')) {
                $WriteChildren = 'list';
            } else {
                $WriteChildren = 'rows';
            }
        }
        $H = 'h' . ($Depth + 1);
        ?>
        <tr class="<?php 
        echo CssClass($Row);
        ?>
">
            <td class="CategoryName">
                <div class="Wrap">
                    <?php 
        echo GetOptions($Row);
        echo CategoryPhoto($Row);
        echo "<{$H}>";
        echo anchor(htmlspecialchars($Row['Name']), $Row['Url']);
        Gdn::controller()->EventArguments['Category'] = $Row;
        Gdn::controller()->fireEvent('AfterCategoryTitle');
        echo "</{$H}>";
        ?>
                    <div class="CategoryDescription">
                        <?php 
        echo $Row['Description'];
        ?>
                    </div>
                    <?php 
        if ($WriteChildren === 'list') {
            ?>
                        <div class="ChildCategories">
                            <?php 
            echo wrap(t('Child Categories') . ': ', 'b');
            echo CategoryString($Children, $Depth + 1);
            ?>
                        </div>
                    <?php 
        }
        ?>
                </div>
            </td>
            <td class="BigCount CountDiscussions">
                <div class="Wrap">
                    <?php 
        //            echo "({$Row['CountDiscussions']})";
        echo BigPlural($Row['CountAllDiscussions'], '%s discussion');
        ?>
                </div>
            </td>
            <td class="BigCount CountComments">
                <div class="Wrap">
                    <?php 
        //            echo "({$Row['CountComments']})";
        echo BigPlural($Row['CountAllComments'], '%s comment');
        ?>
                </div>
            </td>
            <td class="BlockColumn LatestPost">
                <div class="Block Wrap">
                    <?php 
        if ($Row['LastTitle']) {
            ?>
                        <?php 
            echo userPhoto($Row, array('Size' => 'Small', 'Px' => 'Last'));
            echo anchor(SliceString(Gdn_Format::text($Row['LastTitle']), 100), $Row['LastUrl'], 'BlockTitle LatestPostTitle', array('title' => html_entity_decode($Row['LastTitle'])));
            ?>
                        <div class="Meta">
                            <?php 
            echo userAnchor($Row, 'UserLink MItem', 'Last');
            ?>
                            <span class="Bullet">•</span>
                            <?php 
            echo anchor(Gdn_Format::date($Row['LastDateInserted'], 'html'), $Row['LastUrl'], 'CommentDate MItem');
            if (isset($Row['LastCategoryID'])) {
                $LastCategory = CategoryModel::categories($Row['LastCategoryID']);
                echo ' <span>', sprintf('in %s', anchor($LastCategory['Name'], CategoryUrl($LastCategory, '', '//'))), '</span>';
            }
            ?>
                        </div>
                    <?php 
        }
        ?>
                </div>
            </td>
        </tr>
        <?php 
        if ($WriteChildren === 'rows') {
            foreach ($Children as $ChildRow) {
                WriteTableRow($ChildRow, $Depth + 1);
            }
        }
    }
 /**
  * Display custom fields on Profile.
  */
 public function userInfoModule_onBasicInfo_handler($Sender)
 {
     if ($Sender->User->Banned) {
         return;
     }
     try {
         // Get the custom fields
         $ProfileFields = Gdn::userModel()->getMeta($Sender->User->UserID, 'Profile.%', 'Profile.');
         // Import from CustomProfileFields if available
         if (!count($ProfileFields) && is_object($Sender->User) && c('Plugins.CustomProfileFields.SuggestedFields', false)) {
             $ProfileFields = Gdn::userModel()->getAttribute($Sender->User->UserID, 'CustomProfileFields', false);
             if ($ProfileFields) {
                 // Migrate to UserMeta & delete original
                 Gdn::userModel()->setMeta($Sender->User->UserID, $ProfileFields, 'Profile.');
                 Gdn::userModel()->saveAttribute($Sender->User->UserID, 'CustomProfileFields', false);
             }
         }
         // Send them off for magic formatting
         $ProfileFields = $this->parseSpecialFields($ProfileFields);
         // Get all field data, error check
         $AllFields = $this->getProfileFields();
         if (!is_array($AllFields) || !is_array($ProfileFields)) {
             return;
         }
         // DateOfBirth is special case that core won't handle
         // Hack it in here instead
         if (c('ProfileExtender.Fields.DateOfBirth.OnProfile')) {
             // Do not use Gdn_Format::Date because it shifts to local timezone
             $BirthdayStamp = Gdn_Format::toTimestamp($Sender->User->DateOfBirth);
             if ($BirthdayStamp) {
                 $ProfileFields['DateOfBirth'] = date(t('Birthday Format', 'F j, Y'), $BirthdayStamp);
                 $AllFields['DateOfBirth'] = array('Label' => t('Birthday'), 'OnProfile' => true);
             }
         }
         // Display all non-hidden fields
         $ProfileFields = array_reverse($ProfileFields);
         foreach ($ProfileFields as $Name => $Value) {
             // Skip empty and hidden fields.
             if (!$Value || !val('OnProfile', $AllFields[$Name])) {
                 continue;
             }
             // Non-magic fields must be plain text, but we'll auto-link
             if (!in_array($Name, $this->MagicLabels)) {
                 $Value = Gdn_Format::links(Gdn_Format::text($Value));
             }
             echo ' <dt class="ProfileExtend Profile' . Gdn_Format::alphaNumeric($Name) . '">' . Gdn_Format::text($AllFields[$Name]['Label']) . '</dt> ';
             echo ' <dd class="ProfileExtend Profile' . Gdn_Format::alphaNumeric($Name) . '">' . Gdn_Format::htmlFilter($Value) . '</dd> ';
         }
     } catch (Exception $ex) {
         // No errors
     }
 }
Ejemplo n.º 29
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(htmlspecialchars(sliceString(Gdn_Format::plainText($Content['Body'], $Content['Format']), $Sender->BodyLimit)), $ContentURL, 'BodyLink');
        $Sender->fireEvent('AfterPromotedBody');
        // separate event to account for less space.
        ?>
            </div>
        </div>
    <?php 
    }
Ejemplo n.º 30
0
 /**
  * Renders a plaintext email.
  *
  * @return string A plaintext email.
  */
 protected function plainTextEmail()
 {
     $email = ['banner' => val('alt', $this->image) . ' ' . val('link', $this->image), 'title' => $this->getTitle(), 'lead' => $this->getLead(), 'message' => $this->getMessage(), 'button' => sprintf(t('%s: %s'), val('text', $this->button), val('url', $this->button)), 'footer' => $this->getFooter()];
     foreach ($email as $key => $val) {
         if (!$val) {
             unset($email[$key]);
         } else {
             if ($key == 'message') {
                 $email[$key] = "<br>{$val}<br>";
             }
         }
     }
     return Gdn_Format::plainText(Gdn_Format::text(implode('<br>', $email), false));
 }