/**
 * A placeholder for future menu items.
 *
 * @param array $Params The parameters passed into the function.
 * @param Smarty $Smarty The smarty object rendering the template.
 * @return string
 */
function smarty_function_custom_menu($Params, &$Smarty)
{
    $Controller = $Smarty->Controller;
    if (is_object($Menu = val('Menu', $Controller))) {
        $Format = val('format', $Params, wrap('<a href="%url" class="%class">%text</a>', val('wrap', $Params, 'li')));
        $Result = '';
        foreach ($Menu->Items as $Group) {
            foreach ($Group as $Item) {
                // Make sure the item is a custom item.
                if (valr('Attributes.Standard', $Item)) {
                    continue;
                }
                // Make sure the user has permission for the item.
                if ($Permission = val('Permission', $Item)) {
                    if (!Gdn::session()->checkPermission($Permission)) {
                        continue;
                    }
                }
                if (($Url = val('Url', $Item)) && ($Text = val('Text', $Item))) {
                    $Attributes = val('Attributes', $Item);
                    $Result .= Gdn_Theme::link($Url, $Text, $Format, $Attributes) . "\r\n";
                }
            }
        }
        return $Result;
    }
    return '';
}
 /**
  *
  *
  * @param $Result
  * @param $PageWhere
  * @param $DiscussionID
  * @param $Page
  * @param null $Limit
  */
 public function cachePageWhere($Result, $PageWhere, $DiscussionID, $Page, $Limit = null)
 {
     if (!$this->pageCache || !empty($this->_Where) || $this->_OrderBy[0][0] != 'c.DateInserted' || $this->_OrderBy[0][1] == 'desc') {
         return;
     }
     if (count($Result) == 0) {
         return;
     }
     $ConfigLimit = c('Vanilla.Comments.PerPage', 30);
     if (!$Limit) {
         $Limit = $ConfigLimit;
     }
     if ($Limit != $ConfigLimit) {
         return;
     }
     if (is_array($PageWhere)) {
         $Curr = array_values($PageWhere);
     } else {
         $Curr = false;
     }
     $New = array(GetValueR('0.DateInserted', $Result));
     if (count($Result) >= $Limit) {
         $New[] = valr($Limit - 1 . '.DateInserted', $Result);
     }
     if ($Curr != $New) {
         trace('CommentModel->CachePageWhere()');
         $CacheKey = "Comment.Page.{$Limit}.{$DiscussionID}.{$Page}";
         Gdn::cache()->store($CacheKey, $New, array(Gdn_Cache::FEATURE_EXPIRY => 86400));
         trace($New, $CacheKey);
         //         Gdn::controller()->setData('_PageCacheStore', array($CacheKey, $New));
     }
 }
 public function discussionModel_afterSaveDiscussion_handler($Sender)
 {
     $FormPostValues = val('FormPostValues', $Sender->EventArguments, array());
     $url = valr("Discussion.Url", $Sender->EventArguments);
     if (val('IsNewDiscussion', $FormPostValues, false) !== false) {
         $this->_push(array($url));
     }
 }
 /**
  *
  *
  * @param $Data
  * @param $Options
  * @return bool
  */
 public static function check(&$Data, &$Options)
 {
     // Make the request.
     $Get = array();
     if (isset($Data['IPAddress'])) {
         $AddIP = true;
         // Don't check against the localhost.
         foreach (array('127.0.0.1/0', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16') as $LocalCIDR) {
             if (Gdn_Statistics::cidrCheck($Data['IPAddress'], $LocalCIDR)) {
                 $AddIP = false;
                 break;
             }
         }
         if ($AddIP) {
             $Get['ip'] = $Data['IPAddress'];
         }
     }
     if (isset($Data['Username'])) {
         $Get['username'] = $Data['Username'];
     }
     if (isset($Data['Email'])) {
         $Get['email'] = $Data['Email'];
     }
     if (empty($Get)) {
         return false;
     }
     $Get['f'] = 'json';
     $Url = "http://www.stopforumspam.com/api?" . http_build_query($Get);
     $Curl = curl_init();
     curl_setopt($Curl, CURLOPT_URL, $Url);
     curl_setopt($Curl, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($Curl, CURLOPT_TIMEOUT, 4);
     curl_setopt($Curl, CURLOPT_FAILONERROR, 1);
     $ResultString = curl_exec($Curl);
     curl_close($Curl);
     if ($ResultString) {
         $Result = json_decode($ResultString, true);
         $IPFrequency = valr('ip.frequency', $Result, 0);
         $EmailFrequency = valr('email.frequency', $Result, 0);
         $IsSpam = false;
         // Flag registrations as spam above a certain threshold.
         if ($IPFrequency >= c('Plugins.StopForumSpam.IPThreshold1', 5) || $EmailFrequency >= c('Plugins.StopForumSpam.EmailThreshold1', 20)) {
             $IsSpam = true;
         }
         // Don't even log registrations that are above another threahold.
         if ($IPFrequency >= c('Plugins.StopForumSpam.IPThreshold2', 20) || $EmailFrequency >= c('Plugins.StopForumSpam.EmailThreshold2', 50)) {
             $Options['Log'] = false;
         }
         if ($Result) {
             $Data['_Meta']['IP Frequency'] = $IPFrequency;
             $Data['_Meta']['Email Frequency'] = $EmailFrequency;
         }
         return $IsSpam;
     }
     return false;
 }
/**
 * Get all tutorials, or a specific one.
 */
function getTutorials($TutorialCode = '')
{
    // Define all Tutorials
    $Tutorials = array(array('Code' => 'introduction', 'Name' => 'Introduction to Vanilla', 'Description' => 'This video gives you a brief overview of the Vanilla administrative dashboard and the forum itself.', 'VideoID' => '31043422'), array('Code' => 'using-the-forum', 'Name' => 'Using the Forum', 'Description' => 'Learn how to start, announce, close, edit and delete discussions and comments.', 'VideoID' => '31502992'), array('Code' => 'private-conversations', 'Name' => 'Private Conversations', 'Description' => 'Learn how to start new private conversations and add people to them.', 'VideoID' => '31498383'), array('Code' => 'user-profiles', 'Name' => 'User Profiles', 'Description' => 'Learn how to use and manage your user profile. ', 'VideoID' => '31499266'), array('Code' => 'appearance', 'Name' => 'Changing the appearance of your forum', 'Description' => 'This tutorial takes you through the "Appearance" section of the Vanilla Forums administrative dashboard.', 'VideoID' => '31089641'), array('Code' => 'roles-and-permissions', 'Name' => 'Managing Roles and Permissions in Vanilla', 'Description' => 'This tutorial walks you through how to create new roles and how to use permissions.', 'VideoID' => '31091056'), array('Code' => 'users', 'Name' => 'Finding &amp; Managing Users', 'Description' => 'This tutorial shows you how to search for and manage users.', 'VideoID' => '31094514'), array('Code' => 'category-management-and-advanced-settings', 'Name' => 'Category Management &amp; Advanced Settings', 'Description' => 'Learn how to add, edit, and manage categories. Also learn about advanced forum settings.', 'VideoID' => '31492046'), array('Code' => 'user-registration', 'Name' => 'User Registration', 'Description' => 'Learn to control how new users get into your community.', 'VideoID' => '31493119'));
    // Default Thumbnails
    $Thumbnail = Asset('applications/dashboard/design/images/help-tn-200.jpg');
    $LargeThumbnail = Asset('applications/dashboard/design/images/help-tn-640.jpg');
    for ($i = 0; $i < count($Tutorials); $i++) {
        $Tutorials[$i]['Thumbnail'] = $Thumbnail;
        $Tutorials[$i]['LargeThumbnail'] = $LargeThumbnail;
    }
    if ($TutorialCode != '') {
        $Keys = consolidateArrayValuesByKey($Tutorials, 'Code');
        $Index = array_search($TutorialCode, $Keys);
        if ($Index === FALSE) {
            return FALSE;
        }
        // Not found!
        // Found it, so define it's thumbnail location
        $Tutorial = val($Index, $Tutorials);
        $VideoID = val('VideoID', $Tutorial);
        try {
            $Vimeo = unserialize(file_get_contents("http://vimeo.com/api/v2/video/" . $Tutorial['VideoID'] . ".php"));
            $Tutorial['Thumbnail'] = str_replace('http://', '//', valr('0.thumbnail_medium', $Vimeo));
            $Tutorial['LargeThumbnail'] = str_replace('http://', '//', valr('0.thumbnail_large', $Vimeo));
        } catch (Exception $Ex) {
            // Do nothing
        }
        return $Tutorial;
    } else {
        // Loop through each tutorial populating the thumbnail image location
        try {
            foreach ($Tutorials as $Key => $Tutorial) {
                $Vimeo = unserialize(file_get_contents("http://vimeo.com/api/v2/video/" . $Tutorial['VideoID'] . ".php"));
                $Tutorial['Thumbnail'] = str_replace('http://', '//', valr('0.thumbnail_medium', $Vimeo));
                $Tutorial['LargeThumbnail'] = str_replace('http://', '//', valr('0.thumbnail_large', $Vimeo));
            }
        } catch (Exception $Ex) {
            // Do nothing
        }
        return $Tutorials;
    }
}
Esempio n. 6
0
function writeConnection($Row)
{
    $c = Gdn::controller();
    $Connected = val('Connected', $Row);
    ?>
    <li id="<?php 
    echo "Provider_{$Row['ProviderKey']}";
    ?>
" class="Item">
        <div class="Connection-Header">
         <span class="IconWrap">
            <?php 
    echo img(val('Icon', $Row, Asset('/applications/dashboard/design/images/connection-64.png')));
    ?>
         </span>
         <span class="Connection-Name">
            <?php 
    echo val('Name', $Row, t('Unknown'));
    if ($Connected) {
        echo ' <span class="Gloss Connected">';
        if ($Photo = valr('Profile.Photo', $Row)) {
            echo ' ' . Img($Photo, array('class' => 'ProfilePhoto ProfilePhotoSmall'));
        }
        echo ' ' . htmlspecialchars(GetValueR('Profile.Name', $Row)) . '</span>';
    }
    ?>
         </span>
         <span class="Connection-Connect">
            <?php 
    echo ConnectButton($Row);
    ?>
         </span>
        </div>
        <!--      <div class="Connection-Body">
         <?php 
    //         if (Debug()) {
    //            decho(val($Row['ProviderKey'], $c->User->Attributes), 'Attributes');
    //         }
    ?>
      </div>-->
    </li>
<?php 
}
Esempio n. 7
0
 /**
  * Create or update a comment.
  *
  * @since 2.0.0
  * @access public
  *
  * @param int $DiscussionID Unique ID to add the comment to. If blank, this method will throw an error.
  */
 public function comment($DiscussionID = '')
 {
     // Get $DiscussionID from RequestArgs if valid
     if ($DiscussionID == '' && count($this->RequestArgs)) {
         if (is_numeric($this->RequestArgs[0])) {
             $DiscussionID = $this->RequestArgs[0];
         }
     }
     // If invalid $DiscussionID, get from form.
     $this->Form->setModel($this->CommentModel);
     $DiscussionID = is_numeric($DiscussionID) ? $DiscussionID : $this->Form->getFormValue('DiscussionID', 0);
     // Set discussion data
     $this->DiscussionID = $DiscussionID;
     $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID);
     // Is this an embedded comment being posted to a discussion that doesn't exist yet?
     $vanilla_type = $this->Form->getFormValue('vanilla_type', '');
     $vanilla_url = $this->Form->getFormValue('vanilla_url', '');
     $vanilla_category_id = $this->Form->getFormValue('vanilla_category_id', '');
     $Attributes = array('ForeignUrl' => $vanilla_url);
     $vanilla_identifier = $this->Form->getFormValue('vanilla_identifier', '');
     $isEmbeddedComments = $vanilla_url != '' && $vanilla_identifier != '';
     // Only allow vanilla identifiers of 32 chars or less - md5 if larger
     if (strlen($vanilla_identifier) > 32) {
         $Attributes['vanilla_identifier'] = $vanilla_identifier;
         $vanilla_identifier = md5($vanilla_identifier);
     }
     if (!$Discussion && $isEmbeddedComments) {
         $Discussion = $Discussion = $this->DiscussionModel->getForeignID($vanilla_identifier, $vanilla_type);
         if ($Discussion) {
             $this->DiscussionID = $DiscussionID = $Discussion->DiscussionID;
             $this->Form->setValue('DiscussionID', $DiscussionID);
         }
     }
     // If so, create it!
     if (!$Discussion && $isEmbeddedComments) {
         // Add these values back to the form if they exist!
         $this->Form->addHidden('vanilla_identifier', $vanilla_identifier);
         $this->Form->addHidden('vanilla_type', $vanilla_type);
         $this->Form->addHidden('vanilla_url', $vanilla_url);
         $this->Form->addHidden('vanilla_category_id', $vanilla_category_id);
         $PageInfo = fetchPageInfo($vanilla_url);
         if (!($Title = $this->Form->getFormValue('Name'))) {
             $Title = val('Title', $PageInfo, '');
             if ($Title == '') {
                 $Title = t('Undefined discussion subject.');
                 if (!empty($PageInfo['Exception']) && $PageInfo['Exception'] === "Couldn't connect to host.") {
                     $Title .= ' ' . t('Page timed out.');
                 }
             }
         }
         $Description = val('Description', $PageInfo, '');
         $Images = val('Images', $PageInfo, array());
         $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here');
         if (!$Description && count($Images) == 0) {
             $Body = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
         } else {
             $Body = formatString('
         <div class="EmbeddedContent">{Image}<strong>{Title}</strong>
            <p>{Excerpt}</p>
            <p><a href="{Url}">{LinkText}</a></p>
            <div class="ClearFix"></div>
         </div>', array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? img(val(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $vanilla_url, 'LinkText' => $LinkText));
         }
         if ($Body == '') {
             $Body = $vanilla_url;
         }
         if ($Body == '') {
             $Body = t('Undefined discussion body.');
         }
         // Validate the CategoryID for inserting.
         $Category = CategoryModel::categories($vanilla_category_id);
         if (!$Category) {
             $vanilla_category_id = c('Vanilla.Embed.DefaultCategoryID', 0);
             if ($vanilla_category_id <= 0) {
                 // No default category defined, so grab the first non-root category and use that.
                 $vanilla_category_id = $this->DiscussionModel->SQL->select('CategoryID')->from('Category')->where('CategoryID >', 0)->get()->firstRow()->CategoryID;
                 // No categories in the db? default to 0
                 if (!$vanilla_category_id) {
                     $vanilla_category_id = 0;
                 }
             }
         } else {
             $vanilla_category_id = $Category['CategoryID'];
         }
         $EmbedUserID = c('Garden.Embed.UserID');
         if ($EmbedUserID) {
             $EmbedUser = Gdn::userModel()->getID($EmbedUserID);
         }
         if (!$EmbedUserID || !$EmbedUser) {
             $EmbedUserID = Gdn::userModel()->getSystemUserID();
         }
         $EmbeddedDiscussionData = array('InsertUserID' => $EmbedUserID, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime(), 'CategoryID' => $vanilla_category_id, 'ForeignID' => $vanilla_identifier, 'Type' => $vanilla_type, 'Name' => $Title, 'Body' => $Body, 'Format' => 'Html', 'Attributes' => dbencode($Attributes));
         $this->EventArguments['Discussion'] =& $EmbeddedDiscussionData;
         $this->fireEvent('BeforeEmbedDiscussion');
         $DiscussionID = $this->DiscussionModel->SQL->insert('Discussion', $EmbeddedDiscussionData);
         $ValidationResults = $this->DiscussionModel->validationResults();
         if (count($ValidationResults) == 0 && $DiscussionID > 0) {
             $this->Form->addHidden('DiscussionID', $DiscussionID);
             // Put this in the form so reposts won't cause new discussions.
             $this->Form->setFormValue('DiscussionID', $DiscussionID);
             // Put this in the form values so it is used when saving comments.
             $this->setJson('DiscussionID', $DiscussionID);
             $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => false));
             // Update the category discussion count
             if ($vanilla_category_id > 0) {
                 $this->DiscussionModel->updateDiscussionCount($vanilla_category_id, $DiscussionID);
             }
         }
     }
     // If no discussion was found, error out
     if (!$Discussion) {
         $this->Form->addError(t('Failed to find discussion for commenting.'));
     }
     /**
      * Special care is taken for embedded comments.  Since we don't currently use an advanced editor for these
      * comments, we may need to apply certain filters and fixes to the data to maintain its intended display
      * with the input format (e.g. maintaining newlines).
      */
     if ($isEmbeddedComments) {
         $inputFormatter = $this->Form->getFormValue('Format', c('Garden.InputFormatter'));
         switch ($inputFormatter) {
             case 'Wysiwyg':
                 $this->Form->setFormValue('Body', nl2br($this->Form->getFormValue('Body')));
                 break;
         }
     }
     $PermissionCategoryID = val('PermissionCategoryID', $Discussion);
     // Setup head
     $this->addJsFile('jquery.autosize.min.js');
     $this->addJsFile('autosave.js');
     $this->addJsFile('post.js');
     // Setup comment model, $CommentID, $DraftID
     $Session = Gdn::session();
     $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : '';
     $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : '';
     $this->EventArguments['CommentID'] = $CommentID;
     $this->EventArguments['DraftID'] = $DraftID;
     // Determine whether we are editing
     $Editing = $CommentID > 0 || $DraftID > 0;
     $this->EventArguments['Editing'] = $Editing;
     // If closed, cancel & go to discussion
     if ($Discussion && $Discussion->Closed == 1 && !$Editing && !$Session->checkPermission('Vanilla.Discussions.Close', true, 'Category', $PermissionCategoryID)) {
         redirect(DiscussionUrl($Discussion));
     }
     // Add hidden IDs to form
     $this->Form->addHidden('DiscussionID', $DiscussionID);
     $this->Form->addHidden('CommentID', $CommentID);
     $this->Form->addHidden('DraftID', $DraftID, true);
     // Check permissions
     if ($Discussion && $Editing) {
         // Permission to edit
         if ($this->Comment->InsertUserID != $Session->UserID) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure that content can (still) be edited.
         $EditContentTimeout = c('Garden.EditContentTimeout', -1);
         $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time();
         if (!$CanEdit) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         // Make sure only moderators can edit closed things
         if ($Discussion->Closed) {
             $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID);
         }
         $this->Form->setFormValue('CommentID', $CommentID);
     } elseif ($Discussion) {
         // Permission to add
         $this->permission('Vanilla.Comments.Add', true, 'Category', $Discussion->PermissionCategoryID);
     }
     if ($this->Form->authenticatedPostBack()) {
         // Save as a draft?
         $FormValues = $this->Form->formValues();
         $FormValues = $this->CommentModel->filterForm($FormValues);
         if (!$Editing) {
             unset($FormValues['CommentID']);
         }
         if ($DraftID == 0) {
             $DraftID = $this->Form->getFormValue('DraftID', 0);
         }
         $Type = GetIncomingValue('Type');
         $Draft = $Type == 'Draft';
         $this->EventArguments['Draft'] = $Draft;
         $Preview = $Type == 'Preview';
         if ($Draft) {
             $DraftID = $this->DraftModel->save($FormValues);
             $this->Form->addHidden('DraftID', $DraftID, true);
             $this->Form->setValidationResults($this->DraftModel->validationResults());
         } elseif (!$Preview) {
             // Fix an undefined title if we can.
             if ($this->Form->getFormValue('Name') && val('Name', $Discussion) == t('Undefined discussion subject.')) {
                 $Set = array('Name' => $this->Form->getFormValue('Name'));
                 if (isset($vanilla_url) && $vanilla_url && strpos(val('Body', $Discussion), t('Undefined discussion subject.')) !== false) {
                     $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here');
                     $Set['Body'] = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText));
                 }
                 $this->DiscussionModel->setField(val('DiscussionID', $Discussion), $Set);
             }
             $Inserted = !$CommentID;
             $CommentID = $this->CommentModel->save($FormValues);
             // The comment is now half-saved.
             if (is_numeric($CommentID) && $CommentID > 0) {
                 if (in_array($this->deliveryType(), array(DELIVERY_TYPE_ALL, DELIVERY_TYPE_DATA))) {
                     $this->CommentModel->save2($CommentID, $Inserted, true, true);
                 } else {
                     $this->jsonTarget('', url("/post/comment2.json?commentid={$CommentID}&inserted={$Inserted}"), 'Ajax');
                 }
                 // $Discussion = $this->DiscussionModel->getID($DiscussionID);
                 $Comment = $this->CommentModel->getID($CommentID, DATASET_TYPE_OBJECT, array('Slave' => false));
                 $this->EventArguments['Discussion'] = $Discussion;
                 $this->EventArguments['Comment'] = $Comment;
                 $this->fireEvent('AfterCommentSave');
             } elseif ($CommentID === SPAM || $CommentID === UNAPPROVED) {
                 $this->StatusMessage = t('CommentRequiresApprovalStatus', 'Your comment will appear after it is approved.');
             }
             $this->Form->setValidationResults($this->CommentModel->validationResults());
             if ($CommentID > 0 && $DraftID > 0) {
                 $this->DraftModel->delete($DraftID);
             }
         }
         // Handle non-ajax requests first:
         if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
             if ($this->Form->errorCount() == 0) {
                 // Make sure that this form knows what comment we are editing.
                 if ($CommentID > 0) {
                     $this->Form->addHidden('CommentID', $CommentID);
                 }
                 // If the comment was not a draft
                 if (!$Draft) {
                     // Redirect to the new comment.
                     if ($CommentID > 0) {
                         redirect("discussion/comment/{$CommentID}/#Comment_{$CommentID}");
                     } elseif ($CommentID == SPAM) {
                         $this->setData('DiscussionUrl', DiscussionUrl($Discussion));
                         $this->View = 'Spam';
                     }
                 } elseif ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $this->Comment = new stdClass();
                     $this->Comment->InsertUserID = $Session->User->UserID;
                     $this->Comment->InsertName = $Session->User->Name;
                     $this->Comment->InsertPhoto = $Session->User->Photo;
                     $this->Comment->DateInserted = Gdn_Format::date();
                     $this->Comment->Body = val('Body', $FormValues, '');
                     $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
                     $this->addAsset('Content', $this->fetchView('preview'));
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
             }
         } else {
             // Handle ajax-based requests
             if ($this->Form->errorCount() > 0) {
                 // Return the form errors
                 $this->errorMessage($this->Form->errors());
             } else {
                 // Make sure that the ajax request form knows about the newly created comment or draft id
                 $this->setJson('CommentID', $CommentID);
                 $this->setJson('DraftID', $DraftID);
                 if ($Preview) {
                     // If this was a preview click, create a comment shell with the values for this comment
                     $this->Comment = new stdClass();
                     $this->Comment->InsertUserID = $Session->User->UserID;
                     $this->Comment->InsertName = $Session->User->Name;
                     $this->Comment->InsertPhoto = $Session->User->Photo;
                     $this->Comment->DateInserted = Gdn_Format::date();
                     $this->Comment->Body = val('Body', $FormValues, '');
                     $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter'));
                     $this->View = 'preview';
                 } elseif (!$Draft) {
                     // If the comment was not a draft
                     // If Editing a comment
                     if ($Editing) {
                         // Just reload the comment in question
                         $this->Offset = 1;
                         $Comments = $this->CommentModel->getIDData($CommentID, array('Slave' => false));
                         $this->setData('Comments', $Comments);
                         $this->setData('Discussion', $Discussion);
                         // Load the discussion
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         // Also define the discussion url in case this request came from the post screen and needs to be redirected to the discussion
                         $this->setJson('DiscussionUrl', DiscussionUrl($this->Discussion) . '#Comment_' . $CommentID);
                     } else {
                         // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments.
                         $OrderBy = valr('0.0', $this->CommentModel->orderBy());
                         //                     $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID'));
                         //							$DisplayNewCommentOnly = $this->Form->getFormValue('DisplayNewCommentOnly');
                         //                     if (!$Redirect) {
                         //                        // Otherwise load all new comments that the user hasn't seen yet
                         //                        $LastCommentID = $this->Form->getFormValue('LastCommentID');
                         //                        if (!is_numeric($LastCommentID))
                         //                           $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly
                         //
                         //                        // Don't reload the first comment if this new comment is the first one.
                         //                        $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID);
                         //                        // Do not load more than a single page of data...
                         //                        $Limit = c('Vanilla.Comments.PerPage', 30);
                         //
                         //                        // Redirect if the new new comment isn't on the same page.
                         //                        $Redirect |= !$DisplayNewCommentOnly && PageNumber($this->Offset, $Limit) != PageNumber($Discussion->CountComments - 1, $Limit);
                         //                     }
                         //                     if ($Redirect) {
                         //                        // The user posted a comment on a page other than the last one, so just redirect to the last page.
                         //                        $this->RedirectUrl = Gdn::request()->Url("discussion/comment/$CommentID/#Comment_$CommentID", true);
                         //                     } else {
                         //                        // Make sure to load all new comments since the page was last loaded by this user
                         //								if ($DisplayNewCommentOnly)
                         $this->Offset = $this->CommentModel->GetOffset($CommentID);
                         $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => false));
                         $this->setData('Comments', $Comments);
                         $this->setData('NewComments', true);
                         $this->ClassName = 'DiscussionController';
                         $this->ControllerName = 'discussion';
                         $this->View = 'comments';
                         //                     }
                         // Make sure to set the user's discussion watch records
                         $CountComments = $this->CommentModel->getCount($DiscussionID);
                         $Limit = is_object($this->data('Comments')) ? $this->data('Comments')->numRows() : $Discussion->CountComments;
                         $Offset = $CountComments - $Limit;
                         $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments);
                     }
                 } else {
                     // If this was a draft save, notify the user about the save
                     $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date()));
                 }
                 // And update the draft count
                 $UserModel = Gdn::userModel();
                 $CountDrafts = $UserModel->getAttribute($Session->UserID, 'CountDrafts', 0);
                 $this->setJson('MyDrafts', t('My Drafts'));
                 $this->setJson('CountDrafts', $CountDrafts);
             }
         }
     } elseif ($this->Request->isPostBack()) {
         throw new Gdn_UserException(t('Invalid CSRF token.', 'Invalid CSRF token. Please try again.'), 401);
     } else {
         // Load form
         if (isset($this->Comment)) {
             $this->Form->setData((array) $this->Comment);
         }
     }
     // Include data for FireEvent
     if (property_exists($this, 'Discussion')) {
         $this->EventArguments['Discussion'] = $this->Discussion;
     }
     if (property_exists($this, 'Comment')) {
         $this->EventArguments['Comment'] = $this->Comment;
     }
     $this->fireEvent('BeforeCommentRender');
     if ($this->deliveryType() == DELIVERY_TYPE_DATA) {
         if ($this->data('Comments') instanceof Gdn_DataSet) {
             $Comment = $this->data('Comments')->firstRow(DATASET_TYPE_ARRAY);
             if ($Comment) {
                 $Photo = $Comment['InsertPhoto'];
                 if (strpos($Photo, '//') === false) {
                     $Photo = Gdn_Upload::url(changeBasename($Photo, 'n%s'));
                 }
                 $Comment['InsertPhoto'] = $Photo;
             }
             $this->Data = array('Comment' => $Comment);
         }
         $this->RenderData($this->Data);
     } else {
         require_once $this->fetchViewLocation('helper_functions', 'Discussion');
         // Render default view.
         $this->render();
     }
 }
 /** Checks to see of a table and/or column exists in the import data.
  *
  * @param string $Table The name of the table to check for.
  * @param string $Column
  * @return bool
  */
 public function importExists($Table, $Column = '')
 {
     if (!array_key_exists('Tables', $this->Data) || !array_key_exists($Table, $this->Data['Tables'])) {
         return false;
     }
     if (!$Column) {
         return true;
     }
     $Tables = $this->Data['Tables'];
     $Exists = valr("Tables.{$Table}.Columns.{$Column}", $this->Data, false);
     return $Exists !== false;
 }
