コード例 #1
0
 public function ProfileController_Quotes_Create($Sender)
 {
     $Sender->Permission('Garden.SignIn.Allow');
     $Sender->Title("Quotes Settings");
     $Args = $Sender->RequestArgs;
     if (sizeof($Args) < 2) {
         $Args = array_merge($Args, array(0, 0));
     } elseif (sizeof($Args) > 2) {
         $Args = array_slice($Args, 0, 2);
     }
     list($UserReference, $Username) = $Args;
     $Sender->GetUserInfo($UserReference, $Username);
     $UserPrefs = Gdn_Format::Unserialize($Sender->User->Preferences);
     if (!is_array($UserPrefs)) {
         $UserPrefs = array();
     }
     $UserID = $ViewingUserID = Gdn::Session()->UserID;
     if ($Sender->User->UserID != $ViewingUserID) {
         $Sender->Permission('Garden.Users.Edit');
         $UserID = $Sender->User->UserID;
     }
     $Sender->SetData('ForceEditing', $UserID == Gdn::Session()->UserID ? FALSE : $Sender->User->Name);
     $QuoteFolding = GetValue('Quotes.Folding', $UserPrefs, '1');
     $Sender->Form->SetValue('QuoteFolding', $QuoteFolding);
     $Sender->SetData('QuoteFoldingOptions', array('None' => t("Don't fold quotes"), '1' => Plural(1, '%s level deep', '%s levels deep'), '2' => Plural(2, '%s level deep', '%s levels deep'), '3' => Plural(3, '%s level deep', '%s levels deep'), '4' => Plural(4, '%s level deep', '%s levels deep'), '5' => Plural(5, '%s level deep', '%s levels deep')));
     // If seeing the form for the first time...
     if ($Sender->Form->IsPostBack()) {
         $NewFoldingLevel = $Sender->Form->GetValue('QuoteFolding', '1');
         if ($NewFoldingLevel != $QuoteFolding) {
             Gdn::UserModel()->SavePreference($UserID, 'Quotes.Folding', $NewFoldingLevel);
             $Sender->InformMessage(T("Your changes have been saved."));
         }
     }
     $Sender->Render('quotes', '', 'plugins/Quotes');
 }
コード例 #2
0
 protected function _AttachPostCount($Sender)
 {
     $User = Gdn::UserModel()->GetID($Sender->EventArguments['Author']->UserID);
     if ($User) {
         $Posts = GetValue('CountComments', $User, 0) + GetValue('CountDiscussions', $User, 0);
         echo '<span class="MItem PostCount">' . Plural(number_format($Posts), '@' . T('Posts.Singular: %s', 'Posts: <b>%s</b>'), '@' . T('Posts.Plural: %s', 'Posts: <b>%s</b>')) . '</span>';
     }
 }
コード例 #3
0
ファイル: onlineusers.php プロジェクト: Servault/Blargboard
function OnlineUsers($forum = 0, $update = true)
{
    global $loguserid;
    $forumClause = "";
    $browseLocation = __("online");
    if ($update) {
        if ($loguserid) {
            Query("UPDATE {users} SET lastforum={0} WHERE id={1}", $forum, $loguserid);
        } else {
            Query("UPDATE {guests} SET lastforum={0} WHERE ip={1}", $forum, $_SERVER['REMOTE_ADDR']);
        }
    }
    if ($forum) {
        $forumClause = " and lastforum={1}";
        $forumName = FetchResult("SELECT title FROM {forums} WHERE id={0}", $forum);
        $browseLocation = format(__("browsing {0}"), $forumName);
    }
    $rOnlineUsers = Query("select u.(_userfields) from {users} u where (lastactivity > {0} or lastposttime > {0}) and loggedin = 1 " . $forumClause . " order by name", time() - 300, $forum);
    $onlineUserCt = 0;
    $onlineUsers = "";
    while ($user = Fetch($rOnlineUsers)) {
        $user = getDataPrefix($user, "u_");
        $userLink = UserLink($user, true);
        $onlineUsers .= ($onlineUserCt ? ", " : "") . $userLink;
        $onlineUserCt++;
    }
    //$onlineUsers = $onlineUserCt." "user".(($onlineUserCt > 1 || $onlineUserCt == 0) ? "s" : "")." ".$browseLocation.($onlineUserCt ? ": " : ".").$onlineUsers;
    $onlineUsers = Plural($onlineUserCt, __("user")) . " " . $browseLocation . ($onlineUserCt ? ": " : ".") . $onlineUsers;
    $data = Fetch(Query("select \n\t\t(select count(*) from {guests} where bot=0 and date > {0} {$forumClause}) as guests,\n\t\t(select count(*) from {guests} where bot=1 and date > {0} {$forumClause}) as bots\n\t\t", time() - 300, $forum));
    $guests = $data["guests"];
    $bots = $data["bots"];
    if ($guests) {
        $onlineUsers .= " | " . Plural($guests, __("guest"));
    }
    if ($bots) {
        $onlineUsers .= " | " . Plural($bots, __("bot"));
    }
    //	$onlineUsers = "<div style=\"display: inline-block; height: 16px; overflow: hidden; padding: 0px; line-height: 16px;\">".$onlineUsers."</div>";
    return $onlineUsers;
}
コード例 #4
0
ファイル: results.php プロジェクト: Nordic-T/vanilla-plugins
function RenderQuestion($Question)
{
    echo '<li class="DP_ResultQuestion">';
    echo Wrap($Question->Title, 'span');
    echo Wrap(sprintf(Plural($Question->CountResponses, '%s vote', '%s votes'), $Question->CountResponses), 'span', array('class' => 'Number DP_VoteCount'));
    // 'randomize' option bar colors
    $k = $Question->QuestionID % 10;
    echo '<ol class="DP_ResultOptions">';
    foreach ($Question->Options as $Option) {
        $String = Wrap($Option->Title, 'div');
        $Percentage = $Question->CountResponses == 0 ? '0.00' : number_format($Option->CountVotes / $Question->CountResponses * 100, 2);
        // Put text where it makes sense
        if ($Percentage < 10) {
            $String .= '<span class="DP_Bar DP_Bar-' . $k . '" style="width: ' . $Percentage . '%;">&nbsp</span> ' . $Percentage . '%';
        } else {
            $String .= '<span class="DP_Bar DP_Bar-' . $k . '" style="width: ' . $Percentage . '%;">' . $Percentage . '%</span>';
        }
        echo Wrap($String, 'li', array('class' => 'DP_ResultOption'));
        $k = ++$k % 10;
    }
    echo '</ol>';
    echo '</li>';
}
コード例 #5
0
ファイル: answers.php プロジェクト: mcnasby/datto-vanilla
<?php

if (!defined('APPLICATION')) {
    exit;
}
?>
<div class="DataBox DataBox-AcceptedAnswers"><span id="latest"></span>
   <h2 class="CommentHeading"><?php 
echo Plural(count($Sender->Data('Answers')), 'Best Answer', 'Best Answers');
?>
</h2>
   <ul class="MessageList DataList AcceptedAnswers">
      <?php 
foreach ($Sender->Data('Answers') as $Row) {
    $Sender->EventArguments['Comment'] = $Row;
    WriteComment($Row, $Sender, Gdn::Session(), 0);
}
?>
   </ul>
