/** Set the order of the comments. */ public function OrderBy($Value = NULL) { if ($Value === NULL) { return $this->_OrderBy; } if (is_string($Value)) { $Value = array($Value); } if (is_array($Value)) { // Set the order of this object. $OrderBy = array(); foreach ($Value as $Part) { if (StringEndsWith($Part, ' desc', TRUE)) { $OrderBy[] = array(substr($Part, 0, -5), 'desc'); } elseif (StringEndsWith($Part, ' asc', TRUE)) { $OrderBy[] = array(substr($Part, 0, -4), 'asc'); } else { $OrderBy[] = array($Part, 'asc'); } } $this->_OrderBy = $OrderBy; } elseif (is_a($Value, 'Gdn_SQLDriver')) { // Set the order of the given sql. foreach ($this->_OrderBy as $Parts) { $Value->OrderBy($Parts[0], $Parts[1]); } } }
function GetTextRowsFromText($fontSize, $font, $text, $maxWidth) { $text = str_replace("\n", "\n ", $text); $text = str_replace("\\n", "\n ", $text); $words = explode(" ", $text); $rows = array(); $tmpRow = ""; for ($i = 0; $i < count($words); $i++) { //last word if ($i == count($words) - 1) { $rows[] = $tmpRow . $words[$i]; break; } if (GetTextWidth($fontSize, $font, $tmpRow . $words[$i]) > $maxWidth) { $rows[] = $tmpRow; $tmpRow = ""; } else { if (StringEndsWith($tmpRow, "\n ")) { $tmpRow = str_replace("\n ", "", $tmpRow); $rows[] = $tmpRow; $tmpRow = ""; } } //add new word to row $tmpRow .= $words[$i] . " "; } return $rows; }
public function Analytics($Method, $RequestParameters, $Callback = FALSE) { $AnalyticsServer = C('Garden.Analytics.Remote', 'http://analytics.vanillaforums.com'); $FullMethod = explode('/', $Method); if (sizeof($FullMethod) < 2) { array_unshift($FullMethod, "analytics"); } list($ApiController, $ApiMethod) = $FullMethod; $ApiController = strtolower($ApiController); $ApiMethod = StringEndsWith(strtolower($ApiMethod), '.json', TRUE, TRUE) . '.json'; $FinalURL = CombinePaths(array($AnalyticsServer, $ApiController, $ApiMethod)); // Sign request $this->Sign($RequestParameters, TRUE); $FinalURL .= '?' . http_build_query($RequestParameters); try { $Response = ProxyRequest($FinalURL, 10, TRUE); } catch (Exception $e) { $Response = FALSE; } if ($Response !== FALSE) { $JsonResponse = json_decode($Response); if ($JsonResponse !== FALSE) { $JsonResponse = (array) GetValue('Analytics', $JsonResponse, FALSE); } // If we received a reply, parse it if ($JsonResponse !== FALSE) { $this->ParseAnalyticsResponse($JsonResponse, $Response, $Callback); return $JsonResponse; } } return FALSE; }
/** * Render the given view. * * @param string $Path The path to the view's file. * @param Controller $Controller The controller that is rendering the view. */ public function Render($Path, $Controller) { $Smarty = $this->Smarty(); // Get a friendly name for the controller. $ControllerName = get_class($Controller); if (StringEndsWith($ControllerName, 'Controller', TRUE)) { $ControllerName = substr($ControllerName, 0, -10); } // Get an ID for the body. $BodyIdentifier = strtolower($Controller->ApplicationFolder.'_'.$ControllerName.'_'.Gdn_Format::AlphaNumeric(strtolower($Controller->RequestMethod))); $Smarty->assign('BodyID', $BodyIdentifier); //$Smarty->assign('Config', Gdn::Config()); // Assign some information about the user. $Session = Gdn::Session(); if($Session->IsValid()) { $User = array( 'Name' => $Session->User->Name, 'CountNotifications' => (int)GetValue('CountNotifications', $Session->User->CountNotifications, 0), 'CountUnreadConversations' => (int)GetValue('CountUnreadConversations', $Session->User, 0), 'SignedIn' => TRUE); } else { $User = FALSE; /*array( 'Name' => '', 'CountNotifications' => 0, 'SignedIn' => FALSE);*/ } $Smarty->assign('User', $User); // Make sure that any datasets use arrays instead of objects. foreach($Controller->Data as $Key => $Value) { if($Value instanceof Gdn_DataSet) { $Controller->Data[$Key] = $Value->ResultArray(); } elseif($Value instanceof stdClass) { $Controller->Data[$Key] = (array)$Value; } } $Controller->Data['BodyClass'] = GetValue('CssClass', $Controller->Data, '', TRUE); $Smarty->assign('Assets', (array)$Controller->Assets); $Smarty->assign('Path', Gdn::Request()->Path()); // Assigign the controller data last so the controllers override any default data. $Smarty->assign($Controller->Data); $Smarty->Controller = $Controller; // for smarty plugins $Smarty->security = TRUE; $Smarty->security_settings['IF_FUNCS'] = array_merge($Smarty->security_settings['IF_FUNCS'], array('CheckPermission', 'GetValue', 'SetValue', 'Url')); $Smarty->secure_dir = array($Path); $Smarty->display($Path); }
public function Analytics($Method, $RequestParameters, $Callback = FALSE, $ParseResponse = TRUE) { $FullMethod = explode('/', $Method); if (sizeof($FullMethod) < 2) { array_unshift($FullMethod, "analytics"); } list($ApiController, $ApiMethod) = $FullMethod; $ApiController = strtolower($ApiController); $ApiMethod = StringEndsWith(strtolower($ApiMethod), '.json', TRUE, TRUE) . '.json'; $FinalURL = 'http://' . CombinePaths(array($this->AnalyticsServer, $ApiController, $ApiMethod)); // Allow hooking of analytics events $this->EventArguments['AnalyticsMethod'] =& $Method; $this->EventArguments['AnalyticsArgs'] =& $RequestParameters; $this->EventArguments['AnalyticsUrl'] =& $FinalURL; $this->FireEvent('SendAnalytics'); // Sign request $this->Sign($RequestParameters, TRUE); $RequestMethod = GetValue('RequestMethod', $RequestParameters, 'GET'); unset($RequestParameters['RequestMethod']); try { $ProxyRequest = new ProxyRequest(FALSE, array('Method' => $RequestMethod, 'Timeout' => 10, 'Cookies' => FALSE)); $Response = $ProxyRequest->Request(array('Url' => $FinalURL), $RequestParameters); } catch (Exception $e) { $Response = FALSE; } if ($Response !== FALSE) { $JsonResponse = json_decode($Response, TRUE); if ($JsonResponse !== FALSE) { if ($ParseResponse) { $AnalyticsJsonResponse = (array) GetValue('Analytics', $JsonResponse, FALSE); // If we received a reply, parse it if ($AnalyticsJsonResponse !== FALSE) { $this->ParseAnalyticsResponse($AnalyticsJsonResponse, $Response, $Callback); return $AnalyticsJsonResponse; } } else { return $JsonResponse; } } return $Response; } return FALSE; }
public function Query($Sql, $InputParameters = NULL, $Options = array()) { $Trace = debug_backtrace(); $Method = ''; foreach ($Trace as $Info) { $Class = GetValue('class', $Info, ''); if ($Class === '' || StringEndsWith($Class, 'Model', TRUE) || StringEndsWith($Class, 'Plugin', TRUE)) { $Type = ArrayValue('type', $Info, ''); $Method = $Class . $Type . $Info['function'] . '(' . self::FormatArgs($Info['args']) . ')'; break; } } // Save the query for debugging // echo '<br />adding to queries: '.$Sql; $Query = array('Sql' => $Sql, 'Parameters' => $InputParameters, 'Method' => $Method); $SaveQuery = TRUE; if (isset($Options['Cache'])) { $CacheKeys = (array) $Options['Cache']; $Cache = array(); $AllSet = TRUE; foreach ($CacheKeys as $CacheKey) { $Value = Gdn::Cache()->Get($CacheKey); $CacheValue = $Value !== Gdn_Cache::CACHEOP_FAILURE; $AllSet &= $CacheValue; $Cache[$CacheKey] = $CacheValue; } $SaveQuery = !$AllSet; $Query['Cache'] = $Cache; } // Start the Query Timer $TimeStart = Now(); $Result = parent::Query($Sql, $InputParameters, $Options); $Query = array_merge($this->LastInfo, $Query); // Aggregate the query times $TimeEnd = Now(); $this->_ExecutionTime += $TimeEnd - $TimeStart; if ($SaveQuery && !StringBeginsWith($Sql, 'set names')) { $Query['Time'] = $TimeEnd - $TimeStart; $this->_Queries[] = $Query; } return $Result; }
/** * @todo Put the query debugging logic into the debug plugin. * 1. Create a subclass of this object where Query() does the debugging stuff. * 2. Install that class to Gdn to override the database. */ public function Query($Sql, $InputParameters = NULL) { $Trace = debug_backtrace(); $Method = ''; foreach ($Trace as $Info) { $Class = GetValue('class', $Info, ''); if ($Class === '' || StringEndsWith($Class, 'Model', TRUE)) { $Type = ArrayValue('type', $Info, ''); $Method = $Class . $Type . $Info['function'] . '(' . self::FormatArgs($Info['args']) . ')'; break; } } // Save the query for debugging // echo '<br />adding to queries: '.$Sql; $this->_Queries[] = array('Sql' => $Sql, 'Parameters' => $InputParameters, 'Method' => $Method); // Start the Query Timer $TimeStart = list($sm, $ss) = explode(' ', microtime()); $Result = parent::Query($Sql, $InputParameters); // Aggregate the query times $TimeEnd = list($em, $es) = explode(' ', microtime()); $this->_ExecutionTime += $em + $es - ($sm + $ss); $this->_QueryTimes[] = $em + $es - ($sm + $ss); return $Result; }
public function fetchPageInfo($Url, $ThrowError = false) { $PageInfo = FetchPageInfo($Url, 3, $ThrowError); $Title = val('Title', $PageInfo, ''); if ($Title == '') { if ($ThrowError) { throw new Gdn_UserException(t("The page didn't contain any information.")); } $Title = formatString(t('Undefined discussion subject.'), array('Url' => $Url)); } else { if ($Strip = c('Vanilla.Embed.StripPrefix')) { $Title = stringBeginsWith($Title, $Strip, true, true); } if ($Strip = c('Vanilla.Embed.StripSuffix')) { $Title = StringEndsWith($Title, $Strip, true, true); } } $Title = trim($Title); $Description = val('Description', $PageInfo, ''); $Images = val('Images', $PageInfo, array()); $Body = formatString(t('EmbeddedDiscussionFormat'), array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? img(val(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $Url)); if ($Body == '') { $Body = $Url; } if ($Body == '') { $Body = formatString(t('EmbeddedNoBodyFormat.'), array('Url' => $Url)); } $Result = array('Name' => $Title, 'Body' => $Body, 'Format' => 'Html'); return $Result; }
/** * * @param array $Data * @param array $Columns The columns/table information for the join. Depending on the argument's index it will be interpreted differently. * - <b>numeric</b>: This column will come be added to the resulting join. The value can be either a string or a two element array where the second element specifies an alias. * - <b>alias</b>: The alias of the child table in the query. * - <b>child</b>: The name of the child column. * - <b>column</b>: The name of the column to put the joined data into. Can't be used with <b>prefix</b>. * - <b>parent</b>: The name of the parent column. * - <b>table</b>: The name of the child table in the join. * - <b>prefix</b>: The name of the prefix to give the columns. Can't be used with <b>column</b>. * @param array $Options An array of extra options. * - <b>sql</b>: A Gdn_SQLDriver with the child query. * - <b>type</b>: The join type, either JOIN_INNER, JOIN_LEFT. This defaults to JOIN_INNER. */ public static function Join(&$Data, $Columns, $Options = array()) { $Options = array_change_key_case($Options); $Sql = Gdn::SQL(); //GetValue('sql', $Options, Gdn::SQL()); $ResultColumns = array(); // Grab the columns. foreach ($Columns as $Index => $Name) { if (is_numeric($Index)) { // This is a column being selected. if (is_array($Name)) { $Column = $Name[0]; $ColumnAlias = $Name[1]; } else { $Column = $Name; $ColumnAlias = ''; } if (($Pos = strpos($Column, '.')) !== FALSE) { $Sql->Select($Column, '', $ColumnAlias); $Column = substr($Column, $Pos + 1); } else { $Sql->Select(isset($TableAlias) ? $TableAlias.'.'.$Column : $Column, '', $ColumnAlias); } if ($ColumnAlias) $ResultColumns[] = $ColumnAlias; else $ResultColumns[] = $Column; } else { switch (strtolower($Index)) { case 'alias': $TableAlias = $Name; break; case 'child': $ChildColumn = $Name; break; case 'column': $JoinColumn = $Name; break; case 'parent': $ParentColumn = $Name; break; case 'prefix': $ColumnPrefix = $Name; break; case 'table': $Table = $Name; break; case 'type': // The type shouldn't be here, but handle it. $Options['Type'] = $Name; break; default: throw new Exception("Gdn_DataSet::Join(): Unknown column option '$Index'."); } } } if (!isset($TableAlias)) { if (isset($Table)) $TableAlias = 'c'; else $TableAlias = 'c'; } if (!isset($ParentColumn)) { if (isset($ChildColumn)) $ParentColumn = $ChildColumn; elseif (isset($Table)) $ChildColumn = $Table.'ID'; else throw Exception("Gdn_DataSet::Join(): Missing 'parent' argument'."); } // Figure out some options if they weren't specified. if (!isset($ChildColumn)) { if (isset($ParentColumn)) $ChildColumn = $ParentColumn; elseif (isset($Table)) $ChildColumn = $Table.'ID'; else throw Exception("Gdn_DataSet::Join(): Missing 'child' argument'."); } if (!isset($ColumnPrefix) && !isset($JoinColumn)) { $ColumnPrefix = StringEndsWith($ParentColumn, 'ID', TRUE, TRUE); } $JoinType = strtolower(GetValue('Type', $Options, JOIN_LEFT)); // Start augmenting the sql for the join. if (isset($Table)) $Sql->From("$Table $TableAlias"); $Sql->Select("$TableAlias.$ChildColumn"); // Get the IDs to generate an in clause with. $IDs = ConsolidateArrayValuesByKey($Data, $ParentColumn); $Sql->WhereIn($ChildColumn, $IDs); $ChildData = $Sql->Get()->ResultArray(); $ChildData = self::Index($ChildData, $ChildColumn, array('unique' => isset($ColumnPrefix))); $NotFound = array(); // Join the data in. foreach ($Data as $Index => &$Row) { $ParentID = GetValue($ParentColumn, $Row); if (isset($ChildData[$ParentID])) { $ChildRow = $ChildData[$ParentID]; if (isset($ColumnPrefix)) { // Add the data to the columns. foreach ($ChildRow as $Name => $Value) { SetValue($ColumnPrefix.$Name, $Row, $Value); } } else { // Add the result data. SetValue($JoinColumn, $Row, $ChildRow); } } else { if ($JoinType == JOIN_LEFT) { if (isset($ColumnPrefix)) { foreach ($ResultColumns as $Name) { SetValue($ColumnPrefix.$Name, $Row, NULL); } } else { SetValue($JoinColumn, $Row, array()); } } else { $NotFound[] = $Index; } } } // Remove inner join rows. if ($JoinType == JOIN_INNER) { foreach ($NotFound as $Index) { unset($Data[$Index]); } } }
public function UtilityController_SiteMap_Create($Sender, $Args = array()) { Gdn::Session()->Start(0, FALSE, FALSE); $Sender->DeliveryMethod(DELIVERY_METHOD_XHTML); $Sender->DeliveryType(DELIVERY_TYPE_VIEW); $Sender->SetHeader('Content-Type', 'text/xml'); $Arg = StringEndsWith(GetValue(0, $Args), '.xml', TRUE, TRUE); $Parts = explode('-', $Arg, 2); $Type = strtolower($Parts[0]); $Arg = GetValue(1, $Parts, ''); $Urls = array(); switch ($Type) { case 'category': // Build the category site map. $this->BuildCategorySiteMap($Arg, $Urls); break; default: // See if a plugin can build the sitemap. $this->EventArguments['Type'] = $Type; $this->EventArguments['Arg'] = $Arg; $this->EventArguments['Urls'] =& $Urls; $this->FireEvent('SiteMap' . ucfirst($Type)); break; } $Sender->SetData('Urls', $Urls); $Sender->Render('SiteMap', '', 'plugins/Sitemaps'); }
/** * Serves a file to the browser. * * @param string $File The full path to the file being served. * @param string $Name The name to give the file being served (don't include file extension, it will be added automatically). Will use file's name on disk if ignored. * @param string $MimeType The mime type of the file. */ public static function ServeFile($File, $Name = '', $MimeType = '') { if (is_readable($File)) { // Get the db connection and make sure it is closed $Database = Gdn::Database(); $Database->CloseConnection(); $Size = filesize($File); $Extension = strtolower(pathinfo($File, PATHINFO_EXTENSION)); if ($Name == '') { $Name = pathinfo($File, PATHINFO_FILENAME) . '.' . $Extension; } elseif (!StringEndsWith($Name, '.' . $Extension)) { $Name .= '.' . $Extension; } $Name = rawurldecode($Name); // Figure out the MIME type $MimeTypes = array("pdf" => "application/pdf", "txt" => "text/plain", "html" => "text/html", "htm" => "text/html", "exe" => "application/octet-stream", "zip" => "application/zip", "doc" => "application/msword", "xls" => "application/vnd.ms-excel", "ppt" => "application/vnd.ms-powerpoint", "gif" => "image/gif", "png" => "image/png", "jpeg" => "image/jpg", "jpg" => "image/jpg", "php" => "text/plain"); if ($MimeType == '') { if (array_key_exists($Extension, $MimeTypes)) { $MimeType = $MimeTypes[$Extension]; } else { $MimeType = 'application/force-download'; } } @ob_end_clean(); // required for IE, otherwise Content-Disposition may be ignored if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } header('Content-Type: ' . $MimeType); header('Content-Disposition: attachment; filename="' . $Name . '"'); header("Content-Transfer-Encoding: binary"); header('Accept-Ranges: bytes'); header("Cache-control: private"); header('Pragma: private'); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); readfile($File); exit; } }
/** * * * @param $Path * @param $Controller */ public function init($Path, $Controller) { $Smarty = $this->smarty(); // Get a friendly name for the controller. $ControllerName = get_class($Controller); if (StringEndsWith($ControllerName, 'Controller', true)) { $ControllerName = substr($ControllerName, 0, -10); } // Get an ID for the body. $BodyIdentifier = strtolower($Controller->ApplicationFolder . '_' . $ControllerName . '_' . Gdn_Format::alphaNumeric(strtolower($Controller->RequestMethod))); $Smarty->assign('BodyID', $BodyIdentifier); //$Smarty->assign('Config', Gdn::Config()); // Assign some information about the user. $Session = Gdn::session(); if ($Session->isValid()) { $User = array('Name' => $Session->User->Name, 'Photo' => '', 'CountNotifications' => (int) val('CountNotifications', $Session->User, 0), 'CountUnreadConversations' => (int) val('CountUnreadConversations', $Session->User, 0), 'SignedIn' => true); $Photo = $Session->User->Photo; if ($Photo) { if (!IsUrl($Photo)) { $Photo = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s')); } } else { if (function_exists('UserPhotoDefaultUrl')) { $Photo = UserPhotoDefaultUrl($Session->User, 'ProfilePhoto'); } elseif ($ConfigPhoto = C('Garden.DefaultAvatar')) { $Photo = Gdn_Upload::url($ConfigPhoto); } else { $Photo = Asset('/applications/dashboard/design/images/defaulticon.png', true); } } $User['Photo'] = $Photo; } else { $User = false; /*array( 'Name' => '', 'CountNotifications' => 0, 'SignedIn' => FALSE);*/ } $Smarty->assign('User', $User); // Make sure that any datasets use arrays instead of objects. foreach ($Controller->Data as $Key => $Value) { if ($Value instanceof Gdn_DataSet) { $Controller->Data[$Key] = $Value->resultArray(); } elseif ($Value instanceof stdClass) { $Controller->Data[$Key] = (array) $Value; } } $BodyClass = val('CssClass', $Controller->Data, '', true); $Sections = Gdn_Theme::section(null, 'get'); if (is_array($Sections)) { foreach ($Sections as $Section) { $BodyClass .= ' Section-' . $Section; } } $Controller->Data['BodyClass'] = $BodyClass; // Set the current locale for themes to take advantage of. $Locale = Gdn::locale()->Locale; $CurrentLocale = array('Key' => $Locale, 'Lang' => str_replace('_', '-', $Locale)); if (class_exists('Locale')) { $CurrentLocale['Language'] = Locale::getPrimaryLanguage($Locale); $CurrentLocale['Region'] = Locale::getRegion($Locale); $CurrentLocale['DisplayName'] = Locale::getDisplayName($Locale, $Locale); $CurrentLocale['DisplayLanguage'] = Locale::getDisplayLanguage($Locale, $Locale); $CurrentLocale['DisplayRegion'] = Locale::getDisplayRegion($Locale, $Locale); } $Smarty->assign('CurrentLocale', $CurrentLocale); $Smarty->assign('Assets', (array) $Controller->Assets); $Smarty->assign('Path', Gdn::request()->path()); // Assign the controller data last so the controllers override any default data. $Smarty->assign($Controller->Data); $Smarty->Controller = $Controller; // for smarty plugins $Smarty->security = true; $Smarty->security_settings['IF_FUNCS'] = array_merge($Smarty->security_settings['IF_FUNCS'], array('Category', 'CheckPermission', 'InSection', 'InCategory', 'MultiCheckPermission', 'GetValue', 'SetValue', 'Url')); $Smarty->security_settings['MODIFIER_FUNCS'] = array_merge($Smarty->security_settings['MODIFIER_FUNCS'], array('sprintf')); $Smarty->secure_dir = array($Path); }
public function InsertPermissionTable() { if ($this->ImportExists('Permission', 'JunctionTable')) { $this->_InsertTable('Permission'); return TRUE; } // Clear the permission table in case the step was only half done before. $this->SQL->Delete('Permission', array('RoleID <>' => 0)); // Grab all of the permission columns. $PM = new PermissionModel(); $GlobalColumns = array_filter($PM->PermissionColumns()); unset($GlobalColumns['PermissionID']); $JunctionColumns = array_filter($PM->PermissionColumns('Category', 'PermissionCategoryID')); unset($JunctionColumns['PermissionID']); $JunctionColumns = array_merge(array('JunctionTable' => 'Category', 'JunctionColumn' => 'PermissionCategoryID', 'JunctionID' => -1), $JunctionColumns); $ColumnSets = array($GlobalColumns, $JunctionColumns); $Data = $this->SQL->Get('zPermission')->ResultArray(); foreach ($Data as $Row) { $Preset = strtolower(GetValue('_Permissions', $Row)); foreach ($ColumnSets as $ColumnSet) { $Set = array(); $Set['RoleID'] = $Row['RoleID']; foreach ($ColumnSet as $ColumnName => $Default) { if (isset($Row[$ColumnName])) { $Value = $Row[$ColumnName]; } elseif (strpos($ColumnName, '.') === FALSE) { $Value = $Default; } elseif ($Preset == 'all') { $Value = 1; } elseif ($Preset == 'view') { $Value = StringEndsWith($ColumnName, 'View', TRUE); } else { $Value = $Default & 1; } $Set["`{$ColumnName}`"] = $Value; } $this->SQL->Insert('Permission', $Set); unset($Set); } } return TRUE; }
public function InsertPermissionTable() { // $this->LoadState(); // Clear the permission table in case the step was only half done before. $this->SQL->Delete('Permission', array('RoleID <>' => 0)); // Grab all of the permission columns. $PM = new PermissionModel(); $GlobalColumns = array_filter($PM->PermissionColumns()); unset($GlobalColumns['PermissionID']); $JunctionColumns = array_filter($PM->PermissionColumns('Category', 'PermissionCategoryID')); unset($JunctionColumns['PermissionID']); $JunctionColumns = array_merge(array('JunctionTable' => 'Category', 'JunctionColumn' => 'PermissionCategoryID', 'JunctionID' => -1), $JunctionColumns); if ($this->ImportExists('Permission', 'JunctionTable')) { $ColumnSets = array(array_merge($GlobalColumns, $JunctionColumns)); $ColumnSets[0]['JunctionTable'] = NULL; $ColumnSets[0]['JunctionColumn'] = NULL; $ColumnSets[0]['JunctionID'] = NULL; } else { $ColumnSets = array($GlobalColumns, $JunctionColumns); } $Data = $this->SQL->Get('zPermission')->ResultArray(); foreach ($Data as $Row) { $Presets = array_map('trim', explode(',', GetValue('_Permissions', $Row))); foreach ($ColumnSets as $ColumnSet) { $Set = array(); $Set['RoleID'] = $Row['RoleID']; foreach ($Presets as $Preset) { if (strpos($Preset, '.') !== FALSE) { // This preset is a specific permission. if (array_key_exists($Preset, $ColumnSet)) { $Set["`{$Preset}`"] = 1; } continue; } $Preset = strtolower($Preset); foreach ($ColumnSet as $ColumnName => $Default) { if (isset($Row[$ColumnName])) { $Value = $Row[$ColumnName]; } elseif (strpos($ColumnName, '.') === FALSE) { $Value = $Default; } elseif ($Preset == 'all') { $Value = 1; } elseif ($Preset == 'view') { $Value = StringEndsWith($ColumnName, 'View', TRUE) && !in_array($ColumnName, array('Garden.Settings.View')); } elseif ($Preset == $ColumnName) { $Value = 1; } else { $Value = $Default & 1; } $Set["`{$ColumnName}`"] = $Value; } } $this->SQL->Insert('Permission', $Set); unset($Set); } } return TRUE; }
/** * Offers a quick and dirty way of parsing an addon's info array without using eval(). * * @param string $Path The path to the info array. * @param string $Variable The name of variable containing the information. * @return array|false The info array or false if the file could not be parsed. */ public static function parseInfoArray($Path, $Variable = false) { $fp = fopen($Path, 'rb'); $Lines = array(); $InArray = false; // Get all of the lines in the info array. while (($Line = fgets($fp)) !== false) { // Remove comments from the line. $Line = preg_replace('`\\s//.*$`', '', $Line); if (!$Line) { continue; } if (!$InArray && preg_match('`\\$([A-Za-z]+Info)\\s*\\[`', trim($Line), $Matches)) { $Variable = $Matches[1]; if (preg_match('`\\[\\s*[\'"](.+?)[\'"]\\s*\\]`', $Line, $Matches)) { $GlobalKey = $Matches[1]; $InArray = true; } } elseif ($InArray && StringEndsWith(trim($Line), ';')) { break; } elseif ($InArray) { $Lines[] = trim($Line); } } fclose($fp); if (count($Lines) == 0) { return false; } // Parse the name/value information in the arrays. $Result = array(); foreach ($Lines as $Line) { // Get the name from the line. if (!preg_match('`[\'"](.+?)[\'"]\\s*=>`', $Line, $Matches) || !substr($Line, -1) == ',') { continue; } $Key = $Matches[1]; // Strip the key from the line. $Line = trim(trim(substr(strstr($Line, '=>'), 2)), ','); if (strlen($Line) == 0) { continue; } $Value = null; if (is_numeric($Line)) { $Value = $Line; } elseif (strcasecmp($Line, 'TRUE') == 0 || strcasecmp($Line, 'FALSE') == 0) { $Value = $Line; } elseif (in_array($Line[0], array('"', "'")) && substr($Line, -1) == $Line[0]) { $Quote = $Line[0]; $Value = trim($Line, $Quote); $Value = str_replace('\\' . $Quote, $Quote, $Value); } elseif (stringBeginsWith($Line, 'array(') && substr($Line, -1) == ')') { // Parse the line's array. $Line = substr($Line, 6, strlen($Line) - 7); $Items = explode(',', $Line); $Array = array(); foreach ($Items as $Item) { $SubItems = explode('=>', $Item); if (count($SubItems) == 1) { $Array[] = trim(trim($SubItems[0]), '"\''); } elseif (count($SubItems) == 2) { $SubKey = trim(trim($SubItems[0]), '"\''); $SubValue = trim(trim($SubItems[1]), '"\''); $Array[$SubKey] = $SubValue; } } $Value = $Array; } if ($Value != null) { $Result[$Key] = $Value; } } $Result = array($GlobalKey => $Result, 'Variable' => $Variable); return $Result; }
public function SetCookie($Key, $Payload) { $Path = Gdn::Config('Garden.Cookie.Path', '/'); $Domain = Gdn::Config('Garden.Cookie.Domain', ''); // If the domain being set is completely incompatible with the current domain then make the domain work. $CurrentHost = Gdn::Request()->Host(); if (!StringEndsWith($CurrentHost, trim($Domain, '.'))) $Domain = ''; $CookieHashMethod = C('Garden.Cookie.HashMethod'); $CookieSalt = C('Garden.Cookie.Salt'); // Create the cookie contents $KeyHash = self::_Hash($Key, $CookieHashMethod, $CookieSalt); $Hash = self::_HashHMAC($CookieHashMethod, $Key, $KeyHash); $Cookie = array($Key,$Hash,time()); if (!is_null($Payload)) { if (!is_array($Payload)) $Payload = array($Payload); $Cookie = array_merge($Cookie, $Payload); } $CookieContents = implode('|',$Cookie); // Create the cookie. Lasts for the browser session only. setcookie($this->_CookieName, $CookieContents, 0, $Path, $Domain); $_COOKIE[$this->_CookieName] = $CookieContents; }
/** * Load discussions for a specific tag. * @param DiscussionsController $Sender */ public function DiscussionsController_Tagged_Create($Sender) { Gdn_Theme::Section('DiscussionList'); $Args = $Sender->RequestArgs; $Get = array_change_key_case($Sender->Request->Get()); if ($UseCategories = C('Plugins.Tagging.UseCategories')) { // The url is in the form /category/tag/p1 $CategoryCode = GetValue(0, $Args); $Tag = GetValue(1, $Args); $Page = GetValue(2, $Args); } else { // The url is in the form /tag/p1 $CategoryCode = ''; $Tag = GetValue(0, $Args); $Page = GetValue(1, $Args); } // Look for explcit values. $CategoryCode = GetValue('category', $Get, $CategoryCode); $Tag = GetValue('tag', $Get, $Tag); $Page = GetValue('page', $Get, $Page); $Category = CategoryModel::Categories($CategoryCode); $Tag = StringEndsWith($Tag, '.rss', TRUE, TRUE); list($Offset, $Limit) = OffsetLimit($Page, C('Vanilla.Discussions.PerPage', 30)); $MultipleTags = strpos($Tag, ',') !== FALSE; $Sender->SetData('Tag', $Tag, TRUE); $TagModel = TagModel::instance(); $RecordCount = FALSE; if (!$MultipleTags) { $Tags = $TagModel->GetWhere(array('Name' => $Tag))->ResultArray(); if (count($Tags) == 0) { throw NotFoundException('Page'); } if (count($Tags) > 1) { foreach ($Tags as $TagRow) { if ($TagRow['CategoryID'] == GetValue('CategoryID', $Category)) { break; } } } else { $TagRow = array_pop($Tags); } $Tags = $TagModel->getRelatedTags($TagRow); $RecordCount = $TagRow['CountDiscussions']; $Sender->SetData('CountDiscussions', $RecordCount); $Sender->SetData('Tags', $Tags); $Sender->SetData('Tag', $TagRow); $ChildTags = $TagModel->getChildTags($TagRow['TagID']); $Sender->SetData('ChildTags', $ChildTags); } $Sender->Title(htmlspecialchars($TagRow['FullName'])); $UrlTag = rawurlencode($Tag); if (urlencode($Tag) == $Tag) { $Sender->CanonicalUrl(Url(ConcatSep('/', "/discussions/tagged/{$UrlTag}", PageNumber($Offset, $Limit, TRUE)), TRUE)); $FeedUrl = Url(ConcatSep('/', "/discussions/tagged/{$UrlTag}/feed.rss", PageNumber($Offset, $Limit, TRUE, FALSE)), '//'); } else { $Sender->CanonicalUrl(Url(ConcatSep('/', 'discussions/tagged', PageNumber($Offset, $Limit, TRUE)) . '?Tag=' . $UrlTag, TRUE)); $FeedUrl = Url(ConcatSep('/', 'discussions/tagged', PageNumber($Offset, $Limit, TRUE, FALSE), 'feed.rss') . '?Tag=' . $UrlTag, '//'); } if ($Sender->Head) { $Sender->AddJsFile('discussions.js'); $Sender->Head->AddRss($FeedUrl, $Sender->Head->Title()); } if (!is_numeric($Offset) || $Offset < 0) { $Offset = 0; } // Add Modules $Sender->AddModule('NewDiscussionModule'); $Sender->AddModule('DiscussionFilterModule'); $Sender->AddModule('BookmarkedModule'); $Sender->SetData('Category', FALSE, TRUE); $Sender->AnnounceData = FALSE; $Sender->SetData('Announcements', array(), TRUE); $DiscussionModel = new DiscussionModel(); $TagModel->SetTagSql($DiscussionModel->SQL, $Tag, $Limit, $Offset, $Sender->Request->Get('op', 'or')); $Sender->DiscussionData = $DiscussionModel->Get($Offset, $Limit, array('Announce' => 'all')); $Sender->SetData('Discussions', $Sender->DiscussionData, TRUE); $Sender->SetJson('Loading', $Offset . ' to ' . $Limit); // Build a pager. $PagerFactory = new Gdn_PagerFactory(); $Sender->Pager = $PagerFactory->GetPager('Pager', $Sender); $Sender->Pager->ClientID = 'Pager'; $Sender->Pager->Configure($Offset, $Limit, $RecordCount, ''); $Sender->View = C('Vanilla.Discussions.Layout'); /* // If these don't equal, then there is a category that should be inserted. if ($UseCategories && $Category && $TagRow['FullName'] != GetValue('Name', $Category)) { $Sender->Data['Breadcrumbs'][] = array('Name' => $Category['Name'], 'Url' => TagUrl($TagRow)); } $Sender->Data['Breadcrumbs'][] = array('Name' => $TagRow['FullName'], 'Url' => ''); */ // Render the controller. $this->View = C('Vanilla.Discussions.Layout') == 'table' ? 'table' : 'index'; $Sender->Render($this->View, 'discussions', 'vanilla'); }
/** * * * @param Gdn_Controller $Controller * @param string $Type * @return void */ protected function attachUploadsToComment($Controller, $Type = 'comment') { $RawType = ucfirst($Type); if (StringEndsWith($Controller->RequestMethod, 'Comment', true) && $Type != 'comment') { $Type = 'comment'; $RawType = 'Comment'; if (!isset($Controller->Comment)) { return; } $Controller->EventArguments['Comment'] = $Controller->Comment; } $MediaList = $this->mediaCache(); if (!is_array($MediaList)) { return; } $Param = $Type == 'comment' ? 'CommentID' : 'DiscussionID'; $MediaKey = $Type . '/' . val($Param, val($RawType, $Controller->EventArguments)); if (array_key_exists($MediaKey, $MediaList)) { include_once $Controller->fetchViewLocation('fileupload_functions', '', 'plugins/FileUpload'); $Controller->setData('CommentMediaList', $MediaList[$MediaKey]); $Controller->setData('GearImage', $this->getWebResource('images/gear.png')); $Controller->setData('Garbage', $this->getWebResource('images/trash.png')); $Controller->setData('CanDownload', $this->CanDownload); echo $Controller->fetchView($this->getView('link_files.php')); } }
/** * * * @param $Suffix * @param $Value * @param $Expires */ public function setCookie($Suffix, $Value, $Expires) { $Name = c('Garden.Cookie.Name') . $Suffix; $Path = c('Garden.Cookie.Path'); $Domain = c('Garden.Cookie.Domain'); // If the domain being set is completely incompatible with the current domain then make the domain work. $CurrentHost = Gdn::request()->host(); if (!StringEndsWith($CurrentHost, trim($Domain, '.'))) { $Domain = ''; } // Allow people to specify up to a year of expiry. if (abs($Expires) < 31556926) { $Expires = time() + $Expires; } safeCookie($Name, $Value, $Expires, $Path, $Domain); $_COOKIE[$Name] = $Value; }
/** * Call a method on the given model. */ public function Model() { $this->Permission('Garden.Settings.Manage'); $this->DeliveryMethod(DELIVERY_METHOD_JSON); $this->DeliveryType(DELIVERY_TYPE_DATA); $Args = func_get_args(); // Check to see if we have a model. $ModelName = StringEndsWith(array_shift($Args), 'Model', TRUE, TRUE); $ModelName = ucfirst($ModelName) . 'Model'; if (!class_exists($ModelName)) { throw NotFoundException($ModelName); } // Check for json/xml style extension. if (count($Args)) { $LastArg = $Args[count($Args) - 1]; $Extension = strrchr($LastArg, '.'); if ($Extension) { $Args[count($Args) - 1] = substr($LastArg, 0, -strlen($Extension)); $Extension = strtolower($Extension); if ($Extension == '.xml') { $this->DeliveryMethod(DELIVERY_METHOD_XML); } } } // Instantiate the model. $Model = new $ModelName(); $MethodName = array_shift($Args); // Reflect the arguments. $Callback = array($Model, $MethodName); if ($this->Request->Get('help')) { $this->SetData('Model', get_class($Model)); if ($MethodName) { if (!method_exists($Model, $MethodName)) { throw NotFoundException($ModelName . '->' . $MethodName . '()'); } $this->SetData('Method', $MethodName); $Meth = new ReflectionMethod($Callback[0], $Callback[1]); $MethArgs = $Meth->getParameters(); $Args = array(); foreach ($MethArgs as $Index => $MethArg) { $ParamName = $MethArg->getName(); if ($MethArg->isDefaultValueAvailable()) { $Args[$ParamName] = $MethArg->getDefaultValue(); } else { $Args[$ParamName] = 'REQUIRED'; } } $this->SetData('Args', $Args); } else { $Class = new ReflectionClass($Model); $Meths = $Class->getMethods(); $Methods = array(); foreach ($Meths as $Meth) { $MethodName = $Meth->getName(); if (StringBeginsWith($MethodName, '_')) { continue; } $MethArgs = $Meth->getParameters(); $Args = array(); foreach ($MethArgs as $Index => $MethArg) { $ParamName = $MethArg->getName(); if ($MethArg->isDefaultValueAvailable()) { $Args[$ParamName] = $MethArg->getDefaultValue(); } else { $Args[$ParamName] = 'REQUIRED'; } } $Methods[$MethodName] = array('Method' => $MethodName, 'Args' => $Args); } $this->SetData('Methods', $Methods); } } else { if (!method_exists($Model, $MethodName)) { throw NotFoundException($ModelName . '->' . $MethodName . '()'); } $MethodArgs = ReflectArgs($Callback, $this->Request->Get(), $Args); $Result = call_user_func_array($Callback, $MethodArgs); if (is_array($Result)) { $this->Data = $Result; } elseif (is_a($Result, 'Gdn_DataSet')) { $Result = $Result->ResultArray(); $this->Data = $Result; } elseif (is_a($Result, 'stdClass')) { $this->Data = (array) $Result; } else { $this->SetData('Result', $Result); } } $this->Render(); }
/** * Gets or sets the name of the page for the controller. * The page name is meant to be a friendly name suitable to be consumed by developers. * * @param string|NULL $Value A new value to set. */ public function PageName($Value = NULL) { if ($Value !== NULL) { $this->_PageName = $Value; return $Value; } if ($this->_PageName === NULL) { if ($this->ControllerName) { $Name = $this->ControllerName; } else { $Name = get_class($this); } $Name = strtolower($Name); if (StringEndsWith($Name, 'controller', FALSE)) { $Name = substr($Name, 0, -strlen('controller')); } return $Name; } else { return $this->_PageName; } }
function RemoveKeysFromNestedArray($Array, $Matches) { if (is_array($Array)) { foreach ($Array as $Key => $Value) { $IsMatch = FALSE; foreach ($Matches as $Match) { if (StringEndsWith($Key, $Match)) { unset($Array[$Key]); $IsMatch = TRUE; } } if (!$IsMatch && (is_array($Value) || is_object($Value))) { $Array[$Key] = RemoveKeysFromNestedArray($Value, $Matches); } } } else { if (is_object($Array)) { $Arr = get_object_vars($Array); foreach ($Arr as $Key => $Value) { $IsMatch = FALSE; foreach ($Matches as $Match) { if (StringEndsWith($Key, $Match)) { unset($Array->{$Key}); $IsMatch = TRUE; } } if (!$IsMatch && (is_array($Value) || is_object($Value))) { $Array->{$Key} = RemoveKeysFromNestedArray($Value, $Matches); } } } } return $Array; }
/** * Set where to go after signin. * * @access public * @since 2.0.0 * * @param string $Target Where we're requested to go to. * @return string URL to actually go to (validated & safe). */ public function Target($Target = FALSE) { if ($Target === FALSE) { $Target = $this->Form->GetFormValue('Target', FALSE); if (!$Target) { $Target = $this->Request->Get('Target', '/'); } } // Make sure that the target is a valid url. if (!preg_match('`(^https?://)`', $Target)) { $Target = '/' . ltrim($Target, '/'); } else { $MyHostname = parse_url(Gdn::Request()->Domain(), PHP_URL_HOST); $TargetHostname = parse_url($Target, PHP_URL_HOST); // Only allow external redirects to trusted domains. $TrustedDomains = C('Garden.TrustedDomains', TRUE); if (is_array($TrustedDomains)) { // Add this domain to the trusted hosts. $TrustedDomains[] = $MyHostname; $Sender->EventArguments['TrustedDomains'] =& $TrustedDomains; $this->FireEvent('BeforeTargetReturn'); } if ($TrustedDomains === TRUE) { return $Target; } elseif (count($TrustedDomains) == 0) { // Only allow http redirects if they are to the same host name. if ($MyHostname != $TargetHostname) { $Target = ''; } } else { // Loop the trusted domains looking for a match $Match = FALSE; foreach ($TrustedDomains as $TrustedDomain) { if (StringEndsWith($TargetHostname, $TrustedDomain, TRUE)) { $Match = TRUE; } } if (!$Match) { $Target = ''; } } } return $Target; }
/** * Joins the query to a permission junction table and limits the results accordingly. * * @param Gdn_SQLDriver $SQL The SQL driver to add the permission to. * @param mixed $Permissions The permission name (or array of names) to use when limiting the query. * @param string $ForeignAlias The alias of the table to join to (ie. Category). * @param string $ForeignColumn The primary key column name of $JunctionTable (ie. CategoryID). * @param string $JunctionTable * @param string $JunctionColumn */ public function SQLPermission($SQL, $Permissions, $ForeignAlias, $ForeignColumn, $JunctionTable = '', $JunctionColumn = '') { $Session = Gdn::Session(); // Figure out the junction table if necessary. if (!$JunctionTable && StringEndsWith($ForeignColumn, 'ID')) { $JunctionTable = substr($ForeignColumn, 0, -2); } // Check to see if the permission is disabled. if (C('Garden.Permission.Disabled.' . $JunctionTable)) { if (!$Session->CheckPermission($Permissions)) { $SQL->Where('1', '0', FALSE, FALSE); } } elseif ($Session->UserID <= 0 || is_object($Session->User) && $Session->User->Admin != '1') { $SQL->Distinct()->Join('Permission _p', '_p.JunctionID = ' . $ForeignAlias . '.' . $ForeignColumn, 'inner')->Join('UserRole _ur', '_p.RoleID = _ur.RoleID', 'inner')->BeginWhereGroup()->Where('_ur.UserID', $Session->UserID); if (!is_array($Permissions)) { $Permissions = array($Permissions); } $SQL->BeginWhereGroup(); foreach ($Permissions as $Permission) { $SQL->Where('_p.`' . $Permission . '`', 1); } $SQL->EndWhereGroup(); } else { // Force this method to play nice in case it is used in an or clause // (ie. it returns true in a sql sense by doing 1 = 1) $SQL->Where('1', '1', FALSE, FALSE); } return $SQL; }
public function DiscussionsController_AfterDiscussionTabs_Handler($Sender, $Args) { if (StringEndsWith(Gdn::Request()->Path(), '/unanswered', TRUE)) { $CssClass = ' class="Active"'; } else { $CssClass = ''; } $Count = Gdn::Cache()->Get('QnA-UnansweredCount'); if ($Count === Gdn_Cache::CACHEOP_FAILURE) { $Count = ' <span class="Popin Count" rel="/discussions/unansweredcount">'; } else { $Count = ' <span class="Count">' . $Count . '</span>'; } echo '<li' . $CssClass . '><a class="TabLink QnA-UnansweredQuestions" href="' . Url('/discussions/unanswered') . '">' . T('Unanswered Questions', 'Unanswered') . $Count . '</span></a></li>'; }
/** * Add user data to a result set. * * @param array|Gdn_DataSet $Data Results we need to associate user data with. * @param array $Columns Database columns containing UserIDs to get data for. * @param array $Options Optionally pass list of user data to collect with key 'Join'. */ public function joinUsers(&$Data, $Columns, $Options = []) { if ($Data instanceof Gdn_DataSet) { $Data2 = $Data->result(); } else { $Data2 =& $Data; } // Grab all of the user fields that need to be joined. $UserIDs = []; foreach ($Data as $Row) { foreach ($Columns as $ColumnName) { $ID = val($ColumnName, $Row); if (is_numeric($ID)) { $UserIDs[$ID] = 1; } } } // Get the users. $Users = $this->getIDs(array_keys($UserIDs)); // Get column name prefix (ex: 'Insert' from 'InsertUserID') $Prefixes = []; foreach ($Columns as $ColumnName) { $Prefixes[] = StringEndsWith($ColumnName, 'UserID', true, true); } // Join the user data using prefixes (ex: 'Name' for 'InsertUserID' becomes 'InsertName') $Join = val('Join', $Options, ['Name', 'Email', 'Photo']); foreach ($Data2 as &$Row) { foreach ($Prefixes as $Px) { $ID = val($Px . 'UserID', $Row); if (is_numeric($ID)) { $User = val($ID, $Users, false); foreach ($Join as $Column) { $Value = $User[$Column]; if ($Column == 'Photo') { if ($Value && !isUrl($Value)) { $Value = Gdn_Upload::url(changeBasename($Value, 'n%s')); } elseif (!$Value) { $Value = UserModel::getDefaultAvatarUrl($User); } } setValue($Px . $Column, $Row, $Value); } } else { foreach ($Join as $Column) { setValue($Px . $Column, $Row, null); } } } } }
public static function DeleteCookie($CookieName, $Path = NULL, $Domain = NULL) { if (is_null($Path)) { $Path = Gdn::Config('Garden.Cookie.Path'); } if (is_null($Domain)) { $Domain = Gdn::Config('Garden.Cookie.Domain'); } $CurrentHost = Gdn::Request()->Host(); if (!StringEndsWith($CurrentHost, trim($Domain, '.'))) { $Domain = ''; } $Expiry = time() - 60 * 60; setcookie($CookieName, "", $Expiry, $Path, $Domain); $_COOKIE[$CookieName] = NULL; }
public function Init($Path, $Controller) { $Smarty = $this->Smarty(); // Get a friendly name for the controller. $ControllerName = get_class($Controller); if (StringEndsWith($ControllerName, 'Controller', TRUE)) { $ControllerName = substr($ControllerName, 0, -10); } // Get an ID for the body. $BodyIdentifier = strtolower($Controller->ApplicationFolder . '_' . $ControllerName . '_' . Gdn_Format::AlphaNumeric(strtolower($Controller->RequestMethod))); $Smarty->assign('BodyID', $BodyIdentifier); //$Smarty->assign('Config', Gdn::Config()); // Assign some information about the user. $Session = Gdn::Session(); if ($Session->IsValid()) { $User = array('Name' => $Session->User->Name, 'Photo' => '', 'CountNotifications' => (int) GetValue('CountNotifications', $Session->User, 0), 'CountUnreadConversations' => (int) GetValue('CountUnreadConversations', $Session->User, 0), 'SignedIn' => TRUE); $Photo = $Session->User->Photo; if ($Photo) { if (!preg_match('`^https?://`i', $Photo)) { $Photo = Gdn_Upload::Url(ChangeBasename($Photo, 'n%s')); } } else { if (function_exists('UserPhotoDefaultUrl')) { $Photo = UserPhotoDefaultUrl($Session->User, 'ProfilePhoto'); } elseif ($ConfigPhoto = C('Garden.DefaultAvatar')) { $Photo = Gdn_Upload::Url($ConfigPhoto); } else { $Photo = Asset('/applications/dashboard/design/images/defaulticon.png', TRUE); } } $User['Photo'] = $Photo; } else { $User = FALSE; /*array( 'Name' => '', 'CountNotifications' => 0, 'SignedIn' => FALSE);*/ } $Smarty->assign('User', $User); // Make sure that any datasets use arrays instead of objects. foreach ($Controller->Data as $Key => $Value) { if ($Value instanceof Gdn_DataSet) { $Controller->Data[$Key] = $Value->ResultArray(); } elseif ($Value instanceof stdClass) { $Controller->Data[$Key] = (array) $Value; } } $BodyClass = GetValue('CssClass', $Controller->Data, '', TRUE); $Sections = Gdn_Theme::Section(NULL, 'get'); if (is_array($Sections)) { foreach ($Sections as $Section) { $BodyClass .= ' Section-' . $Section; } } $Controller->Data['BodyClass'] = $BodyClass; $Smarty->assign('Assets', (array) $Controller->Assets); $Smarty->assign('Path', Gdn::Request()->Path()); // Assigign the controller data last so the controllers override any default data. $Smarty->assign($Controller->Data); $Smarty->Controller = $Controller; // for smarty plugins $Smarty->security = TRUE; $Smarty->security_settings['IF_FUNCS'] = array_merge($Smarty->security_settings['IF_FUNCS'], array('CheckPermission', 'MultiCheckPermission', 'GetValue', 'SetValue', 'Url', 'InSection', 'InCategory')); $Smarty->security_settings['MODIFIER_FUNCS'] = array_merge($Smarty->security_settings['MODIFIER_FUNCS'], array('sprintf')); $Smarty->secure_dir = array($Path); }
public function API($Url, $Params = NULL) { if (strpos($Url, '//') === FALSE) { $Url = self::$BaseApiUrl . trim($Url, '/'); } $Consumer = new OAuthConsumer(C('Plugins.SinaConnect.ConsumerKey'), C('Plugins.SinaConnect.Secret')); $AccessToken = $this->AccessToken(); $Request = OAuthRequest::from_consumer_and_token($Consumer, $AccessToken, 'GET', $Url, $Params); $SignatureMethod = new OAuthSignatureMethod_HMAC_SHA1(); $Request->sign_request($SignatureMethod, $Consumer, $AccessToken); $Curl = $this->_Curl($Request); $Response = curl_exec($Curl); $HttpCode = curl_getinfo($Curl, CURLINFO_HTTP_CODE); curl_close($Curl); if (StringEndsWith($Url, 'json', TRUE)) { $Result = @json_decode($Response) or $Response; } else { $Result = $Response; } if ($HttpCode == '200') { return $Result; } else { throw new OAuthException(GetValue('error', $Result, $Result), $HttpCode); } }
/** * Get the path of a view. * * @param string $View The name of the view. * @param string $Controller The name of the controller invoking the view or blank. * @param string $Folder The application folder or plugins/plugin folder. * @return string|false The path to the view or false if it wasn't found. * @deprecated */ function viewLocation($View, $Controller, $Folder) { deprecated('viewLocation()'); $Paths = array(); if (strpos($View, '/') !== false) { // This is a path to the view from the root. $Paths[] = $View; } else { $View = strtolower($View); $Controller = strtolower(StringEndsWith($Controller, 'Controller', true, true)); if ($Controller) { $Controller = '/' . $Controller; } $Extensions = array('tpl', 'php'); // 1. First we check the theme. if (Gdn::Controller() && ($Theme = Gdn::Controller()->Theme)) { foreach ($Extensions as $Ext) { $Paths[] = PATH_THEMES . "/{$Theme}/views{$Controller}/{$View}.{$Ext}"; } } // 2. Then we check the application/plugin. if (StringBeginsWith($Folder, 'plugins/')) { // This is a plugin view. foreach ($Extensions as $Ext) { $Paths[] = PATH_ROOT . "/{$Folder}/views{$Controller}/{$View}.{$Ext}"; } } else { // This is an application view. $Folder = strtolower($Folder); foreach ($Extensions as $Ext) { $Paths[] = PATH_APPLICATIONS . "/{$Folder}/views{$Controller}/{$View}.{$Ext}"; } if ($Folder != 'dashboard' && StringEndsWith($View, '.master')) { // This is a master view that can always fall back to the dashboard. foreach ($Extensions as $Ext) { $Paths[] = PATH_APPLICATIONS . "/dashboard/views{$Controller}/{$View}.{$Ext}"; } } } } // Now let's search the paths for the view. foreach ($Paths as $Path) { if (file_exists($Path)) { return $Path; } } Trace(array('view' => $View, 'controller' => $Controller, 'folder' => $Folder), 'View'); Trace($Paths, 'ViewLocation()'); return false; }