Esempio n. 9
0
 /**
  * Generate an e-tag for the application from the versions of all of its enabled applications/plugins.
  **/
 public static function eTag()
 {
     $Data = array();
     $Data['vanilla-core-' . APPLICATION_VERSION] = true;
     $Plugins = Gdn::pluginManager()->EnabledPlugins();
     foreach ($Plugins as $Info) {
         $Data[strtolower("{$Info['Index']}-plugin-{$Info['Version']}")] = true;
     }
     //      echo(Gdn_Upload::FormatFileSize(strlen(serialize($Plugins))));
     //      decho($Plugins);
     $Applications = Gdn::ApplicationManager()->EnabledApplications();
     foreach ($Applications as $Info) {
         $Data[strtolower("{$Info['Index']}-app-{$Info['Version']}")] = true;
     }
     // Add the desktop theme version.
     $Info = Gdn::ThemeManager()->GetThemeInfo(Gdn::ThemeManager()->DesktopTheme());
     if (!empty($Info)) {
         $Version = val('Version', $Info, 'v0');
         $Data[strtolower("{$Info['Index']}-theme-{$Version}")] = true;
         if (Gdn::controller()->Theme && Gdn::controller()->ThemeOptions) {
             $Filenames = valr('Styles.Value', Gdn::controller()->ThemeOptions);
             $Data[$Filenames] = true;
         }
     }
     // Add the mobile theme version.
     $Info = Gdn::ThemeManager()->GetThemeInfo(Gdn::ThemeManager()->MobileTheme());
     if (!empty($Info)) {
         $Version = val('Version', $Info, 'v0');
         $Data[strtolower("{$Info['Index']}-theme-{$Version}")] = true;
     }
     Gdn::pluginManager()->EventArguments['ETagData'] =& $Data;
     $Suffix = '';
     Gdn::pluginManager()->EventArguments['Suffix'] =& $Suffix;
     Gdn::pluginManager()->FireAs('AssetModel')->fireEvent('GenerateETag');
     unset(Gdn::pluginManager()->EventArguments['ETagData']);
     ksort($Data);
     $Result = substr(md5(implode(',', array_keys($Data))), 0, 8) . $Suffix;
     //      decho($Data);
     //      die();
     return $Result;
 }