</div>
コード例 #6
0
ファイル: flagging.php プロジェクト: Nordic-T/vanilla-plugins
        $TitleCell = TRUE;
        ksort($FlaggedList, SORT_STRING);
        $NumComplaintsInThread = sizeof($FlaggedList);
        foreach ($FlaggedList as $FlagIndex => $Flag) {
            if ($TitleCell) {
                $TitleCell = FALSE;
                ?>
                        <div class="FlaggedTitleCell">
                           <div class="FlaggedItemURL"><?php 
                echo Anchor(Url($Flag['ForeignURL'], TRUE), $Flag['ForeignURL']);
                ?>
</div>
                           <div class="FlaggedItemInfo">
                              <?php 
                if ($NumComplaintsInThread > 1) {
                    $OtherString = T(' and') . ' ' . ($NumComplaintsInThread - 1) . ' ' . T(Plural($NumComplaintsInThread - 1, 'other', 'others'));
                } else {
                    $OtherString = '';
                }
                ?>
                              <span><?php 
                echo T('FlaggedBy', "Reported by:");
                ?>
 </span>
                              <span><?php 
                printf(T('<strong>%s</strong>%s on %s'), Anchor($Flag['InsertName'], "profile/{$Flag['InsertUserID']}/{$Flag['InsertName']}"), $OtherString, $Flag['DateInserted']);
                ?>
</span>
                           </div>
                           <div class="FlaggedItemComment">"<?php 
                echo Gdn_Format::Text($Flag['Comment']);
コード例 #7
0
ファイル: applicants.php プロジェクト: rnovino/Garden
echo T('Manage Applicants');
?>
</h1>
<?php 
echo $this->Form->Open(array('action' => Url('/dashboard/user/applicants')));
echo $this->Form->Errors();
$NumApplicants = $this->UserData->NumRows();
if ($NumApplicants == 0) {
    ?>
      <div class="Info"><?php 
    echo T('There are currently no applicants.');
    ?>
</div>
   <?php 
} else {
    $AppText = Plural($NumApplicants, 'There is currently %s applicant', 'There are currently %s applicants');
    ?>
<div class="Info"><?php 
    echo sprintf($AppText, $NumApplicants);
    ?>
</div>
<table class="CheckColumn">
   <thead>
      <tr>
         <td><?php 
    echo T('Action');
    ?>
</td>
         <th class="Alt"><?php 
    echo T('Applicant');
    ?>
コード例 #8
0
ファイル: popin.php プロジェクト: rnovino/Garden
         <div class="Author Photo"><?php 
        echo UserPhoto($Row, array('Px' => 'First'));
        ?>
</div>
         <div class="ItemContent">
            <b class="Subject"><?php 
        echo Anchor($Row->Name, $Row->Url . '#latest');
        ?>
</b>
            <div class="Meta">
               <?php 
        echo ' <span class="MItem">' . Plural($Row->CountComments, '%s comment', '%s comments') . '</span> ';
        if ($Row->CountUnreadComments === TRUE) {
            echo ' <strong class="HasNew"> ' . T('new') . '</strong> ';
        } elseif ($Row->CountUnreadComments > 0) {
            echo ' <strong class="HasNew"> ' . Plural($Row->CountUnreadComments, '%s new', '%s new plural') . '</strong> ';
        }
        echo ' <span class="MItem">' . Gdn_Format::Date($Row->DateLastComment) . '</span> ';
        ?>
            </div>
         </div>
      </li>
      <?php 
    }
    ?>
      <li class="Item Center">
         <?php 
    echo Anchor(sprintf(T('All %s'), T('Bookmarks')), '/discussions/bookmarked');
    ?>
      </li>
<?php 
コード例 #9
0
ファイル: footer.php プロジェクト: RoadrunnerWMC/ABXD-plugins
<?php

$footerExtensionsB .= format(__("Page rendered in {0} seconds with {1}") . "<br>", sprintf('%1.3f', usectime() - $timeStart), Plural($queries, __("MySQL query")));
コード例 #10
0
<?php

if (!defined('APPLICATION')) {
    exit;
}
?>
<h1><?php 
echo $this->Data('Title');
?>
</h1>
<?php 
echo $this->Form->Open();
echo $this->Form->Errors();
$CountAllowed = GetValue('CountAllowed', $this->Data, 0);
$CountNotAllowed = GetValue('CountNotAllowed', $this->Data, 0);
$CountCheckedDiscussions = GetValue('CountCheckedDiscussions', $this->Data, 0);
if ($CountNotAllowed > 0) {
    echo Wrap(sprintf('You do not have permission to delete %1$s of the selected discussions.', $CountNotAllowed), 'p');
    echo Wrap(sprintf('You are about to delete %1$s of the %2$s selected discussions.', $CountAllowed, $CountCheckedDiscussions), 'p');
} else {
    echo Wrap(sprintf('You are about to delete %s.', Plural($CountAllowed, '%s discussion', '%s discussions')), 'p');
}
echo '<p><strong>' . T('Are you sure you wish to continue?') . '</strong></p>';
echo '<div class="Buttons Buttons-Confirm">', $this->Form->Button('OK', array('class' => 'Button Primary')), $this->Form->Button('Cancel', array('type' => 'button', 'class' => 'Button Close')), '</div>';
echo $this->Form->Close();
コード例 #11
0
 /**
  * @param array $FormPostValues
  * @param bool $Insert
  * @return bool
  */
 public function Validate($FormPostValues, $Insert = FALSE)
 {
     $valid = parent::Validate($FormPostValues, $Insert);
     if (!CheckPermission('Garden.Moderation.Manage') && C('Conversations.MaxRecipients')) {
         $max = C('Conversations.MaxRecipients');
         if (isset($FormPostValues['RecipientUserID']) && count($FormPostValues['RecipientUserID']) > $max) {
             $this->Validation->AddValidationResult('To', Plural($max, "You are limited to %s recipient.", "You are limited to %s recipients."));
             $valid = false;
         }
     }
     return $valid;
 }
コード例 #12
0
<?php if (!defined('APPLICATION')) exit(); ?>
<h1><?php echo $this->Data('Title'); ?></h1>
<?php
echo $this->Form->Open();
echo $this->Form->Errors();

$CountCheckedComments = GetValue('CountCheckedComments', $this->Data, 0);

echo Wrap(sprintf(
   'You have chosen to split %s into a new discussion.',
   Plural($CountCheckedComments, '%s comment', '%s comments')
   ), 'p');
?>
<ul>
   <li>
      <?php
         echo $this->Form->Label('New Discussion Topic', 'Name');
         echo $this->Form->TextBox('Name');
      ?>
   </li>
   <?php if ($this->ShowCategorySelector === TRUE) { ?>
   <li>
      <?php
         echo '<p><div class="Category">';
         echo $this->Form->Label('Category', 'CategoryID'), ' ';
         echo $this->Form->DropDown('CategoryID', $this->CategoryData, array('TextField' => 'Name', 'ValueField' => 'CategoryID'));
         echo '</div></p>';
      ?>
   </li>
   <?php } ?>
</ul>
コード例 #13
0
   <div class="Photo"><?php echo UserPhoto($PhotoUser); ?></div>
   <?php } ?>
   <div class="ItemContent Conversation">
      <?php
      $Url = '/messages/'.$Conversation->ConversationID.'/#Item_'.$JumpToItem;

      if ($Names) {
         echo '<h3 class="Users">', Anchor(htmlspecialchars($Names), $Url), '</h3>';
      }
      if ($SubjectsVisible && $Subject = GetValue('Subject', $Conversation)) {
         echo '<div class="Subject"><b>'.Anchor(htmlspecialchars($Subject), $Url).'</b></div>';
      }
      ?>
      <div class="Excerpt"><?php echo Anchor($Message, $Url, 'Message'); ?></div>
      <div class="Meta">
         <?php 
         $this->FireEvent('BeforeConversationMeta');

         echo '<span class="MetaItem">'.sprintf(Plural($Conversation->CountMessages, '%s message', '%s messages'), $Conversation->CountMessages).'</span>';

         if ($Conversation->CountNewMessages > 0) {
            echo '<strong class="MetaItem">'.Plural($Conversation->CountNewMessages, '%s new', '%s new').'</strong>';
         }
         
         echo '<span class="MetaItem">'.Gdn_Format::Date($Conversation->DateLastMessage).'</span>';
         ?>
      </div>
   </div>
</li>
<?php
}
コード例 #14
0
ファイル: helper_functions.php プロジェクト: Raz0r/Garden
function WriteDiscussion($Discussion, &$Sender, &$Session, $Alt2)
{
    static $Alt = FALSE;
    $CssClass = 'Item';
    $CssClass .= $Discussion->Bookmarked == '1' ? ' Bookmarked' : '';
    $CssClass .= $Alt ? ' Alt ' : '';
    $Alt = !$Alt;
    $CssClass .= $Discussion->Announce == '1' ? ' Announcement' : '';
    $CssClass .= $Discussion->Dismissed == '1' ? ' Dismissed' : '';
    $CssClass .= $Discussion->InsertUserID == $Session->UserID ? ' Mine' : '';
    $CssClass .= $Discussion->CountUnreadComments > 0 && $Session->IsValid() ? ' New' : '';
    $DiscussionUrl = '/discussion/' . $Discussion->DiscussionID . '/' . Gdn_Format::Url($Discussion->Name) . ($Discussion->CountCommentWatch > 0 && C('Vanilla.Comments.AutoOffset') && $Session->UserID > 0 ? '/#Item_' . $Discussion->CountCommentWatch : '');
    //   $DiscussionUrl = $Discussion->Url;
    $Sender->EventArguments['DiscussionUrl'] =& $DiscussionUrl;
    $Sender->EventArguments['Discussion'] =& $Discussion;
    $Sender->EventArguments['CssClass'] =& $CssClass;
    $First = UserBuilder($Discussion, 'First');
    $Last = UserBuilder($Discussion, 'Last');
    $Sender->FireEvent('BeforeDiscussionName');
    $DiscussionName = $Discussion->Name;
    if ($DiscussionName == '') {
        $DiscussionName = T('Blank Discussion Topic');
    }
    $Sender->EventArguments['DiscussionName'] =& $DiscussionName;
    static $FirstDiscussion = TRUE;
    if (!$FirstDiscussion) {
        $Sender->FireEvent('BetweenDiscussion');
    } else {
        $FirstDiscussion = FALSE;
    }
    ?>
<li class="<?php 
    echo $CssClass;
    ?>
">
   <?php 
    if (!property_exists($Sender, 'CanEditDiscussions')) {
        $Sender->CanEditDiscussions = GetValue('PermsDiscussionsEdit', CategoryModel::Categories($Discussion->CategoryID)) && C('Vanilla.AdminCheckboxes.Use');
    }
    $Sender->FireEvent('BeforeDiscussionContent');
    WriteOptions($Discussion, $Sender, $Session);
    ?>
   <div class="ItemContent Discussion">
      <?php 
    echo Anchor($DiscussionName, $DiscussionUrl, 'Title');
    ?>
      <?php 
    $Sender->FireEvent('AfterDiscussionTitle');
    ?>
      <div class="Meta">
         <?php 
    $Sender->FireEvent('BeforeDiscussionMeta');
    ?>
         <?php 
    if ($Discussion->Announce == '1') {
        ?>
         <span class="Tag Announcement"><?php 
        echo T('Announcement');
        ?>
</span>
         <?php 
    }
    ?>
         <?php 
    if ($Discussion->Closed == '1') {
        ?>
         <span class="Tag Closed"><?php 
        echo T('Closed');
        ?>
</span>
         <?php 
    }
    ?>
         <span class="MItem CommentCount"><?php 
    printf(Plural($Discussion->CountComments, '%s comment', '%s comments'), $Discussion->CountComments);
    if ($Session->IsValid() && $Discussion->CountUnreadComments > 0) {
        echo ' <strong class="HasNew">' . Plural($Discussion->CountUnreadComments, '%s new', '%s new plural') . '</strong>';
    }
    ?>
</span>
         <?php 
    $Sender->FireEvent('AfterCountMeta');
    if ($Discussion->LastCommentID != '') {
        echo ' <span class="MItem LastCommentBy">' . sprintf(T('Most recent by %1$s'), UserAnchor($Last)) . '</span> ';
        echo ' <span class="MItem LastCommentDate">' . Gdn_Format::Date($Discussion->LastDate) . '</span>';
    } else {
        echo ' <span class="MItem LastCommentBy">' . sprintf(T('Started by %1$s'), UserAnchor($First)) . '</span> ';
        echo ' <span class="MItem LastCommentDate">' . Gdn_Format::Date($Discussion->FirstDate);
        if ($Source = GetValue('Source', $Discussion)) {
            echo ' ' . sprintf(T('via %s'), T($Source . ' Source', $Source));
        }
        echo '</span> ';
    }
    if (C('Vanilla.Categories.Use') && $Discussion->CategoryUrlCode != '') {
        echo ' ' . Wrap(Anchor($Discussion->Category, '/categories/' . rawurlencode($Discussion->CategoryUrlCode)), 'span', array('class' => 'Tag Category'));
    }
    $Sender->FireEvent('DiscussionMeta');
    ?>
      </div>
   </div>
</li>
<?php 
}
コード例 #15
0
ファイル: conversations.php プロジェクト: robi-bobi/Garden
    $Name = $Session->UserID == $Conversation->LastMessageUserID ? 'You' : $Conversation->LastMessageName;
    $JumpToItem = $Conversation->CountMessages - $Conversation->CountNewMessages;
    ?>
