/** * Takes a route and prepends the web root (expects "/controller/action/params" as $Path). * * @param array $Params The parameters passed into the function. * The parameters that can be passed to this function are as follows. * - <b>path</b>: The relative path for the url. There are some special paths that can be used to return "intelligent" links: * - <b>signinout</b>: This will return a signin/signout url that will toggle depending on whether or not the user is already signed in. When this path is given the text is automaticall set. * - <b>withdomain</b>: Whether or not to add the domain to the url. * - <b>text</b>: Html text to be put inside an anchor. If this value is set then an html <a></a> is returned rather than just a url. * - <b>id, class, etc.</b>: When an anchor is generated then any other attributes are passed through and will be written in the resulting tag. * @param Smarty $Smarty The smarty object rendering the template. * @return The url. */ function smarty_function_link($Params, &$Smarty) { $Path = val('path', $Params, '', true); $Text = val('text', $Params, '', true); $NoTag = val('notag', $Params, false, true); $CustomFormat = val('format', $Params, false, true); if (!$Text && $Path != 'signinout' && $Path != 'signin') { $NoTag = true; } if ($CustomFormat) { $Format = $CustomFormat; } elseif ($NoTag) { $Format = '%url'; } else { $Format = '<a href="%url" class="%class">%text</a>'; } $Options = array(); if (isset($Params['withdomain'])) { $Options['WithDomain'] = $Params['withdomain']; } if (isset($Params['class'])) { $Options['class'] = $Params['class']; } if (isset($Params['tk'])) { $Options['TK'] = $Params['tk']; } if (isset($Params['target'])) { $Options['Target'] = $Params['target']; } $Result = Gdn_Theme::link($Path, $Text, $Format, $Options); return $Result; }
/** * Map an API request to a resource * * @since 0.1.0 * @access public * @param Gdn_Dispatcher $sender * @return void */ public function Gdn_Dispatcher_beforeDispatch_handler($sender) { $path = APIEngine::getRequestURI(); // Set the call and resource paths if they exist $call = val(0, $path); $resource = val(1, $path); // Abandon the dispatch if this isn't an API call with a valid resource if ($call != "api" || !$resource) { return; } APIEngine::setRequestHeaders(); try { // Mark the dispatch with the API version $sender->API = c("API.Version", "Undefined"); // Attempt dispatching the API request APIEngine::dispatchRequest(); } catch (Exception $exception) { // As we can"t pass an object to WithControllerMethod(), we extract // the values we need manually before passing them on. The exception // message is Base64 encoded as WithControllerMethod() mangles // the formatting. $code = $exception->getCode(); $message = base64_encode($exception->getMessage()); $arguments = [$code, $message]; // Call the Exception method if an exception is thrown Gdn::request()->withControllerMethod("API", "Exception", $arguments); } }
/** * * * @param array $Params * @param object $Smarty * @return string */ function smarty_function_signin_link($Params, &$Smarty) { if (!Gdn::session()->isValid()) { $Wrap = val('wrap', $Params, 'li'); return Gdn_Theme::link('signinout', val('text', $Params, ''), val('format', $Params, wrap('<a href="%url" rel="nofollow" class="%class">%text</a>', $Wrap)), $Params); } }
/** * Token-based, per-request authentication * * This method takes the entire request string and turns the query into an * array of data. It then uses all the data to generate a signature the same * way it got generated on the client. If the server signature and client * token match, the client is considered legimate and the request is served. * * Based on initial work by Diego Zanella * @link http://careers.stackoverflow.com/diegozanella * * @since 0.1.0 * @access public * @throws Exception * @return void * @static */ public static function authenticateRequest() { $username = getIncomingValue("username"); $email = getIncomingValue("email"); if (!$username && !$email) { throw new Exception(t("API.Error.User.Missing"), 401); } if (!($userID = static::getUserID($username, $email))) { throw new Exception(t("API.Error.User.Invalid"), 401); } if (!($timestamp = getIncomingValue("timestamp"))) { throw new Exception(t("API.Error.Timestamp.Missing"), 401); } // Make sure that request is still valid if (abs($timestamp - time()) > c("API.Expiration")) { throw new Exception(t("API.Error.Timestamp.Invalid"), 401); } if (!($token = getIncomingValue("token"))) { throw new Exception(t("API.Error.Token.Missing"), 401); } $parsedUrl = parse_url(Gdn::request()->pathAndQuery()); // Turn the request query data into an array to be used in the token // generation parse_str(val("query", $parsedUrl, []), $data); // Unset the values we don't want to include in the token generation unset($data["token"], $data["DeliveryType"], $data["DeliveryMethod"]); if ($token != ($signature = static::generateSignature($data))) { throw new Exception(t("API.Error.Token.Invalid"), 401); } // Now that the client has been thoroughly verified, start a session for // the duration of the request using the User ID specified earlier if ($token == $signature) { Gdn::session()->start(intval($userID), false); } }
/** * * * @param $Data */ function _checkTable($Data) { echo "<table class='Data' width='100%' style='table-layout: fixed;'>\n"; echo "<thead><tr><td width='20%'>Field</td><td width='45%'>Current</td><td width='35%'>File</td></tr></thead>"; $First = true; foreach ($Data as $Key => $Value) { if (stringBeginsWith($Key, 'File_') || is_array($Value) || $Key == 'Name') { continue; } $Value = Gdn_Format::html($Value); $FileValue = Gdn_Format::html(val('File_' . $Key, $Data)); if ($Key == 'MD5') { $Value = substr($Value, 0, 10); $FileValue = substr($FileValue, 0, 10); } if ($Key == 'FileSize') { $Value = Gdn_Upload::FormatFileSize($Value); } echo "<tr><td>{$Key}</td><td>{$Value}</td>"; if ($Error = val('File_Error', $Data)) { if ($First) { echo '<td rowspan="4">', htmlspecialchars($Error), '</td>'; } } else { echo "<td>{$FileValue}</td></tr>"; } echo "\n"; $First = false; } echo '</table>'; }
/** * Register API endpoints * * @since 0.1.0 * @access public * @param array $data * @return void * @static */ public static function register($data) { static::get("/bans", ["controller" => "Settings", "method" => "bans", "arguments" => ["Page" => val("Page", $data)]]); static::post("/bans", ["controller" => "Settings", "method" => "bans", "arguments" => ["Action" => "add"]]); static::put("/bans/[i:ID]", ["controller" => "Settings", "method" => "bans", "arguments" => ["Action" => "edit"]]); static::delete("/bans/[i:ID]", ["controller" => "Settings", "method" => "bans", "arguments" => ["Action" => "delete"]]); }
/** * Calculate the user's default photo url. * * @param array|object $user The user to examine. * @param array $options An array of options. * - Size: The size of the photo. * @return string Returns the vanillicon url for the user. */ function userPhotoDefaultUrl($user, $options = array()) { static $iconSize = null, $type = null; if ($iconSize === null) { $thumbSize = c('Garden.Thumbnail.Size'); $iconSize = $thumbSize <= 50 ? 50 : 100; } if ($type === null) { $type = c('Plugins.Vanillicon.Type'); } $size = val('Size', $options, $iconSize); $email = val('Email', $user); if (!$email) { $email = val('UserID', $user, 100); } $hash = md5($email); $px = substr($hash, 0, 1); switch ($type) { case 'v2': $photoUrl = "//w{$px}.vanillicon.com/v2/{$hash}.svg"; break; default: $photoUrl = "//w{$px}.vanillicon.com/{$hash}_{$size}.png"; break; } return $photoUrl; }
public function UserModel_AfterSave_Handler($Sender) { $FormValues = $Sender->EventArguments['FormPostValues']; $UserID = val('UserID', $FormValues, 0); $ThemeChooser = val('ThemeChooser', $FormValues, false); $this->SetUserMeta($UserID, 'Theme', $ThemeChooser); }
/** * Writes the search box to the page. * * @param array The parameters passed into the function. This currently takes no parameters. * @param $smarty The smarty object rendering the template. * @return The url. */ function smarty_function_searchbox($params, &$smarty) { $placeholder = array_key_exists('placeholder', $params) ? val('placeholder', $params, '', true) : t('SearchBoxPlaceHolder', 'Search'); $form = Gdn::factory('Form'); $result = $form->open(array('action' => url('/search'), 'method' => 'get')) . $form->textBox('Search', array('placeholder' => $placeholder, 'accesskey' => '/')) . $form->button('Go', array('Name' => '')) . $form->close(); return $result; }
/** * 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 ''; }
/** * Renders an asset from the controller. * * @param array $Params The parameters passed into the function. * The parameters that can be passed to this function are as follows. * - <b>name</b>: The name of the asset. * - <b>tag</b>: The type of tag to wrap the asset in. * - <b>id</b>: The id of the tag if different than the name. * @param object $Smarty Smarty The smarty object rendering the template. * @return string The rendered asset. */ function smarty_function_asset($Params, &$Smarty) { $Name = val('name', $Params); $Tag = val('tag', $Params, ''); $Id = val('id', $Params, $Name); $Class = val('class', $Params, ''); if ($Class != '') { $Class = ' class="' . $Class . '"'; } $Controller = $Smarty->Controller; $Controller->EventArguments['AssetName'] = $Name; $Result = ''; ob_start(); $Controller->fireEvent('BeforeRenderAsset'); $Result .= ob_get_clean(); $Asset = $Controller->getAsset($Name); if (is_object($Asset)) { $Asset->AssetName = $Name; if (val('Visible', $Asset, true)) { $Asset = $Asset->toString(); } else { $Asset = ''; } } if (!empty($Tag)) { $Result .= '<' . $Tag . ' id="' . $Id . '"' . $Class . '>' . $Asset . '</' . $Tag . '>'; } else { $Result .= $Asset; } ob_start(); $Controller->fireEvent('AfterRenderAsset'); $Result .= ob_get_clean(); return $Result; }
/** * * * @param array $Params * @param object $Smarty * @return string */ function smarty_function_module($Params, &$Smarty) { $Name = val('name', $Params); unset($Params['name']); $Result = Gdn_Theme::module($Name, $Params); return $Result; }
public function events() { if (!env('student')) { redirect('m=login'); } $updisciplineId = val($_REQUEST, 'updisciplineId'); $learningMode = val($_REQUEST, 'learningMode'); if (empty($updisciplineId) || empty($learningMode)) { throw new Exception('Missed required param', 404); } $updiscipline = entry_sql('SELECT * FROM updiscipline WHERE updisciplineId=:updisciplineId', array(':updisciplineId' => $updisciplineId)); if (empty($updiscipline)) { throw new Exception('Updiscipline not found', 404); } $groupPeriod = entry_sql('SELECT gp.* FROM group_history gh INNER JOIN group_period gp USING(groupPeriodId) WHERE gh.studentId=:studentId AND gp.sersemester=:sersemester', array('studentId' => studentId(), 'sersemester' => $updiscipline['sersemester'])); if (empty($groupPeriod)) { throw new Exception('Cannot detect groupPeriod', 404); } $events = entries_sql('SELECT * FROM event WHERE updisciplineId=:updisciplineId AND groupPeriodId=:groupPeriodId AND learningMode=:learningMode', array('groupPeriodId' => $groupPeriod['groupPeriodId'], 'updisciplineId' => $updiscipline['updisciplineId'], 'learningMode' => $learningMode)); array_walk($events, function (&$event, $k, $studentId) { $event['c'] = material::i($event['instanceType'])->c(); $event['grade'] = material::i($event['instanceType'])->get_grade($event['instanceId'], $studentId); }, studentId()); env('breadcrumbs', array(array(lng('up:disciplines'), '/?c=up'), array($updiscipline['disciplineName'], '/?c=up&m=events&updisciplineId=' . $updisciplineId . '&learningMode=' . $learningMode), lng('up:events'))); tpl('up/events', array('updiscipline' => $updiscipline, 'events' => $events, 'result' => entry_sql('SELECT * FROM result WHERE studentId=:studentId AND updisciplineId=:updisciplineId AND learningMode=:learningMode', array('studentId' => studentId(), 'updisciplineId' => $updiscipline['updisciplineId'], 'learningMode' => $learningMode)))); }
/** * Is the application/plugin/theme removable? * * @param string $Type self::TYPE_APPLICATION or self::TYPE_PLUGIN or self::TYPE_THEME * @param string $Name * @return boolean */ public static function isRemovable($Type, $Name) { switch ($Type) { case self::TYPE_APPLICATION: $ApplicationManager = Gdn::Factory('ApplicationManager'); if ($IsRemovable = !array_key_exists($Name, $ApplicationManager->EnabledApplications())) { $ApplicationInfo = val($Name, $ApplicationManager->AvailableApplications(), array()); $ApplicationFolder = val('Folder', $ApplicationInfo, ''); $IsRemovable = IsWritable(PATH_APPLICATIONS . DS . $ApplicationFolder); } break; case self::TYPE_PLUGIN: if ($IsRemovable = !array_key_exists($Name, Gdn::pluginManager()->EnabledPlugins())) { $PluginInfo = val($Name, Gdn::pluginManager()->AvailablePlugins(), false); $PluginFolder = val('Folder', $PluginInfo, false); $IsRemovable = IsWritable(PATH_PLUGINS . DS . $PluginFolder); } break; case self::TYPE_THEME: // TODO $IsRemovable = false; break; } return $IsRemovable; }
/** * * * @param array $Params * @param object $Smarty * @return string */ function smarty_function_nomobile_link($Params, &$Smarty) { $Path = val('path', $Params, '', true); $Text = val('text', $Params, '', true); $Wrap = val('wrap', $Params, 'li'); return Gdn_Theme::link('profile/nomobile', val('text', $Params, t("Full Site")), val('format', $Params, wrap('<a href="%url" class="%class">%text</a>', $Wrap))); }
/** * * * @param $JsonResponse * @param $RawResponse */ public function securityTokenCallback($JsonResponse, $RawResponse) { $SecurityToken = val('SecurityToken', $JsonResponse, null); if (!is_null($SecurityToken)) { $this->securityToken($SecurityToken); } }
/** * * * @param array $Params * @param object $Smarty * @return string */ function smarty_function_dashboard_link($Params, &$Smarty) { $Path = val('path', $Params, '', true); $Text = val('text', $Params, '', true); $Wrap = val('wrap', $Params, 'li'); return Gdn_Theme::link('dashboard', val('text', $Params, ''), val('format', $Params, wrap('<a href="%url" class="%class">%text</a>', $Wrap))); }
/** * Build HTML. * * @return string HTML. */ public function toString() { if ($this->_UserData->numRows() == 0) { return ''; } $String = ''; ob_start(); ?> <div class="Box"> <?php echo panelHeading(t('In this Discussion')); ?> <ul class="PanelInfo"> <?php foreach ($this->_UserData->Result() as $User) { ?> <li> <?php echo anchor(wrap(wrap(Gdn_Format::date($User->DateLastActive, 'html')), 'span', array('class' => 'Aside')) . ' ' . wrap(wrap(val('Name', $User), 'span', array('class' => 'Username')), 'span'), userUrl($User)); ?> </li> <?php } ?> </ul> </div> <?php $String = ob_get_contents(); @ob_end_clean(); return $String; }
function writeConditionEdit($Condition, $Sender) { $Px = $Sender->Prefix; $Form = new Gdn_Form(); $Type = val(0, $Condition, ''); $Field = val(1, $Condition, ''); $Expr = val(2, $Condition, ''); echo '<tr>'; // Type. echo '<td>', $Form->DropDown($Px . 'Type[]', $Sender->Types, array('Value' => $Type, 'Class' => 'CondType')), '</td>'; echo '<td>'; // Permission fields. echo '<div class="Cond_permission"' . _DN($Type, Gdn_Condition::PERMISSION) . '>', $Form->DropDown($Px . 'PermissionField[]', $Sender->Permissions, array('Value' => $Type == Gdn_Condition::PERMISSION ? $Field : '')), '</div>'; // Role fields. echo '<div class="Cond_role"' . _DN($Type, Gdn_Condition::ROLE) . '>', $Form->DropDown($Px . 'RoleField[]', $Sender->Roles, array('Value' => $Type == Gdn_Condition::ROLE ? $Field : '')), '</div>'; // Textbox field. echo '<div class="Cond_request"' . _DN($Type, Gdn_Condition::REQUEST) . '>', $Form->textBox($Px . 'Field[]', array('Value' => $Type == Gdn_Condition::REQUEST ? $Field : '')); '</div>'; echo '</td>'; // Expression. echo '<td>', '<div class="Cond_request"' . _DN($Type, Gdn_Condition::REQUEST) . '>', $Form->textBox($Px . 'Expr[]', array('Value' => $Type == Gdn_Condition::REQUEST ? $Expr : '')), '</div>', '</td>'; // Buttons. echo '<td align="right">', '<a href="#" class="DeleteCondition">', t('Delete'), '</a></td>'; echo '</tr>'; }
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)); } }
/** * Add numbering index to discussion's comments. * * @param DiscussionController $sender Sending controller instance. * @param array $args Event arguments. */ public function discussionController_commentInfo_handler($sender, $args) { static $number = 2; $offset = val('Offset', $sender, 0); $commentNumber = $offset + $number; echo wrap(anchor('#' . $commentNumber, commentUrl($args['Comment'])), 'span', ['Class' => 'MItem PostNumbering Num-' . $commentNumber]); $number += 1; }
/** * * * @param $Sender * @param $Args */ public function categoriesController_afterDiscussionLabels_handler($Sender, $Args) { if (!$this->hasLayoutTables() || isMobile()) { if (val('FirstUser', $Args)) { echo '<span class="MItem DiscussionAuthor">' . userAnchor(val('FirstUser', $Args)) . '</span>'; } } }
/** * Register API endpoints * * @since 0.1.0 * @access public * @param array $data * @return void * @static */ public static function register($data) { static::get("/", ["controller" => "Messages", "method" => "all", "authenticate" => true, "arguments" => ["Page" => val("Page", $data)]]); static::get("/[i:ConversationID]", ["controller" => "Messages", "authenticate" => true, "arguments" => ["Offset" => val("Offset", $data), "Limit" => val("Limit", $data)]]); static::post("/", ["controller" => "Messages", "method" => "add"]); static::post("/[i:ConversationID]/messages", ["controller" => "Messages", "method" => "addMessage"]); static::delete("/[i:ConversationID]", ["controller" => "Messages", "method" => "clear", "arguments" => ["TransientKey" => Gdn::session()->transientKey()]]); }
/** * * * @param $group * @param $text * @param bool $permission * @param array $attributes * @return $this|void */ public function addItem($group, $text, $permission = false, $attributes = array()) { if ($permission === false) { $permission = true; } $this->siteNavModule->addGroupIf($permission, $text, slugify($group), val('class', $attributes), '', $attributes); return $this; }
/** * * * @param $Sender * @param $Args */ public function categoriesController_afterDiscussionLabels_handler($Sender, $Args) { if (c('Vanilla.Discussions.Layout') != 'table') { if (val('FirstUser', $Args)) { echo '<span class="MItem DiscussionAuthor">' . userAnchor(val('FirstUser', $Args)) . '</span>'; } } }
/** * Update the configuration. * * @return void */ protected function config() { saveToConfig('Garden.Cookie.Salt', RandomString(10)); $ApplicationInfo = []; include CombinePaths([PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'about.php']); // Detect Internet connection for CDNs $Disconnected = !(bool) @fsockopen('ajax.googleapis.com', 80); saveToConfig(['Garden.Version' => arrayValue('Version', val('Dashboard', $ApplicationInfo, []), 'Undefined'), 'Garden.Cdns.Disable' => $Disconnected, 'Garden.CanProcessImages' => function_exists('gd_info'), 'EnabledPlugins.HtmLawed' => 'HtmLawed']); }
/** * Register API endpoints * * @since 0.1.0 * @access public * @param array $data * @return void * @static */ public static function register($data) { static::get("/", ["controller" => "Activity"]); static::get("/[i:ActivityID]", ["controller" => "Activity", "method" => "item"]); static::post("/", ["controller" => "Activity", "method" => "post", "arguments" => ["Notify" => val("Notify", $data)]]); static::post("/[i:ActivityID]/comments", ["controller" => "Activity", "method" => "comment"]); static::delete("/[i:ActivityID]", ["controller" => "Activity", "method" => "delete", "arguments" => ["TransientKey" => Gdn::session()->transientKey()]]); static::delete("/comments/[i:ID]", ["controller" => "Activity", "method" => "deleteComment", "arguments" => ["TK" => Gdn::session()->transientKey()]]); }
/** * Render a breadcrumb trail for the user based on the page they are on. * * @param array $Params * @param object $Smarty * @return string */ function smarty_function_breadcrumbs($Params, &$Smarty) { $Breadcrumbs = $Smarty->Controller->data('Breadcrumbs'); if (!is_array($Breadcrumbs)) { $Breadcrumbs = array(); } $Options = arrayTranslate($Params, array('homeurl' => 'HomeUrl', 'hidelast' => 'HideLast')); return Gdn_Theme::breadcrumbs($Breadcrumbs, val('homelink', $Params, true), $Options); }
/** * Register API endpoints * * @since 0.1.0 * @access public * @param array $data * @return void * @static */ public static function register($data) { static::get("/", ["controller" => "User", "authenticate" => true, "arguments" => ["Page" => val("Page", $data)]]); static::get("/[i:UserID]", ["controller" => "Profile"]); static::get("/summary", ["controller" => "User", "method" => "summary"]); static::post("/", ["controller" => "User", "method" => "add"]); static::put("/[i:UserID]", ["controller" => "User", "method" => "edit"]); static::delete("/[i:UserID]", ["controller" => "User", "method" => "delete", "arguments" => ["Method" => val("Method", $data)]]); }
/** * Delete a single draft. * * Redirects user back to Index unless DeliveryType is set. * * @since 2.0.0 * @access public * * @param int $DraftID Unique ID of draft to be deleted. * @param string $TransientKey Single-use hash to prove intent. */ public function delete($DraftID = '', $TransientKey = '') { $Form = Gdn::factory('Form'); $Session = Gdn::session(); if (is_numeric($DraftID) && $DraftID > 0) { $Draft = $this->DraftModel->getID($DraftID); } if ($Draft) { if ($Session->validateTransientKey($TransientKey) && (val('InsertUserID', $Draft) == $Session->UserID || checkPermission('Garden.Community.Manage'))) { // Delete the draft if (!$this->DraftModel->deleteID($DraftID)) { $Form->addError('Failed to delete draft'); } } else { throw permissionException('Garden.Community.Manage'); } } else { throw notFoundException('Draft'); } // Redirect if ($this->_DeliveryType === DELIVERY_TYPE_ALL) { $Target = GetIncomingValue('Target', '/drafts'); redirect($Target); } // Return any errors if ($Form->errorCount() > 0) { $this->setJson('ErrorMessage', $Form->errors()); } // Render default view $this->render(); }