Esempio n. 10
0
 /**
  *
  *
  * @param $Code
  * @param $RedirectUri
  * @param bool $ThrowError
  * @return mixed
  * @throws Gdn_UserException
  */
 protected function getAccessToken($Code, $RedirectUri, $ThrowError = true)
 {
     $Get = array('client_id' => c('Plugins.Facebook.ApplicationID'), 'client_secret' => c('Plugins.Facebook.Secret'), 'code' => $Code, 'redirect_uri' => $RedirectUri);
     $Url = 'https://graph.facebook.com/oauth/access_token?' . http_build_query($Get);
     // Get the redirect URI.
     $C = curl_init();
     curl_setopt($C, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($C, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($C, CURLOPT_URL, $Url);
     $Contents = curl_exec($C);
     $Info = curl_getinfo($C);
     if (strpos(val('content_type', $Info, ''), '/javascript') !== false) {
         $Tokens = json_decode($Contents, true);
     } else {
         parse_str($Contents, $Tokens);
     }
     if (val('error', $Tokens)) {
         throw new Gdn_UserException('Facebook returned the following error: ' . valr('error.message', $Tokens, 'Unknown error.'), 400);
     }
     $AccessToken = val('access_token', $Tokens);
     //      $Expires = val('expires', $Tokens, null);
     return $AccessToken;
 }
Esempio n. 11
0
 /**
  * Send welcome email to user.
  *
  * @param int $UserID
  * @param string $Password
  * @param string $RegisterType
  * @param array|null $AdditionalData
  * @throws Exception
  */
 public function sendWelcomeEmail($UserID, $Password, $RegisterType = 'Add', $AdditionalData = null)
 {
     $Session = Gdn::session();
     $Sender = $this->getID($Session->UserID);
     $User = $this->getID($UserID);
     if (!ValidateEmail($User->Email)) {
         return;
     }
     $AppTitle = Gdn::config('Garden.Title');
     $Email = new Gdn_Email();
     $Email->subject(sprintf(t('[%s] Welcome Aboard!'), $AppTitle));
     $Email->to($User->Email);
     $emailTemplate = $Email->getEmailTemplate();
     $Data = [];
     $Data['User'] = arrayTranslate((array) $User, ['UserID', 'Name', 'Email']);
     $Data['Sender'] = arrayTranslate((array) $Sender, ['Name', 'Email']);
     $Data['Title'] = $AppTitle;
     if (is_array($AdditionalData)) {
         $Data = array_merge($Data, $AdditionalData);
     }
     $Data['EmailKey'] = valr('Attributes.EmailKey', $User);
     $message = '<p>' . formatString(t('Hello {User.Name}!'), $Data) . ' ';
     $message .= $this->getEmailWelcome($RegisterType, $User, $Data, $Password);
     // Add the email confirmation key.
     if ($Data['EmailKey']) {
         $emailUrlFormat = '{/entry/emailconfirm,exurl,domain}/{User.UserID,rawurlencode}/{EmailKey,rawurlencode}';
         $url = formatString($emailUrlFormat, $Data);
         $message .= '<p>' . t('You need to confirm your email address before you can continue.') . '</p>';
         $emailTemplate->setButton($url, t('Confirm My Email Address'));
     } else {
         $emailTemplate->setButton(externalUrl('/'), t('Access the Site'));
     }
     $emailTemplate->setMessage($message);
     $emailTemplate->setTitle(t('Welcome Aboard!'));
     $Email->setEmailTemplate($emailTemplate);
     try {
         $Email->send();
     } catch (Exception $e) {
         if (debug()) {
             throw $e;
         }
     }
 }
Esempio n. 12
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;
 }
Esempio n. 13
0
 /**
  * Generates a multi-field form from a schema.
  *
  * @param array $Schema An array where each item of the array is a row that identifies a form field with the following information:
  *  - Name: The name of the form field.
  *  - Control: The type of control used for the field. This is one of the control methods on the Gdn_Form object.
  *  - LabelCode: The translation code for the label. Optional.
  *  - Description: An optional description for the field.
  *  - Items: If the control is a list control then its items are specified here.
  *  - Options: Additional options to be passed into the control.
  * @param type $Options Additional options to pass into the form.
  *  - Wrap: A two item array specifying the text to wrap the form in.
  *  - ItemWrap: A two item array specifying the text to wrap each form item in.
  */
 public function simple($Schema, $Options = array())
 {
     $Result = valr('Wrap.0', $Options, '<ul>');
     $ItemWrap = val('ItemWrap', $Options, array("<li>\n  ", "\n</li>\n"));
     foreach ($Schema as $Index => $Row) {
         if (is_string($Row)) {
             $Row = array('Name' => $Index, 'Control' => $Row);
         }
         if (!isset($Row['Name'])) {
             $Row['Name'] = $Index;
         }
         if (!isset($Row['Options'])) {
             $Row['Options'] = array();
         }
         $Result .= $ItemWrap[0];
         $LabelCode = self::labelCode($Row);
         $Description = val('Description', $Row, '');
         if ($Description) {
             $Description = '<div class="Info">' . $Description . '</div>';
         }
         touchValue('Control', $Row, 'TextBox');
         switch (strtolower($Row['Control'])) {
             case 'categorydropdown':
                 $Result .= $this->label($LabelCode, $Row['Name']) . $Description . $this->categoryDropDown($Row['Name'], $Row['Options']);
                 break;
             case 'checkbox':
                 $Result .= $Description . $this->checkBox($Row['Name'], $LabelCode);
                 break;
             case 'dropdown':
                 $Result .= $this->label($LabelCode, $Row['Name']) . $Description . $this->dropDown($Row['Name'], $Row['Items'], $Row['Options']);
                 break;
             case 'radiolist':
                 $Result .= $Description . $this->radioList($Row['Name'], $Row['Items'], $Row['Options']);
                 break;
             case 'checkboxlist':
                 $Result .= $this->label($LabelCode, $Row['Name']) . $Description . $this->checkBoxList($Row['Name'], $Row['Items'], null, $Row['Options']);
                 break;
             case 'textbox':
                 $Result .= $this->label($LabelCode, $Row['Name']) . $Description . $this->textBox($Row['Name'], $Row['Options']);
                 break;
             case 'callback':
                 $Row['DescriptionHtml'] = $Description;
                 $Row['LabelCode'] = $LabelCode;
                 $Result .= call_user_func($Row['Callback'], $this, $Row);
                 break;
             default:
                 $Result .= "Error a control type of {$Row['Control']} is not supported.";
                 break;
         }
         $Result .= $ItemWrap[1];
     }
     $Result .= valr('Wrap.1', $Options, '</ul>');
     return $Result;
 }
Esempio n. 14
0
 /**
  * Generate an e-tag for the application from the versions of all of its enabled applications/plugins.
  *
  * @return string etag
  **/
 public static function eTag()
 {
     $data = [];
     $data['vanilla-core-' . APPLICATION_VERSION] = true;
     // Look through the enabled addons.
     /* @var Addon $addon */
     foreach (Gdn::addonManager()->getEnabled() as $addon) {
         if ($addon->getType() == Addon::TYPE_THEME) {
             // Themes have to figured out separately.
             continue;
         }
         $key = $addon->getKey();
         $version = $addon->getVersion();
         $type = $addon->getType();
         $data[strtolower("{$key}-{$type}-{$version}")] = true;
     }
     // Add the desktop theme version.
     $themes = ['' => Gdn::addonManager()->lookupTheme(Gdn::themeManager()->desktopTheme()), 'Mobile' => Gdn::addonManager()->lookupTheme(Gdn::themeManager()->mobileTheme())];
     foreach ($themes as $optionsPx => $theme) {
         if (!$theme instanceof Addon) {
             continue;
         }
         $data[$theme->getKey() . '-theme-' . $theme->getVersion()] = true;
         // Look for theme options.
         $options = c("Garden.{$optionsPx}ThemeOptions");
         if (!empty($options)) {
             $data[valr('Styles.Value', $options)] = true;
         }
     }
     $info = Gdn::themeManager()->getThemeInfo(Gdn::themeManager()->desktopTheme());
     if (!empty($info)) {
         $version = val('Version', $info, 'v0');
         $data[strtolower("{$info['Index']}-theme-{$version}")] = true;
         if (Gdn::controller()->Theme && Gdn::controller()->ThemeOptions) {
             $filenames = valr('Styles.Value', Gdn::controller()->ThemeOptions);
             $data[$filenames] = true;
         }
     }
     // Add the mobile theme version.
     $info = Gdn::themeManager()->getThemeInfo(Gdn::themeManager()->mobileTheme());
     if (!empty($info)) {
         $version = val('Version', $info, 'v0');
         $data[strtolower("{$info['Index']}-theme-{$version}")] = true;
     }
     Gdn::pluginManager()->EventArguments['ETagData'] =& $data;
     $suffix = '';
     Gdn::pluginManager()->EventArguments['Suffix'] =& $suffix;
     Gdn::pluginManager()->fireAs('AssetModel')->fireEvent('GenerateETag');
     unset(Gdn::pluginManager()->EventArguments['ETagData']);
     ksort($data);
     $result = substr(md5(implode(',', array_keys($data))), 0, 8) . $suffix;
     return $result;
 }
Esempio n. 15
0
 /**
  *
  *
  * @param $ThemeName
  * @param bool $IsMobile
  * @return bool
  * @throws Exception
  */
 public function enableTheme($ThemeName, $IsMobile = false)
 {
     // Make sure to run the setup
     $this->testTheme($ThemeName);
     // Set the theme.
     $ThemeInfo = $this->getThemeInfo($ThemeName);
     $ThemeFolder = val('Folder', $ThemeInfo, '');
     $oldTheme = $IsMobile ? c('Garden.MobileTheme', 'mobile') : c('Garden.Theme', 'default');
     if ($ThemeFolder == '') {
         throw new Exception(t('The theme folder was not properly defined.'));
     } else {
         $Options = valr("{$ThemeName}.Options", $this->AvailableThemes());
         if ($Options) {
             if ($IsMobile) {
                 saveToConfig(array('Garden.MobileTheme' => $ThemeName, 'Garden.MobileThemeOptions.Name' => valr("{$ThemeName}.Name", $this->availableThemes(), $ThemeFolder)));
             } else {
                 saveToConfig(array('Garden.Theme' => $ThemeName, 'Garden.ThemeOptions.Name' => valr("{$ThemeName}.Name", $this->availableThemes(), $ThemeFolder)));
             }
         } else {
             if ($IsMobile) {
                 saveToConfig('Garden.MobileTheme', $ThemeName);
                 removeFromConfig('Garden.MobileThemeOptions');
             } else {
                 saveToConfig('Garden.Theme', $ThemeName);
                 removeFromConfig('Garden.ThemeOptions');
             }
         }
     }
     if ($oldTheme !== $ThemeName) {
         $this->themeHook($ThemeName, self::ACTION_ENABLE, true);
         Logger::event('theme_changed', Logger::NOTICE, 'The {themeType} theme changed from {oldTheme} to {newTheme}.', array('themeType' => $IsMobile ? 'mobile' : 'desktop', 'oldTheme' => $oldTheme, 'newTheme' => $ThemeName));
     }
     // Tell the locale cache to refresh itself.
     Gdn::locale()->refresh();
     return true;
 }
Esempio n. 16
0
 /**
  * Generates a multi-field form from a schema.
  *
  * @param array $Schema An array where each item of the array is a row that identifies a form field with the following information:
  *  - Name: The name of the form field.
  *  - Control: The type of control used for the field. This is one of the control methods on the Gdn_Form object.
  *  - LabelCode: The translation code for the label. Optional.
  *  - Description: An optional description for the field.
  *  - Items: If the control is a list control then its items are specified here.
  *  - Options: Additional options to be passed into the control.
  * @param type $Options Additional options to pass into the form.
  *  - Wrap: A two item array specifying the text to wrap the form in.
  *  - ItemWrap: A two item array specifying the text to wrap each form item in.
  */
 public function simple($Schema, $Options = array())
 {
     $Result = valr('Wrap.0', $Options, '<ul>');
     foreach ($Schema as $Index => $Row) {
         if (is_string($Row)) {
             $Row = array('Name' => $Index, 'Control' => $Row);
         }
         if (!isset($Row['Name'])) {
             $Row['Name'] = $Index;
         }
         if (!isset($Row['Options'])) {
             $Row['Options'] = array();
         }
         if (strtolower($Row['Control']) == 'callback') {
             $ItemWrap = '';
         } else {
             $ItemWrap = val('ItemWrap', $Options, array('<li class="' . $this->getStyle('form-group') . "\">\n", "\n</li>\n"));
         }
         $Result .= $ItemWrap[0];
         $LabelCode = self::labelCode($Row);
         $image = '';
         if (strtolower($Row['Control']) == 'imageupload') {
             $image = $this->currentImage($Row['Name'], $Row['Options']);
             $image = wrap($image, 'div', ['class' => 'image-wrap-label']);
         }
         $Description = val('Description', $Row, '');
         if ($Description) {
             $Description = wrap($Description, 'div', ['class' => 'description info']);
         }
         $Description .= $image;
         if ($Description) {
             $labelWrap = wrap($this->label($LabelCode, $Row['Name']) . $Description, 'div', ['class' => 'label-wrap']);
         } else {
             $labelWrap = wrap($this->label($LabelCode, $Row['Name']), 'div', ['class' => 'label-wrap']);
         }
         touchValue('Control', $Row, 'TextBox');
         switch (strtolower($Row['Control'])) {
             case 'categorydropdown':
                 $Result .= $this->label($LabelCode, $Row['Name']) . $Description . $this->categoryDropDown($Row['Name'], $Row['Options']);
                 break;
             case 'checkbox':
                 $Result .= $labelWrap . wrap($this->checkBox($Row['Name'], $LabelCode, $Row['Options']), 'div', ['class' => 'input-wrap']);
                 break;
             case 'toggle':
                 $Result .= $Description . $this->toggle($Row['Name'], $LabelCode, $Row['Options']);
                 break;
             case 'dropdown':
                 $Row['Options']['Wrap'] = true;
                 $Result .= $labelWrap . $this->dropDown($Row['Name'], $Row['Items'], $Row['Options']);
                 break;
             case 'radiolist':
                 $Result .= $labelWrap . wrap($this->radioList($Row['Name'], $Row['Items'], $Row['Options']), 'div', ['class' => 'input-wrap']);
                 break;
             case 'checkboxlist':
                 $Result .= $labelWrap . wrap($this->checkBoxList($Row['Name'], $Row['Items'], null, $Row['Options']), 'div', ['class' => 'input-wrap']);
                 break;
             case 'imageupload':
                 $Result .= $labelWrap . $this->imageUploadWrap($Row['Name'], $Row['Options']);
                 break;
             case 'textbox':
                 $Row['Options']['Wrap'] = true;
                 $Result .= $labelWrap . $this->textBox($Row['Name'], $Row['Options']);
                 break;
             case 'callback':
                 $Row['DescriptionHtml'] = $Description;
                 $Row['LabelCode'] = $LabelCode;
                 $Result .= call_user_func($Row['Callback'], $this, $Row);
                 break;
             default:
                 $Result .= "Error a control type of {$Row['Control']} is not supported.";
                 break;
         }
         $Result .= $ItemWrap[1];
     }
     $Result .= valr('Wrap.1', $Options, '</ul>');
     return $Result;
 }
Esempio n. 17
0
 /**
  * Do code checks on an uploaded addon.
  *
  * @param int $AddonID Addon to check.
  * @param bool|false $SaveVersionID Whether to save the version id.
  * @throws Exception Addon not found.
  */
 public function check($AddonID, $SaveVersionID = false)
 {
     $this->permission('Addons.Addon.Manage');
     if ($SaveVersionID !== false) {
         // Get the version data.
         $Version = $this->AddonModel->SQL->getWhere('AddonVersion', array('AddonVersionID' => $SaveVersionID))->firstRow(DATASET_TYPE_ARRAY);
         $this->AddonModel->save($Version);
         $this->Form->setValidationResults($this->AddonModel->validationResults());
     }
     $Addon = $this->AddonModel->getID($AddonID, false, ['GetVersions' => true]);
     $AddonTypes = Gdn::sql()->get('AddonType')->resultArray();
     $AddonTypes = Gdn_DataSet::index($AddonTypes, 'AddonTypeID');
     if (!$Addon) {
         throw notFoundException('Addon');
     }
     // Get the data for the most recent version of the addon.
     $upload = new Gdn_Upload();
     // Also used per version below.
     $Path = $upload->copyLocal($Addon['File']);
     $AddonData = arrayTranslate((array) $Addon, array('AddonID', 'AddonKey', 'Name', 'Type', 'Description', 'Requirements', 'Checked'));
     try {
         $FileAddonData = UpdateModel::analyzeAddon($Path);
         if ($FileAddonData) {
             $AddonData = array_merge($AddonData, arrayTranslate($FileAddonData, array('AddonKey' => 'File_AddonKey', 'Name' => 'File_Name', 'File_Type', 'Description' => 'File_Description', 'Requirements' => 'File_Requirements', 'Checked' => 'File_Checked')));
             $AddonData['File_Type'] = valr($FileAddonData['AddonTypeID'] . '.Label', $AddonTypes, 'Unknown');
         }
         $upload->delete($Path);
     } catch (Exception $Ex) {
         $AddonData['File_Error'] = $Ex->getMessage();
     }
     $this->setData('Addon', $AddonData);
     // Go through the versions and make sure we get the versions to check out.
     $Versions = array();
     foreach ($Addon['Versions'] as $Version) {
         $Version = $Version;
         $Path = $upload->copyLocal($Version['File']);
         try {
             $VersionData = arrayTranslate((array) $Version, array('AddonVersionID', 'Version', 'AddonKey', 'Name', 'MD5', 'FileSize', 'Checked'));
             $FileVersionData = UpdateModel::analyzeAddon($Path);
             $FileVersionData = arrayTranslate($FileVersionData, array('Version' => 'File_Version', 'AddonKey' => 'File_AddonKey', 'Name' => 'File_Name', 'MD5' => 'File_MD5', 'FileSize' => 'File_FileSize', 'Checked' => 'File_Checked'));
             $upload->delete($Path);
         } catch (Exception $Ex) {
             $FileVersionData = array('File_Error' => $Ex->getMessage());
         }
         $Versions[] = array_merge($VersionData, $FileVersionData);
     }
     $this->setData('Versions', $Versions);
     $this->addModule('AddonHelpModule');
     $this->render();
 }
Esempio n. 18
0
 /**
  * @return Gdn_SQLDriver $this
  */
 public function history($UpdateFields = true, $InsertFields = false)
 {
     $UserID = valr('User.UserID', Gdn::session(), Gdn::session()->UserID);
     if ($InsertFields) {
         $this->set('DateInserted', Gdn_Format::toDateTime())->set('InsertUserID', $UserID);
     }
     if ($UpdateFields) {
         $this->set('DateUpdated', Gdn_Format::toDateTime())->set('UpdateUserID', $UserID);
     }
     return $this;
 }
 /**
  * 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');
 }
Esempio n. 20
0
 /**
  * Override the sign in if Google+ is the default sign-in method.
  *
  * @param EntryController $Sender
  * @param array $Args
  */
 public function entryController_overrideSignIn_handler($Sender, $Args)
 {
     if (valr('DefaultProvider.AuthenticationKey', $Args) !== self::ProviderKey || !$this->isConfigured()) {
         return;
     }
     $Url = $this->authorizeUri(array('target' => $Args['Target']));
     $Args['DefaultProvider']['SignInUrl'] = $Url;
     //      redirect($Url);
 }
Esempio n. 21
0
 /**
  *
  *
  * @param $Url
  * @param null $Params
  * @param string $Method
  * @return mixed|string
  * @throws Gdn_UserException
  */
 public function api($Url, $Params = null, $Method = 'GET')
 {
     if (strpos($Url, '//') === false) {
         $Url = self::$BaseApiUrl . trim($Url, '/');
     }
     $Consumer = new OAuthConsumer(c('Plugins.Twitter.ConsumerKey'), c('Plugins.Twitter.Secret'));
     if ($Method == 'POST') {
         $Post = $Params;
     } else {
         $Post = null;
     }
     $AccessToken = $this->accessToken();
     //      var_dump($AccessToken);
     $Request = OAuthRequest::from_consumer_and_token($Consumer, $AccessToken, $Method, $Url, $Params);
     $SignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
     $Request->sign_request($SignatureMethod, $Consumer, $AccessToken);
     //      print_r($Params);
     $Curl = $this->_curl($Request, $Post);
     curl_setopt($Curl, CURLINFO_HEADER_OUT, true);
     //      curl_setopt($Curl, CURLOPT_VERBOSE, true);
     //      $fp = fopen("php://stdout", 'w');
     //      curl_setopt($Curl, CURLOPT_STDERR, $fp);
     $Response = curl_exec($Curl);
     $HttpCode = curl_getinfo($Curl, CURLINFO_HTTP_CODE);
     if ($Response == false) {
         $Response = curl_error($Curl);
     }
     //      echo curl_getinfo($Curl, CURLINFO_HEADER_OUT);
     //
     //      echo($Request->to_postdata());
     //      echo "\n\n";
     trace(curl_getinfo($Curl, CURLINFO_HEADER_OUT));
     trace($Response, 'Response');
     //      print_r(curl_getinfo($Curl));
     //      die();
     curl_close($Curl);
     Gdn::controller()->setJson('Response', $Response);
     if (strpos($Url, '.json') !== false) {
         $Result = @json_decode($Response, true) or $Response;
     } else {
         $Result = $Response;
     }
     //      print_r($Result);
     if ($HttpCode == '200') {
         return $Result;
     } else {
         throw new Gdn_UserException(valr('errors.0.message', $Result, $Response), $HttpCode);
     }
 }
Esempio n. 22
0
 /**
  * Generate an e-tag for the application from the versions of all of its enabled applications/plugins.
  *
  * @return string etag
  **/
 public static function eTag()
 {
     $data = [];
     $data['vanilla-core-' . APPLICATION_VERSION] = true;
     $plugins = Gdn::pluginManager()->enabledPlugins();
     foreach ($plugins as $info) {
         $data[strtolower("{$info['Index']}-plugin-{$info['Version']}")] = true;
     }
     $applications = Gdn::applicationManager()->enabledApplications();
     foreach ($applications as $info) {
         $data[strtolower("{$info['Index']}-app-{$info['Version']}")] = true;
     }
     // Add the desktop theme version.
     $info = Gdn::themeManager()->getThemeInfo(Gdn::themeManager()->desktopTheme());
     if (!empty($info)) {
         $version = val('Version', $info, 'v0');
         $data[strtolower("{$info['Index']}-theme-{$version}")] = true;
         if (Gdn::controller()->Theme && Gdn::controller()->ThemeOptions) {
             $filenames = valr('Styles.Value', Gdn::controller()->ThemeOptions);
             $data[$filenames] = true;
         }
     }
     // Add the mobile theme version.
     $info = Gdn::themeManager()->getThemeInfo(Gdn::themeManager()->mobileTheme());
     if (!empty($info)) {
         $version = val('Version', $info, 'v0');
         $data[strtolower("{$info['Index']}-theme-{$version}")] = true;
     }
     Gdn::pluginManager()->EventArguments['ETagData'] =& $data;
     $suffix = '';
     Gdn::pluginManager()->EventArguments['Suffix'] =& $suffix;
     Gdn::pluginManager()->fireAs('AssetModel')->fireEvent('GenerateETag');
     unset(Gdn::pluginManager()->EventArguments['ETagData']);
     ksort($data);
     $result = substr(md5(implode(',', array_keys($data))), 0, 8) . $suffix;
     return $result;
 }
Esempio n. 23
0
 /**
  * Send welcome email to user.
  *
  * @param $UserID
  * @param $Password
  * @param string $RegisterType
  * @param null $AdditionalData
  * @throws Exception
  */
 public function sendWelcomeEmail($UserID, $Password, $RegisterType = 'Add', $AdditionalData = null)
 {
     $Session = Gdn::session();
     $Sender = $this->getID($Session->UserID);
     $User = $this->getID($UserID);
     if (!ValidateEmail($User->Email)) {
         return;
     }
     $AppTitle = Gdn::config('Garden.Title');
     $Email = new Gdn_Email();
     $Email->subject(sprintf(t('[%s] Welcome Aboard!'), $AppTitle));
     $Email->to($User->Email);
     $Data = array();
     $Data['User'] = arrayTranslate((array) $User, array('UserID', 'Name', 'Email'));
     $Data['Sender'] = arrayTranslate((array) $Sender, array('Name', 'Email'));
     $Data['Title'] = $AppTitle;
     if (is_array($AdditionalData)) {
         $Data = array_merge($Data, $AdditionalData);
     }
     $Data['EmailKey'] = valr('Attributes.EmailKey', $User);
     // Check for the new email format.
     if (($EmailFormat = t("EmailWelcome{$RegisterType}", '#')) != '#') {
         $Message = formatString($EmailFormat, $Data);
     } else {
         $Message = sprintf(t('EmailWelcome'), $User->Name, $Sender->Name, $AppTitle, ExternalUrl('/'), $Password, $User->Email);
     }
     // Add the email confirmation key.
     if ($Data['EmailKey']) {
         $Message .= "\n\n" . FormatString(t('EmailConfirmEmail', self::DEFAULT_CONFIRM_EMAIL), $Data);
     }
     $Message = $this->_addEmailHeaderFooter($Message, $Data);
     $Email->message($Message);
     $Email->send();
 }
Esempio n. 24
0
 /**
  * Save tags when saving a discussion.
  */
 public function discussionModel_afterSaveDiscussion_handler($Sender)
 {
     $FormPostValues = val('FormPostValues', $Sender->EventArguments, array());
     $DiscussionID = val('DiscussionID', $Sender->EventArguments, 0);
     $CategoryID = valr('Fields.CategoryID', $Sender->EventArguments, 0);
     //      $IsInsert = val('Insert', $Sender->EventArguments);
     $RawFormTags = val('Tags', $FormPostValues, '');
     $FormTags = TagModel::splitTags($RawFormTags);
     // If we're associating with categories
     $CategorySearch = c('Plugins.Tagging.CategorySearch', false);
     if ($CategorySearch) {
         $CategoryID = val('CategoryID', $FormPostValues, false);
     }
     // Let plugins add their information getting saved.
     $Types = array('');
     $this->EventArguments['Data'] = $FormPostValues;
     $this->EventArguments['Tags'] =& $FormTags;
     $this->EventArguments['Types'] =& $Types;
     $this->EventArguments['CategoryID'] = $CategoryID;
     $this->fireEvent('SaveDiscussion');
     // Save the tags to the db.
     TagModel::instance()->saveDiscussion($DiscussionID, $FormTags, $Types, $CategoryID);
 }
Esempio n. 25
0
 /**
  * Get a value out of the controller's data array.
  *
  * @param string $Path The path to the data.
  * @param mixed $Default The default value if the data array doesn't contain the path.
  * @return mixed
  * @see GetValueR()
  */
 public function data($Path, $Default = '')
 {
     $Result = valr($Path, $this->Data, $Default);
     return $Result;
 }
Esempio n. 26
0
 /**
  * Handle comment form Resolved checkbox & new user comments.
  *
  * @return void
  */
 public function commentModel_afterSaveComment_handler($sender, $args)
 {
     $resolved = valr('FormPostValues.Resolved', $args);
     $discussionID = val('DiscussionID', $args['FormPostValues']);
     $discussion = array('DiscussionID' => $discussionID);
     if (!checkPermission('Plugins.Resolved.Manage')) {
         // Unset Resolved flag
         $this->resolve($discussion, 0);
     } else {
         if ($resolved) {
             // Set Resolved flag
             $this->resolve($discussion, 1);
         }
     }
 }
 /**
  * Edit a user account.
  *
  * @since 2.0.0
  * @access public
  * @param int $UserID Unique ID.
  */
 public function edit($UserID)
 {
     $this->permission('Garden.Users.Edit');
     // Page setup
     $this->addJsFile('user.js');
     $this->title(t('Edit User'));
     $this->addSideMenu('dashboard/user');
     // Only admins can reassign roles
     $RoleModel = new RoleModel();
     $AllRoles = $RoleModel->getArray();
     $RoleData = $RoleModel->getAssignable();
     $UserModel = new UserModel();
     $User = $UserModel->getID($UserID, DATASET_TYPE_ARRAY);
     // Determine if username can be edited
     $CanEditUsername = (bool) c("Garden.Profile.EditUsernames") || Gdn::session()->checkPermission('Garden.Users.Edit');
     $this->setData('_CanEditUsername', $CanEditUsername);
     // Determine if emails can be edited
     $CanEditEmail = Gdn::session()->checkPermission('Garden.Users.Edit');
     $this->setData('_CanEditEmail', $CanEditEmail);
     // Decide if they have ability to confirm users
     $Confirmed = (bool) valr('Confirmed', $User);
     $CanConfirmEmail = UserModel::RequireConfirmEmail() && Gdn::session()->checkPermission('Garden.Users.Edit');
     $this->setData('_CanConfirmEmail', $CanConfirmEmail);
     $this->setData('_EmailConfirmed', $Confirmed);
     $User['ConfirmEmail'] = (int) $Confirmed;
     // Determine whether user being edited is privileged (can escalate permissions)
     $UserModel = new UserModel();
     $EditingPrivilegedUser = $UserModel->checkPermission($User, 'Garden.Settings.Manage');
     // Determine our password reset options
     // Anyone with user editing my force reset over email
     $this->ResetOptions = array(0 => t('Keep current password.'), 'Auto' => t('Force user to reset their password and send email notification.'));
     // Only admins may manually reset passwords for other admins
     if (checkPermission('Garden.Settings.Manage') || !$EditingPrivilegedUser) {
         $this->ResetOptions['Manual'] = t('Manually set user password. No email notification.');
     }
     // Set the model on the form.
     $this->Form->setModel($UserModel);
     // Make sure the form knows which item we are editing.
     $this->Form->addHidden('UserID', $UserID);
     try {
         $AllowEditing = true;
         $this->EventArguments['AllowEditing'] =& $AllowEditing;
         $this->EventArguments['TargetUser'] =& $User;
         // These are all the 'effective' roles for this edit action. This list can
         // be trimmed down from the real list to allow subsets of roles to be
         // edited.
         $this->EventArguments['RoleData'] =& $RoleData;
         $UserRoleData = $UserModel->getRoles($UserID)->resultArray();
         $RoleIDs = array_column($UserRoleData, 'RoleID');
         $RoleNames = array_column($UserRoleData, 'Name');
         $UserRoleData = arrayCombine($RoleIDs, $RoleNames);
         $this->EventArguments['UserRoleData'] =& $UserRoleData;
         $this->fireEvent("BeforeUserEdit");
         $this->setData('AllowEditing', $AllowEditing);
         $this->Form->setData($User);
         if ($this->Form->authenticatedPostBack()) {
             if (!$CanEditUsername) {
                 $this->Form->setFormValue("Name", $User['Name']);
             }
             // Allow mods to confirm/unconfirm emails
             $this->Form->removeFormValue('Confirmed');
             $Confirmation = $this->Form->getFormValue('ConfirmEmail', null);
             $Confirmation = !is_null($Confirmation) ? (bool) $Confirmation : null;
             if ($CanConfirmEmail && is_bool($Confirmation)) {
                 $this->Form->setFormValue('Confirmed', (int) $Confirmation);
             }
             $ResetPassword = $this->Form->getValue('ResetPassword', false);
             // If we're an admin or this isn't a privileged user, allow manual setting of password
             $AllowManualReset = checkPermission('Garden.Settings.Manage') || !$EditingPrivilegedUser;
             if ($ResetPassword == 'Manual' && $AllowManualReset) {
                 // If a new password was specified, add it to the form's collection
                 $NewPassword = $this->Form->getValue('NewPassword', '');
                 $this->Form->setFormValue('Password', $NewPassword);
             }
             // Role changes
             // These are the new roles the editing user wishes to apply to the target
             // user, adjusted for his ability to affect those roles
             $RequestedRoles = $this->Form->getFormValue('RoleID');
             if (!is_array($RequestedRoles)) {
                 $RequestedRoles = array();
             }
             $RequestedRoles = array_flip($RequestedRoles);
             $UserNewRoles = array_intersect_key($RoleData, $RequestedRoles);
             // These roles will stay turned on regardless of the form submission contents
             // because the editing user does not have permission to modify them
             $ImmutableRoles = array_diff_key($AllRoles, $RoleData);
             $UserImmutableRoles = array_intersect_key($ImmutableRoles, $UserRoleData);
             // Apply immutable roles
             foreach ($UserImmutableRoles as $IMRoleID => $IMRoleName) {
                 $UserNewRoles[$IMRoleID] = $IMRoleName;
             }
             // Put the data back into the forum object as if the user had submitted
             // this themselves
             $this->Form->setFormValue('RoleID', array_keys($UserNewRoles));
             if ($this->Form->save(array('SaveRoles' => true)) !== false) {
                 if ($this->Form->getValue('ResetPassword', '') == 'Auto') {
                     $UserModel->PasswordRequest($User['Email']);
                     $UserModel->setField($UserID, 'HashMethod', 'Reset');
                 }
                 $this->informMessage(t('Your changes have been saved.'));
             }
             $UserRoleData = $UserNewRoles;
         }
     } catch (Exception $Ex) {
         $this->Form->addError($Ex);
     }
     $this->setData('User', $User);
     $this->setData('Roles', $RoleData);
     $this->setData('UserRoles', $UserRoleData);
     $this->render();
 }
Esempio n. 28
0
 /**
  * Saves the category tree based on a provided tree array. We are using the
  * Nested Set tree model.
  *
  *   TreeArray comes in the format:
  *   '0' ...
  *     'item_id' => "root"
  *     'parent_id' => "none"
  *     'depth' => "0"
  *     'left' => "1"
  *     'right' => "34"
  *   '1' ...
  *     'item_id' => "1"
  *     'parent_id' => "root"
  *     'depth' => "1"
  *     'left' => "2"
  *     'right' => "3"
  *   etc...
  *
  * @ref http://articles.sitepoint.com/article/hierarchical-data-database/2
  * @ref http://en.wikipedia.org/wiki/Nested_set_model
  *
  * @since 2.0.16
  * @access public
  *
  * @param array $TreeArray A fully defined nested set model of the category tree.
  */
 public function saveTree($TreeArray)
 {
     // Grab all of the categories so that permissions can be properly saved.
     $PermTree = $this->SQL->select('CategoryID, PermissionCategoryID, TreeLeft, TreeRight, Depth, Sort, ParentCategoryID')->from('Category')->get();
     $PermTree = $PermTree->Index($PermTree->resultArray(), 'CategoryID');
     // The tree must be walked in order for the permissions to save properly.
     usort($TreeArray, array('CategoryModel', '_TreeSort'));
     $Saves = array();
     foreach ($TreeArray as $I => $Node) {
         $CategoryID = val('item_id', $Node);
         if ($CategoryID == 'root') {
             $CategoryID = -1;
         }
         $ParentCategoryID = val('parent_id', $Node);
         if (in_array($ParentCategoryID, array('root', 'none'))) {
             $ParentCategoryID = -1;
         }
         $PermissionCategoryID = valr("{$CategoryID}.PermissionCategoryID", $PermTree, 0);
         $PermCatChanged = false;
         if ($PermissionCategoryID != $CategoryID) {
             // This category does not have custom permissions so must inherit its parent's permissions.
             $PermissionCategoryID = valr("{$ParentCategoryID}.PermissionCategoryID", $PermTree, 0);
             if ($CategoryID != -1 && !valr("{$ParentCategoryID}.Touched", $PermTree)) {
                 throw new Exception("Category {$ParentCategoryID} not touched before touching {$CategoryID}.");
             }
             if ($PermTree[$CategoryID]['PermissionCategoryID'] != $PermissionCategoryID) {
                 $PermCatChanged = true;
             }
             $PermTree[$CategoryID]['PermissionCategoryID'] = $PermissionCategoryID;
         }
         $PermTree[$CategoryID]['Touched'] = true;
         // Only update if the tree doesn't match the database.
         $Row = $PermTree[$CategoryID];
         if ($Node['left'] != $Row['TreeLeft'] || $Node['right'] != $Row['TreeRight'] || $Node['depth'] != $Row['Depth'] || $ParentCategoryID != $Row['ParentCategoryID'] || $Node['left'] != $Row['Sort'] || $PermCatChanged) {
             $Set = array('TreeLeft' => $Node['left'], 'TreeRight' => $Node['right'], 'Depth' => $Node['depth'], 'Sort' => $Node['left'], 'ParentCategoryID' => $ParentCategoryID, 'PermissionCategoryID' => $PermissionCategoryID);
             $this->SQL->update('Category', $Set, array('CategoryID' => $CategoryID))->put();
             $Saves[] = array_merge(array('CategoryID' => $CategoryID), $Set);
         }
     }
     self::ClearCache();
     return $Saves;
 }
Esempio n. 29
0
 /**
  *
  * @param $sender Sending controller instance.
  * @param array $args Event arguments.
  */
 public function base_commentInfo_handler($sender, $args)
 {
     $Type = val('Type', $args);
     if ($Type != 'Comment') {
         return;
     }
     $QnA = valr('Comment.QnA', $args);
     if ($QnA && ($QnA == 'Accepted' || Gdn::session()->checkPermission('Garden.Moderation.Manage'))) {
         $Title = t("QnA {$QnA} Answer", "{$QnA} Answer");
         echo ' <span class="Tag QnA-Box QnA-' . $QnA . '" title="' . htmlspecialchars($Title) . '"><span>' . $Title . '</span></span> ';
     }
 }
 /**
  * Gets or sets a user's preference. This method is meant for ajax calls.
  * @since 2.1
  * @param string $Key The name of the preference.
  */
 public function preference($Key = false)
 {
     $this->permission('Garden.SignIn.Allow');
     if ($this->Form->authenticatedPostBack()) {
         $Data = $this->Form->formValues();
         Gdn::userModel()->SavePreference(Gdn::session()->UserID, $Data);
     } else {
         $User = Gdn::userModel()->getID(Gdn::session()->UserID, DATASET_TYPE_ARRAY);
         $Pref = valr($Key, $User['Preferences'], null);
         $this->setData($Key, $Pref);
     }
     $this->render('Blank', 'Utility');
 }