<li<?php 
    echo $Class == '' ? '' : ' class="' . $Class . '"';
    ?>
>
   <?php 
    $LastAuthor = UserBuilder($Conversation, 'LastMessage');
    echo UserPhoto($LastAuthor, 'Photo');
    ?>
   <div>
      <?php 
    echo UserAnchor($LastAuthor, 'Name');
    echo Anchor(SliceString(Format::Text($Conversation->LastMessage), 100), '/messages/' . $Conversation->ConversationID . '/#Item_' . $JumpToItem, 'Message');
    echo '<div class="Meta">';
    echo Format::Date($Conversation->DateLastMessage);
    echo '<span>&bull;</span>';
    printf(Gdn::Translate(Plural($Conversation->CountMessages, '%s message', '%s messages')), $Conversation->CountMessages);
    if ($Conversation->CountNewMessages > 0) {
        echo '<span>&bull;</span>';
        echo '<em>';
        printf(Gdn::Translate('%s new'), $Conversation->CountNewMessages);
        echo '</em>';
    }
    echo '</div>';
    ?>
   </div>
</li>
<?php 
}
コード例 #16
0
ファイル: default.php プロジェクト: SatiricMan/addons
 public function PostController_Reply_Create($Sender, $EventArguments = '')
 {
     $Sender->View = $this->GetView('vanilla_post_reply.php');
     $ReplyCommentID = 0;
     if (is_array($EventArguments) && array_key_exists(0, $EventArguments)) {
         $ReplyCommentID = is_numeric($EventArguments[0]) ? $EventArguments[0] : 0;
     }
     $ReplyModel = Gdn::Factory('ReplyModel');
     $Sender->ReplyCommentID = $ReplyCommentID;
     // Set the model on the form.
     $Sender->Form->SetModel($ReplyModel);
     // Make sure the form knows which comment we're replying to
     $Sender->Form->AddHidden('ReplyCommentID', $ReplyCommentID);
     $Sender->ReplyComment = $Sender->CommentModel->GetID($ReplyCommentID);
     $Discussion = $Sender->DiscussionModel->GetID($Sender->ReplyComment->DiscussionID);
     $Sender->Permission('Vanilla.Comments.Add', $Discussion->CategoryID);
     if ($Sender->Form->AuthenticatedPostBack()) {
         $CommentID = $Sender->Form->Save();
         if ($Sender->Form->ErrorCount() == 0) {
             // Redirect if this is not an ajax request
             if ($Sender->DeliveryType() == DELIVERY_TYPE_ALL) {
                 $Discussion = $ReplyModel->GetDiscussion($CommentID);
                 Redirect('/vanilla/discussion/' . $Discussion->DiscussionID . '/' . Gdn_Format::Url($Discussion->Name) . '#Comment_' . $CommentID);
             }
             // Load all new replies that the user hasn't seen yet
             $LastCommentID = $Sender->Form->GetFormValue('LastCommentID');
             if (!is_numeric($LastCommentID)) {
                 $LastCommentID = $CommentID - 1;
             }
             $Sender->ReplyData = $ReplyModel->GetNew($ReplyCommentID, $LastCommentID);
             $Sender->CurrentReply = is_object($Sender->ReplyData) ? $Sender->ReplyData->NextRow() : FALSE;
             $Replies = $Sender->ReplyComment->CountReplies + 1;
             $Sender->SetJson('Replies', sprintf(T(Plural($Replies, '%s Reply', '%s Replies')), $Replies));
             $Sender->SetJson('CommentID', $CommentID);
             $Sender->Discussion = $Sender->DiscussionModel->GetID($Sender->ReplyComment->DiscussionID);
             $Sender->ControllerName = 'discussion';
             $Sender->View = $this->GetView('replies.php');
         } else {
             if ($Sender->DeliveryType() !== DELIVERY_TYPE_ALL) {
                 // Handle ajax-based errors
                 $Sender->StatusMessage = $Sender->Form->Errors();
             }
         }
     }
     $Sender->Render();
 }
コード例 #17
0
 /**
  * Add or subtract a value from a comment's score.
  * @param DiscussionController $Sender The controller that is implementing this method.
  * @param array $Args The arguments for the operation.
  */
 public function DiscussionController_Score_Create($Sender, $Args)
 {
     $CommentID = $Args[0];
     $ScoreKey = substr($Args[1], 0, 3) == 'Neg' ? -1 : 1;
     //$TransientKey = $Args[2];
     $SQL = Gdn::SQL();
     $Session = Gdn::Session();
     // Get the current score for this user.
     $Data = $SQL->Select('uc.Score')->From('UserComment uc')->Where('uc.CommentID', $CommentID)->Where('uc.UserID', $Session->UserID)->Get()->FirstRow();
     $UserScore = $Data ? $Data->Score : 0;
     // Get the score increments.
     $Inc = $this->GetScoreIncrements($CommentID, $UserScore);
     $Score = $Inc[$ScoreKey];
     $UserScore += $Score;
     if ($Score != 0) {
         if ($Data) {
             // Update the score on an existing comment.
             $SQL->Update('UserComment')->Set('Score', $UserScore)->Set('DateUpdated', Format::ToDateTime())->Set('UpdateUserID', $Session->UserID)->Where('UserID', $Session->UserID)->Where('CommentID', $CommentID)->Put();
         } else {
             // Insert a new score.
             $SQL->Insert('UserComment', array('CommentID' => $CommentID, 'UserID' => $Session->UserID, 'Score' => $UserScore, 'DateInserted' => Format::ToDateTime(), 'InsertUserID' => $Session->UserID, 'DateUpdated' => Format::ToDateTime(), 'UpdateUserID' => $Session->UserID));
         }
         // Update the comment table with the sum of the scores.
         $Data = $SQL->Select('uc.Score', 'sum', 'SumScore')->From('UserComment uc')->Where('uc.CommentID', $CommentID)->Get()->FirstRow();
         $SumScore = $Data ? $Data->SumScore : 0;
         $SQL->Update('Comment')->Set('SumScore', $SumScore)->Where('CommentID', $CommentID)->Put();
         $Inc = $this->GetScoreIncrements($CommentID, $UserScore);
     }
     // Redirect back where the user came from if necessary
     if ($Sender->DeliveryType() != DELIVERY_TYPE_BOOL) {
         $Target = GetIncomingValue('Target', '/vanilla/discussions/scored');
         Redirect($Target);
     }
     // Send the current information back to be dealt with on the client side.
     $Sender->SetJson('SumScore', isset($SumScore) ? sprintf(Plural($SumScore, '%s point', '%s points'), $SumScore) : NULL);
     $Sender->SetJson('Inc', $Inc);
     $Sender->Render();
     break;
 }
コード例 #18
0
 /**
  * Enabling and disabling categories from list.
  * 
  * @since 2.0.0
  * @access public
  */
 public function ManageCategories()
 {
     // Check permission
     $this->Permission('Vanilla.Categories.Manage');
     // Set up head
     $this->AddSideMenu('vanilla/settings/managecategories');
     $this->AddJsFile('categories.js');
     //       $this->AddJsFile('jquery.ui.packed.js');
     $this->AddJsFile('js/library/jquery.alphanumeric.js');
     $this->AddJsFile('js/library/nestedSortable.1.2.1/jquery-ui-1.8.2.custom.min.js');
     $this->AddJsFile('js/library/nestedSortable.1.2.1/jquery.ui.nestedSortable.js');
     $this->Title(T('Categories'));
     // Get category data
     $this->SetData('CategoryData', $this->CategoryModel->GetAll('TreeLeft'), TRUE);
     // Enable/Disable Categories
     if (Gdn::Session()->ValidateTransientKey(GetValue(1, $this->RequestArgs))) {
         $Toggle = GetValue(0, $this->RequestArgs, '');
         if ($Toggle == 'enable') {
             SaveToConfig('Vanilla.Categories.Use', TRUE);
         } else {
             if ($Toggle == 'disable') {
                 SaveToConfig('Vanilla.Categories.Use', FALSE);
             }
         }
         Redirect('vanilla/settings/managecategories');
     }
     // Setup & save forms
     $Validation = new Gdn_Validation();
     $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
     $ConfigurationModel->SetField(array('Vanilla.Categories.MaxDisplayDepth', 'Vanilla.Categories.DoHeadings', 'Vanilla.Categories.HideModule'));
     // Set the model on the form.
     $this->Form->SetModel($ConfigurationModel);
     // Define MaxDepthOptions
     $DepthData = array();
     $DepthData['2'] = sprintf(T('more than %s deep'), Plural(1, '%s level', '%s levels'));
     $DepthData['3'] = sprintf(T('more than %s deep'), Plural(2, '%s level', '%s levels'));
     $DepthData['4'] = sprintf(T('more than %s deep'), Plural(3, '%s level', '%s levels'));
     $DepthData['0'] = T('never');
     $this->SetData('MaxDepthData', $DepthData);
     // If seeing the form for the first time...
     if ($this->Form->AuthenticatedPostBack() === FALSE) {
         // Apply the config settings to the form.
         $this->Form->SetData($ConfigurationModel->Data);
     } else {
         if ($this->Form->Save() !== FALSE) {
             $this->InformMessage(T("Your settings have been saved."));
         }
     }
     // Render default view
     $this->Render();
 }
コード例 #19
0
ファイル: helper_functions.php プロジェクト: jhampha/Garden
function WriteDiscussion($Discussion, &$Sender, &$Session, $Alt)
{
    $CssClass = 'DiscussionRow';
    $CssClass .= $Discussion->Bookmarked == '1' ? ' Bookmarked' : '';
    $CssClass .= $Alt . ' ';
    $CssClass .= $Discussion->Announce == '1' ? ' Announcement' : '';
    $CssClass .= $Discussion->InsertUserID == $Session->UserID ? ' Mine' : '';
    $CountUnreadComments = $Discussion->CountComments - $Discussion->CountCommentWatch;
    $CssClass .= $CountUnreadComments > 0 && $Session->IsValid() ? ' New' : '';
    ?>
<li class="<?php 
    echo $CssClass;
    ?>
">
   <ul class="Discussion">
      <?php 
    if ($Sender->ShowOptions) {
        ?>
      <li class="Options">
         <?php 
        // Build up the options that the user has for each discussion
        if ($Session->IsValid()) {
            // Bookmark link
            echo Anchor('<span>*</span>', '/vanilla/discussion/bookmark/' . $Discussion->DiscussionID . '/' . $Session->TransientKey() . '?Target=' . urlencode($Sender->SelfUrl), 'Bookmark' . ($Discussion->Bookmarked == '1' ? ' Bookmarked' : ''), array('title' => Gdn::Translate($Discussion->Bookmarked == '1' ? 'Unbookmark' : 'Bookmark')));
            $Sender->Options = '';
            // Dismiss an announcement
            if ($Discussion->Announce == '1' && $Discussion->Dismissed != '1') {
                $Sender->Options .= '<li>' . Anchor('Dismiss', 'vanilla/discussion/dismissannouncement/' . $Discussion->DiscussionID . '/' . $Session->TransientKey(), 'DismissAnnouncement') . '</li>';
            }
            // Edit discussion
            if ($Discussion->FirstUserID == $Session->UserID || $Session->CheckPermission('Vanilla.Discussions.Edit', $Discussion->CategoryID)) {
                $Sender->Options .= '<li>' . Anchor('Edit', 'vanilla/post/editdiscussion/' . $Discussion->DiscussionID, 'EditDiscussion') . '</li>';
            }
            // Announce discussion
            if ($Session->CheckPermission('Vanilla.Discussions.Announce', $Discussion->CategoryID)) {
                $Sender->Options .= '<li>' . Anchor($Discussion->Announce == '1' ? 'Unannounce' : 'Announce', 'vanilla/discussion/announce/' . $Discussion->DiscussionID . '/' . $Session->TransientKey(), 'AnnounceDiscussion') . '</li>';
            }
            // Sink discussion
            if ($Session->CheckPermission('Vanilla.Discussions.Sink', $Discussion->CategoryID)) {
                $Sender->Options .= '<li>' . Anchor($Discussion->Sink == '1' ? 'Unsink' : 'Sink', 'vanilla/discussion/sink/' . $Discussion->DiscussionID . '/' . $Session->TransientKey() . '?Target=' . urlencode($Sender->SelfUrl), 'SinkDiscussion') . '</li>';
            }
            // Close discussion
            if ($Session->CheckPermission('Vanilla.Discussions.Close', $Discussion->CategoryID)) {
                $Sender->Options .= '<li>' . Anchor($Discussion->Closed == '1' ? 'Reopen' : 'Close', 'vanilla/discussion/close/' . $Discussion->DiscussionID . '/' . $Session->TransientKey() . '?Target=' . urlencode($Sender->SelfUrl), 'CloseDiscussion') . '</li>';
            }
            // Delete discussion
            if ($Session->CheckPermission('Vanilla.Discussions.Delete', $Discussion->CategoryID)) {
                $Sender->Options .= '<li>' . Anchor('Delete', 'vanilla/discussion/delete/' . $Discussion->DiscussionID . '/' . $Session->TransientKey() . '?Target=' . urlencode($Sender->SelfUrl), 'DeleteDiscussion') . '</li>';
            }
            // Allow plugins to add options
            $Sender->FireEvent('DiscussionOptions');
            if ($Sender->Options != '') {
                ?>
               <ul class="Options">
                  <li><strong><?php 
                echo Gdn::Translate('Options');
                ?>
</strong>
                     <ul>
                        <?php 
                echo $Sender->Options;
                ?>
                     </ul>
                  </li>
               </ul>
               <?php 
            }
        }
        ?>
      </li>
      <?php 
    }
    ?>
      <li class="Title">
         <strong><?php 
    echo Anchor(Format::Text($Discussion->Name), '/discussion/' . $Discussion->DiscussionID . '/' . Format::Url($Discussion->Name) . ($Discussion->CountCommentWatch > 0 ? '/#Item_' . $Discussion->CountCommentWatch : ''), 'DiscussionLink');
    ?>
</strong>
      </li>
      <li class="Meta">
         <?php 
    echo '<span>';
    echo sprintf(Plural($Discussion->CountComments, '%s comment', '%s comments'), $Discussion->CountComments);
    echo '</span>';
    if ($CountUnreadComments > 0 && $Session->IsValid()) {
        echo '<strong>', sprintf(Gdn::Translate('%s new'), $CountUnreadComments), '</strong>';
    }
    echo '<span>';
    printf(Gdn::Translate('Most recent by %1$s %2$s'), UserAnchor($Discussion->LastName), Format::Date($Discussion->LastDate));
    echo '</span>';
    echo Anchor($Discussion->Category, '/categories/' . urlencode($Discussion->Category), 'Category');
    $Sender->FireEvent('DiscussionMeta');
    ?>
      </li>
   </ul>
</li>
<?php 
}
コード例 #20
0
ファイル: post.php プロジェクト: Servault/Blargboard
function makePostText($post, $poster)
{
    $noSmilies = $post['options'] & 2;
    //Do Ampersand Tags
    $tags = array("postnum" => $post['num'], "postcount" => $poster['posts'], "numdays" => floor((time() - $poster['regdate']) / 86400), "date" => formatdate($post['date']), "rank" => GetRank($poster['rankset'], $poster['posts']));
    $bucket = "amperTags";
    include __DIR__ . "/pluginloader.php";
    if ($poster['signature']) {
        if (!$poster['signsep']) {
            $separator = "<br>_________________________<br>";
        } else {
            $separator = "<br>";
        }
    }
    $attachblock = '';
    if ($post['has_attachments']) {
        if (isset($post['preview_attachs'])) {
            $ispreview = true;
            $fileids = array_keys($post['preview_attachs']);
            $attachs = Query("SELECT id,filename,physicalname,description,downloads \n\t\t\t\tFROM {uploadedfiles}\n\t\t\t\tWHERE id IN ({0c})", $fileids);
        } else {
            $ispreview = false;
            $attachs = Query("SELECT id,filename,physicalname,description,downloads \n\t\t\t\tFROM {uploadedfiles}\n\t\t\t\tWHERE parenttype={0} AND parentid={1} AND deldate=0\n\t\t\t\tORDER BY filename", 'post_attachment', $post['id']);
        }
        while ($attach = Fetch($attachs)) {
            $url = URL_ROOT . 'get.php?id=' . htmlspecialchars($attach['id']);
            $linkurl = $ispreview ? '#' : $url;
            $filesize = filesize(DATA_DIR . 'uploads/' . $attach['physicalname']);
            $attachblock .= '<br><div class="post_attachment">';
            $fext = strtolower(substr($attach['filename'], -4));
            if ($fext == '.png' || $fext == '.jpg' || $fext == 'jpeg' || $fext == '.gif') {
                $alt = htmlspecialchars($attach['filename']) . ' &mdash; ' . BytesToSize($filesize) . ', viewed ' . Plural($attach['downloads'], 'time');
                $attachblock .= '<a href="' . $linkurl . '"><img src="' . $url . '" alt="' . $alt . '" title="' . $alt . '" style="max-width:300px; max-height:300px;"></a>';
            } else {
                $link = '<a href="' . $linkurl . '">' . htmlspecialchars($attach['filename']) . '</a>';
                $desc = htmlspecialchars($attach['description']);
                if ($desc) {
                    $desc .= '<br>';
                }
                $attachblock .= '<strong>' . __('Attachment: ') . $link . '</strong><br>';
                $attachblock .= '<div class="smallFonts">' . $desc;
                $attachblock .= BytesToSize($filesize) . __(' &mdash; Downloaded ') . Plural($attach['downloads'], 'time') . '</div>';
            }
            $attachblock .= '</div>';
        }
    }
    $postText = $poster['postheader'] . $post['text'] . $attachblock . $separator . $poster['signature'];
    $postText = ApplyTags($postText, $tags);
    $postText = CleanUpPost($postText, $noSmilies, false);
    return $postText;
}
コード例 #21
0
ファイル: popin.php プロジェクト: rnovino/Garden
        ?>
</div>
      <div class="ItemContent">
         <b class="Subject"><?php 
        echo Anchor($Subject, "/messages/{$Row['ConversationID']}#latest");
        ?>
</b>
         <?php 
        $Excerpt = SliceString(Gdn_Format::PlainText($Row['LastBody'], $Row['LastFormat']), 80);
        echo Wrap(nl2br($Excerpt), 'div', array('class' => 'Excerpt'));
        ?>
         <div class="Meta">
            <?php 
        echo ' <span class="MItem">' . Plural($Row['CountMessages'], '%s message', '%s messages') . '</span> ';
        if ($Row['CountNewMessages'] > 0) {
            echo ' <strong class="HasNew"> ' . Plural($Row['CountNewMessages'], '%s new', '%s new') . '</strong> ';
        }
        echo ' <span class="MItem">' . Gdn_Format::Date($Row['LastDateInserted']) . '</span> ';
        ?>
         </div>
      </div>
   </li>
   <?php 
    }
    ?>
   <li class="Item Center">
      <?php 
    echo Anchor(sprintf(T('All %s'), T('Messages')), '/messages/inbox');
    ?>
   </li>
<?php 
コード例 #22
0
ファイル: board.php プロジェクト: knytrune/ABXD
<?php

if ($loguserid && isset($_GET['action']) && $_GET['action'] == "markallread") {
    Query("REPLACE INTO {threadsread} (id,thread,date) SELECT {0}, {threads}.id, {1} FROM {threads}", $loguserid, time());
    redirectAction("board");
}
$links = new PipeMenu();
if ($loguserid) {
    $links->add(new PipeMenuLinkEntry(__("Mark all forums read"), "board", 0, "action=markallread", "ok"));
}
makeLinks($links);
makeBreadcrumbs(new PipeMenu());
if (!$mobileLayout) {
    $statData = Fetch(Query("SELECT\n\t\t(SELECT COUNT(*) FROM {threads}) AS numThreads,\n\t\t(SELECT COUNT(*) FROM {posts}) AS numPosts,\n\t\t(SELECT COUNT(*) FROM {users}) AS numUsers,\n\t\t(select count(*) from {posts} where date > {0}) AS newToday,\n\t\t(select count(*) from {posts} where date > {1}) AS newLastHour,\n\t\t(select count(*) from {users} where lastposttime > {2}) AS numActive", time() - 86400, time() - 3600, time() - 2592000));
    $stats = Format(__("{0} and {1} total"), Plural($statData["numThreads"], __("thread")), Plural($statData["numPosts"], __("post")));
    $stats .= "<br />" . format(__("{0} today, {1} last hour"), Plural($statData["newToday"], __("new post")), $statData["newLastHour"]);
    $percent = $statData["numUsers"] ? ceil(100 / $statData["numUsers"] * $statData["numActive"]) : 0;
    $lastUser = Query("select u.(_userfields) from {users} u order by u.regdate desc limit 1");
    if (numRows($lastUser)) {
        $lastUser = getDataPrefix(Fetch($lastUser), "u_");
        $last = format(__("{0}, {1} active ({2}%)"), Plural($statData["numUsers"], __("registered user")), $statData["numActive"], $percent) . "<br />" . format(__("Newest: {0}"), UserLink($lastUser));
    } else {
        $last = __("No registered users") . "<br />&nbsp;";
    }
    write("\n\t\t<table class=\"outline margin width100\" style=\"overflow: auto;\">\n\t\t\t<tr class=\"cell2 center\" style=\"overflow: auto;\">\n\t\t\t<td>\n\t\t\t\t<div style=\"float: left; width: 25%;\">&nbsp;<br />&nbsp;</div>\n\t\t\t\t<div style=\"float: right; width: 25%;\">{1}</div>\n\t\t\t\t<div class=\"center\">\n\t\t\t\t\t{0}\n\t\t\t\t</div>\n\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t", $stats, $last);
}
printRefreshCode();
makeForumListing(0);
コード例 #23
0
ファイル: functions.general.php プロジェクト: sitexa/vanilla
 /**
  * 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;
 }
コード例 #24
0
ファイル: class.format.php プロジェクト: seedbank/old-repo
 /**
  * Formats seconds in a human-readable way (ie. 45 seconds, 15 minutes, 2 hours, 4 days, 2 months, etc).
  */
 public static function Seconds($Seconds)
 {
     if (!is_numeric($Seconds)) {
         $Seconds = abs(time() - self::ToTimestamp($Seconds));
     }
     $Minutes = round($Seconds / 60);
     $Hours = round($Seconds / 3600);
     $Days = round($Seconds / 86400);
     $Weeks = round($Seconds / 604800);
     $Months = round($Seconds / 2629743.83);
     $Years = round($Seconds / 31556926);
     if ($Seconds < 60) {
         return sprintf(Plural($Seconds, '%s second', '%s seconds'), $Seconds);
     } elseif ($Minutes < 60) {
         return sprintf(Plural($Minutes, '%s minute', '%s minutes'), $Minutes);
     } elseif ($Hours < 24) {
         return sprintf(Plural($Hours, '%s hour', '%s hours'), $Hours);
     } elseif ($Days < 7) {
         return sprintf(Plural($Days, '%s day', '%s days'), $Days);
     } elseif ($Weeks < 4) {
         return sprintf(Plural($Weeks, '%s week', '%s weeks'), $Weeks);
     } elseif ($Months < 12) {
         return sprintf(Plural($Months, '%s month', '%s months'), $Months);
     } else {
         return sprintf(Plural($Years, '%s year', '%s years'), $Years);
     }
 }
コード例 #25
0
ファイル: class.usermodel.php プロジェクト: TiGR/Garden
 public function SaveRoles($UserID, $RoleIDs, $RecordActivity = TRUE)
 {
     if (is_string($RoleIDs) && !is_numeric($RoleIDs)) {
         // The $RoleIDs are a comma delimited list of role names.
         $RoleNames = preg_split('/\\s*,\\s*/', $RoleIDs);
         $RoleIDs = $this->SQL->Select('r.RoleID')->From('Role r')->WhereIn('r.Name', $RoleNames)->Get()->ResultArray();
         $RoleIDs = ConsolidateArrayValuesByKey($RoleIDs, 'RoleID');
     }
     if (!is_array($RoleIDs)) {
         $RoleIDs = array($RoleIDs);
     }
     // Get the current roles.
     $OldRoleIDs = array();
     $OldRoleData = $this->SQL->Select('ur.RoleID, r.Name')->From('Role r')->Join('UserRole ur', 'r.RoleID = ur.RoleID')->Where('ur.UserID', $UserID)->Get()->ResultArray();
     if ($OldRoleData !== FALSE) {
         $OldRoleIDs = ConsolidateArrayValuesByKey($OldRoleData, 'RoleID');
     }
     // 1a) Figure out which roles to delete.
     $DeleteRoleIDs = array_diff($OldRoleIDs, $RoleIDs);
     // 1b) Remove old role associations for this user.
     if (count($DeleteRoleIDs) > 0) {
         $this->SQL->WhereIn('RoleID', $DeleteRoleIDs)->Delete('UserRole', array('UserID' => $UserID));
     }
     // 2a) Figure out which roles to insert.
     $InsertRoleIDs = array_diff($RoleIDs, $OldRoleIDs);
     // 2b) Insert the new role associations for this user.
     foreach ($InsertRoleIDs as $InsertRoleID) {
         if (is_numeric($InsertRoleID)) {
             $this->SQL->Insert('UserRole', array('UserID' => $UserID, 'RoleID' => $InsertRoleID));
         }
     }
     // 3. Remove the cached permissions for this user.
     // Note: they are not reset here because I want this action to be
     // performed in one place - /dashboard/library/core/class.session.php
     // It is done in the session because when a role's permissions are changed
     // I can then just erase all cached permissions on the user table for
     // users that are assigned to that changed role - and they can reset
     // themselves the next time the session is referenced.
     $this->SQL->Put('User', array('Permissions' => ''), array('UserID' => $UserID));
     if ($RecordActivity && (count($DeleteRoleIDs) > 0 || count($InsertRoleIDs) > 0)) {
         $User = $this->Get($UserID);
         $Session = Gdn::Session();
         $OldRoles = FALSE;
         if ($OldRoleData !== FALSE) {
             $OldRoles = ConsolidateArrayValuesByKey($OldRoleData, 'Name');
         }
         $NewRoles = FALSE;
         $NewRoleData = $this->SQL->Select('r.RoleID, r.Name')->From('Role r')->Join('UserRole ur', 'r.RoleID = ur.RoleID')->Where('ur.UserID', $UserID)->Get()->ResultArray();
         if ($NewRoleData !== FALSE) {
             $NewRoles = ConsolidateArrayValuesByKey($NewRoleData, 'Name');
         }
         $RemovedRoles = array_diff($OldRoles, $NewRoles);
         $NewRoles = array_diff($NewRoles, $OldRoles);
         $RemovedCount = count($RemovedRoles);
         $NewCount = count($NewRoles);
         $Story = '';
         if ($RemovedCount > 0 && $NewCount > 0) {
             $Story = sprintf(T('%1$s was removed from the %2$s %3$s and added to the %4$s %5$s.'), $User->Name, implode(', ', $RemovedRoles), Plural($RemovedCount, 'role', 'roles'), implode(', ', $NewRoles), Plural($NewCount, 'role', 'roles'));
         } else {
             if ($RemovedCount > 0) {
                 $Story = sprintf(T('%1$s was removed from the %2$s %3$s.'), $User->Name, implode(', ', $RemovedRoles), Plural($RemovedCount, 'role', 'roles'));
             } else {
                 if ($NewCount > 0) {
                     $Story = sprintf(T('%1$s was added to the %2$s %3$s.'), $User->Name, implode(', ', $NewRoles), Plural($NewCount, 'role', 'roles'));
                 }
             }
         }
         AddActivity($Session->UserID != 0 ? $Session->UserID : $UserID, 'RoleChange', $Story, $UserID);
     }
 }
コード例 #26
0
ファイル: inbox.php プロジェクト: bishopb/vanilla
      foreach ($Row['Participants'] as $User) {
          if ($First) {
              $First = FALSE;
          } else {
              echo ', ';
          }
          if ($User['UserID'] == Gdn::Session()->UserID) {
              $User['Name'] = T('You');
          }
          echo UserAnchor($User);
      }
      ?>
          </span>
          <span class="MItem CountMessages">
             <?php 
      echo Plural($Row['CountMessages'], '%s message', '%s messages');
      ?>
          </span>
          <span class="MItem DateLastMessage">
             <?php 
      echo Gdn_Format::Date($Row['DateLastMessage']);
      ?>
          </span>
       </div>
    </li>
    <?php 
  }
  ?>
 </ul>   
 <div class="P PagerContainer">
    <?php 
コード例 #27
0
function _FormatStringCallback($Match, $SetArgs = FALSE)
{
    static $Args = array();
    if ($SetArgs) {
        $Args = $Match;
        return;
    }
    $Match = $Match[1];
    if ($Match == '{') {
        return $Match;
    }
    // Parse out the field and format.
    $Parts = explode(',', $Match);
    $Field = trim($Parts[0]);
    $Format = trim(GetValue(1, $Parts, ''));
    $SubFormat = strtolower(trim(GetValue(2, $Parts, '')));
    $FormatArgs = GetValue(3, $Parts, '');
    if (in_array($Format, array('currency', 'integer', 'percent'))) {
        $FormatArgs = $SubFormat;
        $SubFormat = $Format;
        $Format = 'number';
    } elseif (is_numeric($SubFormat)) {
        $FormatArgs = $SubFormat;
        $SubFormat = '';
    }
    $Value = GetValueR($Field, $Args, '');
    if ($Value == '' && !in_array($Format, array('url', 'exurl'))) {
        $Result = '';
    } else {
        switch (strtolower($Format)) {
            case 'date':
                switch ($SubFormat) {
                    case 'short':
                        $Result = Gdn_Format::Date($Value, '%d/%m/%Y');
                        break;
                    case 'medium':
                        $Result = Gdn_Format::Date($Value, '%e %b %Y');
                        break;
                    case 'long':
                        $Result = Gdn_Format::Date($Value, '%e %B %Y');
                        break;
                    default:
                        $Result = Gdn_Format::Date($Value);
                        break;
                }
                break;
            case 'html':
            case 'htmlspecialchars':
                $Result = htmlspecialchars($Value);
                break;
            case 'number':
                if (!is_numeric($Value)) {
                    $Result = $Value;
                } else {
                    switch ($SubFormat) {
                        case 'currency':
                            $Result = '$' . number_format($Value, is_numeric($FormatArgs) ? $FormatArgs : 2);
                        case 'integer':
                            $Result = (string) round($Value);
                            if (is_numeric($FormatArgs) && strlen($Result) < $FormatArgs) {
                                $Result = str_repeat('0', $FormatArgs - strlen($Result)) . $Result;
                            }
                            break;
                        case 'percent':
                            $Result = round($Value * 100, is_numeric($FormatArgs) ? $FormatArgs : 0);
                            break;
                        default:
                            $Result = number_format($Value, is_numeric($FormatArgs) ? $FormatArgs : 0);
                            break;
                    }
                }
                break;
            case 'plural':
                if (is_array($Value)) {
                    $Value = count($Value);
                } elseif (StringEndsWith($Field, 'UserID', TRUE)) {
                    $Value = 1;
                }
                if (!is_numeric($Value)) {
                    $Result = $Value;
                } else {
                    if (!$SubFormat) {
                        $SubFormat = rtrim("%s {$Field}", 's');
                    }
                    if (!$FormatArgs) {
                        $FormatArgs = $SubFormat . 's';
                    }
                    $Result = Plural($Value, $SubFormat, $FormatArgs);
                }
                break;
            case 'rawurlencode':
                $Result = rawurlencode($Value);
                break;
            case 'text':
                $Result = Gdn_Format::Text($Value, FALSE);
                break;
            case 'time':
                $Result = Gdn_Format::Date($Value, '%l:%M%p');
                break;
            case 'url':
                if (strpos($Field, '/') !== FALSE) {
                    $Value = $Field;
                }
                $Result = Url($Value, $SubFormat == 'domain');
                break;
            case 'exurl':
                if (strpos($Field, '/') !== FALSE) {
                    $Value = $Field;
                }
                $Result = ExternalUrl($Value);
                break;
            case 'urlencode':
                $Result = urlencode($Value);
                break;
            case 'gender':
                // Format in the form of FieldName,gender,male,female,unknown
                if (is_array($Value) && count($Value) == 1) {
                    $Value = array_shift($Value);
                }
                $Gender = 'u';
                if (!is_array($Value)) {
                    $User = Gdn::UserModel()->GetID($Value);
                    if ($User) {
                        $Gender = $User->Gender;
                    }
                }
                switch ($Gender) {
                    case 'm':
                        $Result = $SubFormat;
                        break;
                    case 'f':
                        $Result = $FormatArgs;
                        break;
                    default:
                        $Result = GetValue(4, $Parts);
                }
                break;
            case 'user':
            case 'you':
            case 'his':
            case 'her':
            case 'your':
                $Result = print_r($Value, TRUE);
                $ArgsBak = $Args;
                if (is_array($Value) && count($Value) == 1) {
                    $Value = array_shift($Value);
                }
                if (is_array($Value)) {
                    $Max = C('Garden.FormatUsername.Max', 5);
                    $Count = count($Value);
                    $Result = '';
                    for ($i = 0; $i < $Count; $i++) {
                        if ($i >= $Max && $Count > $Max + 1) {
                            $Others = $Count - $i;
                            $Result .= ' ' . T('sep and', 'and') . ' ' . Plural($Others, '%s other', '%s others');
                            break;
                        }
                        $ID = $Value[$i];
                        if (is_array($ID)) {
                            continue;
                        }
                        if ($i == $Count - 1) {
                            $Result .= ' ' . T('sep and', 'and') . ' ';
                        } elseif ($i > 0) {
                            $Result .= ', ';
                        }
                        $Special = array(-1 => T('everyone'), -2 => T('moderators'), -3 => T('administrators'));
                        if (isset($Special[$ID])) {
                            $Result .= $Special[$ID];
                        } else {
                            $User = Gdn::UserModel()->GetID($ID);
                            $User->Name = FormatUsername($User, $Format, Gdn::Session()->UserID);
                            $Result .= UserAnchor($User);
                        }
                    }
                } else {
                    $User = Gdn::UserModel()->GetID($Value);
                    $User->Name = FormatUsername($User, $Format, Gdn::Session()->UserID);
                    $Result = UserAnchor($User);
                }
                $Args = $ArgsBak;
                break;
            default:
                $Result = $Value;
                break;
        }
    }
    return $Result;
}
コード例 #28
0
 function newComments($Discussion)
 {
     if (!Gdn::session()->isValid()) {
         return '';
     }
     if ($Discussion->CountUnreadComments === TRUE) {
         $Title = htmlspecialchars(t("You haven't read this yet."));
         return ' <strong class="HasNew JustNew NewCommentCount" title="' . $Title . '">' . t('new discussion', 'new') . '</strong>';
     } elseif ($Discussion->CountUnreadComments > 0) {
         $Title = htmlspecialchars(Plural($Discussion->CountUnreadComments, "%s new comment since you last read this.", "%s new comments since you last read this."));
         return ' <strong class="HasNew NewCommentCount" title="' . $Title . '">' . plural($Discussion->CountUnreadComments, '%s new', '%s new plural', BigPlural($Discussion->CountUnreadComments, '%s new', '%s new plural')) . '</strong>';
     }
     return '';
 }
コード例 #29
0
 public function DiscussionsController_AfterCountMeta_Handler($Sender, $Args)
 {
     $Discussion = GetValue('Discussion', $Args);
     if (!$Discussion) {
         return;
     }
     if ($CountWhispers = GetValue('CountWhispers', $Discussion)) {
         $Str = ' <span class="CommentCount MItem">' . Plural($CountWhispers, '%s whisper', '%s whispers') . '</span> ';
         if (GetValue('NewWhispers', $Discussion)) {
             $Str .= ' <strong class="HasNew">' . T('new') . '</strong> ';
         }
         echo $Str;
     }
 }
コード例 #30
0
 /**
  * Gets a nice title to represent the participants in a conversation.
  *
  * @param array|object $Conversation
  * @param array|object $Participants
  * @return string Returns a title for the conversation.
  */
 public static function ParticipantTitle($Conversation, $Html = TRUE, $Max = 3)
 {
     $Participants = GetValue('Participants', $Conversation);
     $Total = GetValue('CountParticipants', $Conversation);
     $MyID = Gdn::Session()->UserID;
     $FoundMe = FALSE;
     // Try getting people that haven't left the conversation and aren't you.
     $Users = array();
     $i = 0;
     foreach ($Participants as $Row) {
         if (GetValue('UserID', $Row) == $MyID) {
             $FoundMe = TRUE;
             continue;
         }
         if (GetValue('Deleted', $Row)) {
             continue;
         }
         if ($Html) {
             $Users[] = UserAnchor($Row);
         } else {
             $Users[] = GetValue('Name', $Row);
         }
         $i++;
         if ($i > $Max || $Total > $Max && $i === $Max) {
             break;
         }
     }
     $Count = count($Users);
     if ($Count === 0) {
         if ($FoundMe) {
             $Result = T('Just you');
         } elseif ($Total) {
             $Result = Plural($Total, '%s person', '%s people');
         } else {
             $Result = T('Nobody');
         }
     } else {
         $Px = implode(', ', $Users);
         if ($Count + 1 === $Total && $FoundMe) {
             $Result = $Px;
         } elseif ($Total === $Count + 1) {
             $Result = sprintf(T('%s and 1 other'), $Px);
         } elseif ($Total > $Count) {
             $Result = sprintf(T('%s and %s others'), $Px, $Total - $Count);
         } else {
             $Result = $Px;
         }
     }
     return $Result;
 }