code
stringlengths 17
247k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public static function _callbackParseUrl($sPath, $aMatches)
{
$sFile = basename($aMatches[1]);
$sDirectory = dirname($aMatches[1]);
$sRootPath = realpath(BX_DIRECTORY_PATH_ROOT);
$sAbsolutePath = realpath($sPath . $sDirectory) . DIRECTORY_SEPARATOR . $sFile;
$sRootPath = str_replace(DIRECTORY_SEPARATOR, '/', $sRootPath);
$sAbsolutePath = str_replace(DIRECTORY_SEPARATOR, '/', $sAbsolutePath);
return 'url(' . bx_ltrim_str($sAbsolutePath, $sRootPath, BX_DOL_URL_ROOT) . ')';
} | Private callback function for CSS compiler.
@param string $sPath CSS file absolute path.
@param array $aMatches matched parts of image's URL.
@return string converted image's URL. | _callbackParseUrl | php | boonex/dolphin.pro | inc/classes/BxDolTemplate.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolTemplate.php | MIT |
function _wrapInTagCss($sFile)
{
if (!$sFile)
return '';
return "<link href=\"" . $sFile . "\" rel=\"stylesheet\" type=\"text/css\" />";
} | Wrap an URL to CSS file into CSS tag.
@param string $sFile - URL to CSS file.
@return string the result of operation. | _wrapInTagCss | php | boonex/dolphin.pro | inc/classes/BxDolTemplate.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolTemplate.php | MIT |
function _includeFiles($sType, &$aFiles)
{
$sMethod = '_wrapInTag' . ucfirst($sType);
$sResult = "";
foreach($aFiles as $aFile)
$sResult .= $this->$sMethod($aFile['url']);
return $sResult;
} | Include CSS/JS files without caching.
@param string $sType the file type (css or js)
@param array $aFiles CSS/JS files to be added to the page.
@return string result of operation. | _includeFiles | php | boonex/dolphin.pro | inc/classes/BxDolTemplate.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolTemplate.php | MIT |
function addInjection($sKey, $sType, $sData, $iReplace = 0)
{
$GLOBALS[$this->_sPrefix . 'Injections']['page_0'][$sKey][] = array(
'page_index' => 0,
'key' => $sKey,
'type' => $sType,
'data' => $sData,
'replace' => $iReplace
);
} | Static method to add ingection available on the current page only.
@param string $sKey - template's key.
@param string $sType - injection type(text, php).
@param string $sData - the data to be added.
@param integer $iReplace - replace already existed data or not. | addInjection | php | boonex/dolphin.pro | inc/classes/BxDolTemplate.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolTemplate.php | MIT |
function getValues($sXmlContent, $sXmlTagName)
{
$rParser = $this->createParser();
xml_parse_into_struct($rParser, $sXmlContent, $aValues, $aIndexes);
xml_parser_free($rParser);
$aTagIndexes = $aIndexes[strtoupper($sXmlTagName)];
$aTagIndexes = isset($aTagIndexes) ? $aTagIndexes : array();
$aReturnValues = array();
foreach($aTagIndexes as $iTagIndex)
$aReturnValues[$aValues[$iTagIndex]['attributes']['KEY']] = $aValues[$iTagIndex]['value'];
return $aReturnValues;
} | Gets the values of the given tag. | getValues | php | boonex/dolphin.pro | inc/classes/BxDolXml.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolXml.php | MIT |
function getData ()
{
return $this->_oDb->getByMonth($this->iYear, $this->iMonth, $this->iNextYear, $this->iNextMonth);
} | return records for current month | getData | php | boonex/dolphin.pro | inc/classes/BxDolTextCalendar.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolTextCalendar.php | MIT |
function getUnit (&$aData)
{
$sUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aData['uri'];
return '<div class="' . $this->sCssPrefix . '-calendar-unit"><a href="' . $sUrl . '" title="' . $aData['caption'] . '">' . $aData['caption'] . '</a></div>';
} | return html for data unit for some day. | getUnit | php | boonex/dolphin.pro | inc/classes/BxDolTextCalendar.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolTextCalendar.php | MIT |
function deleteMemberMenuCaches()
{
//remove all member_menu_keys files
$oCache = $this -> getCacheObject();
$oCache->removeAllByPrefix($this -> sMenuMemberKeysCache);
return $GLOBALS['MySQL']->cleanCache($this -> sMenuCacheFile);
} | Delete all member menu cache files
@return boolean | deleteMemberMenuCaches | php | boonex/dolphin.pro | inc/classes/BxDolMemberMenu.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolMemberMenu.php | MIT |
function __construct ($aChoice = '')
{
$this->aClasses = $GLOBALS['MySQL']->fromCache('sys_objects_search', 'getAllWithKey',
'SELECT `ID` as `id`,
`Title` as `title`,
`ClassName` as `class`,
`ClassPath` as `file`,
`ObjectName`
FROM `sys_objects_search`', 'ObjectName'
);
if (is_array($aChoice) && !empty($aChoice)) {
foreach ($aChoice as $sValue) {
if (isset($this->aClasses[$sValue]))
$this->aChoice[$sValue] = $this->aClasses[$sValue];
}
} else {
$this->aChoice = $this->aClasses;
}
} | Constructor
$aChoice - array of choosen classes (will take a part only existing in `sys_objects_search` table) | __construct | php | boonex/dolphin.pro | inc/classes/BxDolSearch.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolSearch.php | MIT |
function getRssUnitImage (&$a, $sField)
{
// override this functions to return image for rss unit
} | Return rss unit image (redeclared) | getRssUnitImage | php | boonex/dolphin.pro | inc/classes/BxDolSearch.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolSearch.php | MIT |
function getAlternativeName($sNickName)
{
$sRetNickName = '';
$iIndex = 1;
do {
if (!getID($sNickName . $iIndex))
$sRetNickName = $iIndex;
$iIndex++;
} while ($sRetNickName == '');
return $sRetNickName;
} | get profile's alternative nickname
@param $sNickName string
@return suffix to add to nickname to make it unique | getAlternativeName | php | boonex/dolphin.pro | inc/classes/BxDolConnectModule.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolConnectModule.php | MIT |
function isInstalled()
{
return true;
} | Are required php modules are installed for this cache engine ?
@return boolean | isInstalled | php | boonex/dolphin.pro | inc/classes/BxDolCache.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCache.php | MIT |
function checkAction ($iAction, $isPerformAction = false)
{
$iId = $this->_getAuthorId();
$check_res = checkAction($iId, $iAction, $isPerformAction);
return $check_res[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
} | check if user can post/edit or delete own comments | checkAction | php | boonex/dolphin.pro | inc/classes/BxDolCmts.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCmts.php | MIT |
function getProfileImageUrl( $imageNum )
{
} | return link to profile image only.
@param unknown_type $ID
@param unknown_type $imageNum | getProfileImageUrl | php | boonex/dolphin.pro | inc/classes/BxDolProfile.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolProfile.php | MIT |
function getProfileData()
{
global $aUser;
$bUseCacheSystem = ( getParam('enable_cache_system') == 'on' ) ? true : false;
$oPDb = new BxDolProfileQuery();
$sProfileCache = BX_DIRECTORY_PATH_CACHE . 'user' . $this -> _iProfileID . '.php';
if( $bUseCacheSystem && file_exists( $sProfileCache ) && is_file( $sProfileCache ) ) {
require_once($sProfileCache);
$this -> _aProfile = $aUser[$this -> _iProfileID];
} else
$this -> _aProfile = $oPDb -> getProfileDataById( $this -> _iProfileID );
//get couple data
if( $this -> _aProfile['Couple'] ) {
$this -> bCouple = true;
$this -> _iCoupleID = $this -> _aProfile['Couple'];
$sProfileCache = BX_DIRECTORY_PATH_CACHE . 'user' . $this -> _iCoupleID . '.php';
if( $bUseCacheSystem && file_exists( $sProfileCache ) && is_file( $sProfileCache ) ) {
require_once($sProfileCache);
$this -> _aCouple = $aUser[$this -> _iCoupleID];
} else
$this -> _aCouple = $oPDb -> getProfileDataById( $this -> _iCoupleID );
}
return $this -> _aProfile;
} | return assoc array of all frofile fields | getProfileData | php | boonex/dolphin.pro | inc/classes/BxDolProfile.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolProfile.php | MIT |
function updateProfileDataFile( $iProfileID )
{
} | function create cache data file
@param int $iProfileID | updateProfileDataFile | php | boonex/dolphin.pro | inc/classes/BxDolProfile.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolProfile.php | MIT |
function getMembershipStatus( $iPrifileID, $offer_upgrade = true, $credits = 0 )
{
} | Print code for membership status
$memberID - member ID
$offer_upgrade - will this code be printed at [c]ontrol [p]anel
$credits - will print credits status if $credits == 1 | getMembershipStatus | php | boonex/dolphin.pro | inc/classes/BxDolProfile.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolProfile.php | MIT |
static public function getObjectInstance($sObject)
{
if (isset($GLOBALS['bxDolClasses']['BxDolMemberInfo!'.$sObject]))
return $GLOBALS['bxDolClasses']['BxDolMemberInfo!'.$sObject];
$aObject = BxDolMemberInfoQuery::getMemberInfoObject($sObject);
if (!$aObject || !is_array($aObject))
return false;
$sClass = 'BxDolMemberInfo';
if (!empty($aObject['override_class_name'])) {
$sClass = $aObject['override_class_name'];
if (!empty($aObject['override_class_file']))
require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
else
bx_import($sClass);
}
$o = new $sClass($aObject);
return ($GLOBALS['bxDolClasses']['BxDolMemberInfo!'.$sObject] = $o);
} | Get object instance by object name
@param $sObject object name
@return object instance or false on error | getObjectInstance | php | boonex/dolphin.pro | inc/classes/BxDolMemberInfo.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolMemberInfo.php | MIT |
function updateMedia ($iEntryId, $aMediaAdd, $aMediaDelete, $sMediaType)
{
$aMediaValidated = $this->_validateMediaIds ($aMediaAdd);
$this->_oDb->updateMedia ($iEntryId, $aMediaValidated, $aMediaDelete, $sMediaType);
} | Update media in database
First it delete media ids from database, then adds new
Be carefull if you store more information than just a pair of ids
@param $iEntryId associated entry id
@param $aMedia media id's array
@param $sMediaType media type, like images, videos, etc | updateMedia | php | boonex/dolphin.pro | inc/classes/BxDolFormMedia.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolFormMedia.php | MIT |
function addExternalResources ()
{
$GLOBALS['oAdmTemplate']->addJs(array(
'jquery.ui.core.min.js',
'jquery.ui.widget.min.js',
'jquery.ui.mouse.min.js',
'jquery.ui.sortable.min.js',
));
$GLOBALS['oAdmTemplate']->addCss(array(
'mobile.css',
'mobile_builder.css',
));
} | Add external recources, like JS and CSS file | addExternalResources | php | boonex/dolphin.pro | inc/classes/BxDolAdminBuilder.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolAdminBuilder.php | MIT |
function getItem ($aItem)
{
// !!! override this
return $aItem['title'];
} | Override this function to return real item for dragging
@param $aItem array of item properties from database
@return ready html | getItem | php | boonex/dolphin.pro | inc/classes/BxDolAdminBuilder.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolAdminBuilder.php | MIT |
public function setTimezone($sTimezone)
{
$oTimeZone = new DateTimeZone($sTimezone);
$oDate = new DateTime('now', $oTimeZone);
$this->link->query('SET time_zone = "' . $oDate->format('P') . '"');
} | Sets mysql time zone for current session
@param string $sTimezone | setTimezone | php | boonex/dolphin.pro | inc/classes/BxDolDb.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolDb.php | MIT |
public function arrayToSQL($a, $sDiv = ',')
{
$s = '';
foreach($a as $k => $v)
$s .= "`{$k}` = " . $this->escape($v) . $sDiv;
return trim($s, $sDiv);
} | Convert array of key => values to SQL query.
Array keys are field names and array values are field values.
@param $a array
@param $sDiv fields separator, by default it is ',', another useful value is ' AND '
@return part of SQL query string | arrayToSQL | php | boonex/dolphin.pro | inc/classes/BxDolDb.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolDb.php | MIT |
function getData($sKey, $iTTL = false)
{
if (!xcache_isset($sKey))
return null;
return xcache_get($sKey);
} | Get data from shared memory cache
@param string $sKey - file name
@param int $iTTL - time to live
@return the data is got from cache. | getData | php | boonex/dolphin.pro | inc/classes/BxDolCacheXCache.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCacheXCache.php | MIT |
function setData($sKey, $mixedData, $iTTL = false)
{
$bResult = xcache_set($sKey, $mixedData, false === $iTTL ? $this->iTTL : $iTTL);
return $bResult;
} | Save data in shared memory cache
@param string $sKey - file name
@param mixed $mixedData - the data to be cached in the file
@param int $iTTL - time to live
@return boolean result of operation. | setData | php | boonex/dolphin.pro | inc/classes/BxDolCacheXCache.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCacheXCache.php | MIT |
function delData($sKey)
{
if (!xcache_isset($sKey))
return true;
return xcache_unset($sKey);
} | Delete cache from shared memory
@param string $sKey - file name
@return result of the operation | delData | php | boonex/dolphin.pro | inc/classes/BxDolCacheXCache.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCacheXCache.php | MIT |
function isAvailable()
{
return function_exists('xcache_set');
} | Check if xcache functions are available
@return boolean | isAvailable | php | boonex/dolphin.pro | inc/classes/BxDolCacheXCache.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCacheXCache.php | MIT |
function isInstalled()
{
return extension_loaded('xcache');
} | Check if xcache extension is loaded
@return boolean | isInstalled | php | boonex/dolphin.pro | inc/classes/BxDolCacheXCache.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCacheXCache.php | MIT |
function GenPermTableForModules($iType)
{
$aList = array ();
bx_import('BxDolModuleDb');
$oDbModules = new BxDolModuleDb();
$aModules = $oDbModules->getModules();
foreach ($aModules as $a) {
if (empty($a['path']) || !include(BX_DIRECTORY_PATH_MODULES . $a['path'] . 'install/config.php'))
continue;
if (empty($aConfig['install_permissions']) || !is_array($aConfig['install_permissions']['writable']))
continue;
foreach ($aConfig['install_permissions']['writable'] as $sPath) {
if (1 == $iType && is_dir(BX_DIRECTORY_PATH_MODULES . $a['path'] . $sPath))
$aList[] = basename(BX_DIRECTORY_PATH_MODULES) . '/' . $a['path'] . $sPath;
elseif (2 == $iType && is_file(BX_DIRECTORY_PATH_MODULES . $a['path'] . $sPath))
$aList[] = basename(BX_DIRECTORY_PATH_MODULES) . '/' . $a['path'] . $sPath;
}
}
return $this->GenArrElemPerm($aList, $iType);
} | Generate permissions table for modules
@param $iType - 1: folder, 2: file
@return HTML | GenPermTableForModules | php | boonex/dolphin.pro | inc/classes/BxDolAdminTools.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolAdminTools.php | MIT |
function actionMobileEntry($iId)
{
bx_import('BxDolMobileTemplate');
$oMobileTemplate = new BxDolMobileTemplate($this->_oConfig, $this->_oDb);
$oMobileTemplate->pageStart();
$aParams = array(
'sample_type' => 'id',
'id' => (int)$iId,
);
$aEntry = $this->_oDb->getEntries($aParams);
if (empty($aEntry)) {
$oMobileTemplate->displayPageNotFound();
return;
}
echo '<h1>' . $aEntry['caption'] . '</h1>';
echo getLocaleDate($aEntry['when_uts'], BX_DOL_LOCALE_DATE);
echo $aEntry['content'];
$oMobileTemplate->pageCode($aEntry['caption']);
} | Entry view page for mobile app | actionMobileEntry | php | boonex/dolphin.pro | inc/classes/BxDolTextModule.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolTextModule.php | MIT |
function isAvailable()
{
return function_exists('apc_store');
} | Check if apc cache functions are available
@return boolean | isAvailable | php | boonex/dolphin.pro | inc/classes/BxDolCacheAPC.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCacheAPC.php | MIT |
function isInstalled()
{
return extension_loaded('apc');
} | Check if apc extension is loaded
@return boolean | isInstalled | php | boonex/dolphin.pro | inc/classes/BxDolCacheAPC.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCacheAPC.php | MIT |
static public function getObjectInstance($sObject = false)
{
if (!$sObject)
$sObject = getParam('sys_captcha_default');
if (isset($GLOBALS['bxDolClasses']['BxDolCaptcha!'.$sObject]))
return $GLOBALS['bxDolClasses']['BxDolCaptcha!'.$sObject];
$aObject = BxDolCaptchaQuery::getCaptchaObject($sObject);
if (!$aObject || !is_array($aObject))
return false;
if (empty($aObject['override_class_name']))
return false;
$sClass = $aObject['override_class_name'];
if (!empty($aObject['override_class_file']))
require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
else
bx_import($sClass);
$o = new $sClass($aObject);
if (!$o->isAvailable())
return false;
return ($GLOBALS['bxDolClasses']['BxDolCaptcha!'.$sObject] = $o);
} | Get captcha object instance by object name
@param $sObject object name
@return object instance or false on error | getObjectInstance | php | boonex/dolphin.pro | inc/classes/BxDolCaptcha.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCaptcha.php | MIT |
public function isAvailable ()
{
// override this function in particular class
} | Check if captcha is available, like all API keys are specified. | isAvailable | php | boonex/dolphin.pro | inc/classes/BxDolCaptcha.php | https://github.com/boonex/dolphin.pro/blob/master/inc/classes/BxDolCaptcha.php | MIT |
public function __construct($storage = null)
{
if (is_null($storage) || is_array($storage)) {
$storage = new Memory((array) $storage);
}
if (!$storage instanceof ScopeStorageInterface) {
throw new \InvalidArgumentException("Argument 1 to OAuth2\Scope must be null, an array, or instance of OAuth2\Storage\ScopeInterface");
}
$this->storage = $storage;
} | @param mixed @storage
Either an array of supported scopes, or an instance of OAuth2\Storage\ScopeInterface | __construct | php | boonex/dolphin.pro | plugins/OAuth2/Scope.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Scope.php | MIT |
public function checkScope($required_scope, $available_scope)
{
$required_scope = explode(' ', trim($required_scope));
$available_scope = explode(' ', trim($available_scope));
return (count(array_diff($required_scope, $available_scope)) == 0);
} | Check if everything in required scope is contained in available scope.
@param $required_scope
A space-separated string of scopes.
@return
TRUE if everything in required scope is contained in available scope,
and FALSE if it isn't.
@see http://tools.ietf.org/html/rfc6749#section-7
@ingroup oauth2_section_7 | checkScope | php | boonex/dolphin.pro | plugins/OAuth2/Scope.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Scope.php | MIT |
public function scopeExists($scope)
{
// Check reserved scopes first.
$scope = explode(' ', trim($scope));
$reservedScope = $this->getReservedScopes();
$nonReservedScopes = array_diff($scope, $reservedScope);
if (count($nonReservedScopes) == 0) {
return true;
} else {
// Check the storage for non-reserved scopes.
$nonReservedScopes = implode(' ', $nonReservedScopes);
return $this->storage->scopeExists($nonReservedScopes);
}
} | Check if the provided scope exists in storage.
@param $scope
A space-separated string of scopes.
@return
TRUE if it exists, FALSE otherwise. | scopeExists | php | boonex/dolphin.pro | plugins/OAuth2/Scope.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Scope.php | MIT |
public function getReservedScopes()
{
return array('openid', 'offline_access');
} | Get reserved scopes needed by the server.
In case OpenID Connect is used, these scopes must include:
'openid', offline_access'.
@return
An array of reserved scopes. | getReservedScopes | php | boonex/dolphin.pro | plugins/OAuth2/Scope.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Scope.php | MIT |
protected function buildHeader($name, $value)
{
return sprintf("%s: %s\n", $name, $value);
} | Returns the build header line.
@param string $name The header name
@param string $value The header value
@return string The built header line | buildHeader | php | boonex/dolphin.pro | plugins/OAuth2/Response.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Response.php | MIT |
public function getContent($asResource = false)
{
if (false === $this->content || (true === $asResource && null !== $this->content)) {
throw new \LogicException('getContent() can only be called once when using the resource return type.');
}
if (true === $asResource) {
$this->content = false;
return fopen('php://input', 'rb');
}
if (null === $this->content) {
$this->content = file_get_contents('php://input');
}
return $this->content;
} | Returns the request body content.
@param Boolean $asResource If true, a resource will be returned
@return string|resource The request body content or a resource to read the body stream. | getContent | php | boonex/dolphin.pro | plugins/OAuth2/Request.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Request.php | MIT |
public function setAuthorizeController(AuthorizeControllerInterface $authorizeController)
{
$this->authorizeController = $authorizeController;
} | every getter deserves a setter | setAuthorizeController | php | boonex/dolphin.pro | plugins/OAuth2/Server.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Server.php | MIT |
public function handleUserInfoRequest(RequestInterface $request, ResponseInterface $response = null)
{
$this->response = is_null($response) ? new Response() : $response;
$this->getUserInfoController()->handleUserInfoRequest($request, $this->response);
return $this->response;
} | Return claims about the authenticated end-user.
This would be called from the "/UserInfo" endpoint as defined in the spec.
@param $request - OAuth2\RequestInterface
Request object to grant access token
@param $response - OAuth2\ResponseInterface
Response object containing error messages (failure) or user claims (success)
@throws InvalidArgumentException
@throws LogicException
@see http://openid.net/specs/openid-connect-core-1_0.html#UserInfo | handleUserInfoRequest | php | boonex/dolphin.pro | plugins/OAuth2/Server.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Server.php | MIT |
public function handleTokenRequest(RequestInterface $request, ResponseInterface $response = null)
{
$this->response = is_null($response) ? new Response() : $response;
$this->getTokenController()->handleTokenRequest($request, $this->response);
return $this->response;
} | Grant or deny a requested access token.
This would be called from the "/token" endpoint as defined in the spec.
Obviously, you can call your endpoint whatever you want.
@param $request - OAuth2\RequestInterface
Request object to grant access token
@param $response - OAuth2\ResponseInterface
Response object containing error messages (failure) or access token (success)
@throws InvalidArgumentException
@throws LogicException
@see http://tools.ietf.org/html/rfc6749#section-4
@see http://tools.ietf.org/html/rfc6749#section-10.6
@see http://tools.ietf.org/html/rfc6749#section-4.1.3
@ingroup oauth2_section_4 | handleTokenRequest | php | boonex/dolphin.pro | plugins/OAuth2/Server.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Server.php | MIT |
public function handleRevokeRequest(RequestInterface $request, ResponseInterface $response = null)
{
$this->response = is_null($response) ? new Response() : $response;
$this->getTokenController()->handleRevokeRequest($request, $this->response);
return $this->response;
} | Handle a revoke token request
This would be called from the "/revoke" endpoint as defined in the draft Token Revocation spec
@see https://tools.ietf.org/html/rfc7009#section-2
@param RequestInterface $request
@param ResponseInterface $response
@return Response|ResponseInterface | handleRevokeRequest | php | boonex/dolphin.pro | plugins/OAuth2/Server.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Server.php | MIT |
public function handleAuthorizeRequest(RequestInterface $request, ResponseInterface $response, $is_authorized, $user_id = null)
{
$this->response = $response;
$this->getAuthorizeController()->handleAuthorizeRequest($request, $this->response, $is_authorized, $user_id);
return $this->response;
} | Redirect the user appropriately after approval.
After the user has approved or denied the resource request the
authorization server should call this function to redirect the user
appropriately.
@param $request
The request should have the follow parameters set in the querystring:
- response_type: The requested response: an access token, an
authorization code, or both.
- client_id: The client identifier as described in Section 2.
- redirect_uri: An absolute URI to which the authorization server
will redirect the user-agent to when the end-user authorization
step is completed.
- scope: (optional) The scope of the resource request expressed as a
list of space-delimited strings.
- state: (optional) An opaque value used by the client to maintain
state between the request and callback.
@param $is_authorized
TRUE or FALSE depending on whether the user authorized the access.
@param $user_id
Identifier of user who authorized the client
@see http://tools.ietf.org/html/rfc6749#section-4
@ingroup oauth2_section_4 | handleAuthorizeRequest | php | boonex/dolphin.pro | plugins/OAuth2/Server.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Server.php | MIT |
public function validateAuthorizeRequest(RequestInterface $request, ResponseInterface $response = null)
{
$this->response = is_null($response) ? new Response() : $response;
$value = $this->getAuthorizeController()->validateAuthorizeRequest($request, $this->response);
return $value;
} | Pull the authorization request data out of the HTTP request.
- The redirect_uri is OPTIONAL as per draft 20. But your implementation can enforce it
by setting $config['enforce_redirect'] to true.
- The state is OPTIONAL but recommended to enforce CSRF. Draft 21 states, however, that
CSRF protection is MANDATORY. You can enforce this by setting the $config['enforce_state'] to true.
The draft specifies that the parameters should be retrieved from GET, override the Response
object to change this
@return
The authorization parameters so the authorization server can prompt
the user for approval if valid.
@see http://tools.ietf.org/html/rfc6749#section-4.1.1
@see http://tools.ietf.org/html/rfc6749#section-10.12
@ingroup oauth2_section_3 | validateAuthorizeRequest | php | boonex/dolphin.pro | plugins/OAuth2/Server.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Server.php | MIT |
protected function createDefaultJwtAccessTokenResponseType()
{
if (!isset($this->storages['public_key'])) {
throw new \LogicException("You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use crypto tokens");
}
$tokenStorage = null;
if (isset($this->storages['access_token'])) {
$tokenStorage = $this->storages['access_token'];
}
$refreshStorage = null;
if (isset($this->storages['refresh_token'])) {
$refreshStorage = $this->storages['refresh_token'];
}
$config = array_intersect_key($this->config, array_flip(explode(' ', 'store_encrypted_token_string issuer access_lifetime refresh_token_lifetime')));
return new JwtAccessToken($this->storages['public_key'], $tokenStorage, $refreshStorage, $config);
} | For Authorize and Token Controllers | createDefaultJwtAccessTokenResponseType | php | boonex/dolphin.pro | plugins/OAuth2/Server.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Server.php | MIT |
public static function register($dir = null)
{
ini_set('unserialize_callback_func', 'spl_autoload_call');
spl_autoload_register(array(new self($dir), 'autoload'));
} | Registers OAuth2\Autoloader as an SPL autoloader. | register | php | boonex/dolphin.pro | plugins/OAuth2/Autoloader.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Autoloader.php | MIT |
public function autoload($class)
{
if (0 !== strpos($class, 'OAuth2')) {
return;
}
if (file_exists($file = $this->dir.'/'.str_replace('\\', '/', $class).'.php')) {
require $file;
}
} | Handles autoloading of classes.
@param string $class A class name.
@return boolean Returns true if the class has been loaded | autoload | php | boonex/dolphin.pro | plugins/OAuth2/Autoloader.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Autoloader.php | MIT |
public function needsIdToken($request_scope)
{
// see if the "openid" scope exists in the requested scope
return $this->scopeUtil->checkScope('openid', $request_scope);
} | Returns whether the current request needs to generate an id token.
ID Tokens are a part of the OpenID Connect specification, so this
method checks whether OpenID Connect is enabled in the server settings
and whether the openid scope was requested.
@param $request_scope
A space-separated string of scopes.
@return
TRUE if an id token is needed, FALSE otherwise. | needsIdToken | php | boonex/dolphin.pro | plugins/OAuth2/OpenID/Controller/AuthorizeController.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/OpenID/Controller/AuthorizeController.php | MIT |
public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null, $id_token = null)
{
$code = $this->generateAuthorizationCode();
$this->storage->setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, time() + $this->config['auth_code_lifetime'], $scope, $id_token);
return $code;
} | Handle the creation of the authorization code.
@param $client_id
Client identifier related to the authorization code
@param $user_id
User ID associated with the authorization code
@param $redirect_uri
An absolute URI to which the authorization server will redirect the
user-agent to when the end-user authorization step is completed.
@param $scope
(optional) Scopes to be stored in space-separated string.
@param $id_token
(optional) The OpenID Connect id_token.
@see http://tools.ietf.org/html/rfc6749#section-4
@ingroup oauth2_section_4 | createAuthorizationCode | php | boonex/dolphin.pro | plugins/OAuth2/OpenID/ResponseType/AuthorizationCode.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/OpenID/ResponseType/AuthorizationCode.php | MIT |
public function requestHasToken(RequestInterface $request)
{
$headers = $request->headers('AUTHORIZATION');
// check the header, then the querystring, then the request body
return !empty($headers) || (bool) ($request->request($this->config['token_param_name'])) || (bool) ($request->query($this->config['token_param_name']));
} | Check if the request has supplied token
@see https://github.com/bshaffer/oauth2-server-php/issues/349#issuecomment-37993588 | requestHasToken | php | boonex/dolphin.pro | plugins/OAuth2/TokenType/Bearer.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/TokenType/Bearer.php | MIT |
public function getAccessTokenParameter(RequestInterface $request, ResponseInterface $response)
{
$headers = $request->headers('AUTHORIZATION');
/**
* Ensure more than one method is not used for including an
* access token
*
* @see http://tools.ietf.org/html/rfc6750#section-3.1
*/
$methodsUsed = !empty($headers) + (bool) ($request->query($this->config['token_param_name'])) + (bool) ($request->request($this->config['token_param_name']));
if ($methodsUsed > 1) {
$response->setError(400, 'invalid_request', 'Only one method may be used to authenticate at a time (Auth header, GET or POST)');
return null;
}
/**
* If no authentication is provided, set the status code
* to 401 and return no other error information
*
* @see http://tools.ietf.org/html/rfc6750#section-3.1
*/
if ($methodsUsed == 0) {
$response->setStatusCode(401);
return null;
}
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (!preg_match('/' . $this->config['token_bearer_header_name'] . '\s(\S+)/i', $headers, $matches)) {
$response->setError(400, 'invalid_request', 'Malformed auth header');
return null;
}
return $matches[1];
}
if ($request->request($this->config['token_param_name'])) {
// // POST: Get the token from POST data
if (!in_array(strtolower($request->server('REQUEST_METHOD')), array('post', 'put'))) {
$response->setError(400, 'invalid_request', 'When putting the token in the body, the method must be POST or PUT', '#section-2.2');
return null;
}
$contentType = $request->server('CONTENT_TYPE');
if (false !== $pos = strpos($contentType, ';')) {
$contentType = substr($contentType, 0, $pos);
}
if ($contentType !== null && $contentType != 'application/x-www-form-urlencoded') {
// IETF specifies content-type. NB: Not all webservers populate this _SERVER variable
// @see http://tools.ietf.org/html/rfc6750#section-2.2
$response->setError(400, 'invalid_request', 'The content type for POST requests must be "application/x-www-form-urlencoded"');
return null;
}
return $request->request($this->config['token_param_name']);
}
// GET method
return $request->query($this->config['token_param_name']);
} | This is a convenience function that can be used to get the token, which can then
be passed to getAccessTokenData(). The constraints specified by the draft are
attempted to be adheared to in this method.
As per the Bearer spec (draft 8, section 2) - there are three ways for a client
to specify the bearer token, in order of preference: Authorization Header,
POST and GET.
NB: Resource servers MUST accept tokens via the Authorization scheme
(http://tools.ietf.org/html/rfc6750#section-2).
@todo Should we enforce TLS/SSL in this function?
@see http://tools.ietf.org/html/rfc6750#section-2.1
@see http://tools.ietf.org/html/rfc6750#section-2.2
@see http://tools.ietf.org/html/rfc6750#section-2.3
Old Android version bug (at least with version 2.2)
@see http://code.google.com/p/android/issues/detail?id=6684 | getAccessTokenParameter | php | boonex/dolphin.pro | plugins/OAuth2/TokenType/Bearer.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/TokenType/Bearer.php | MIT |
private function dynamo2array($dynamodbResult)
{
$result = array();
foreach ($dynamodbResult["Item"] as $key => $val) {
$result[$key] = $val["S"];
$result[] = $val["S"];
}
return $result;
} | Transform dynamodb resultset to an array.
@param $dynamodbResult
@return $array | dynamo2array | php | boonex/dolphin.pro | plugins/OAuth2/Storage/DynamoDB.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Storage/DynamoDB.php | MIT |
public function getBuildSql($dbName = 'oauth2_server_php')
{
$sql = "
CREATE TABLE {$this->config['client_table']} (
client_id VARCHAR(80) NOT NULL,
client_secret VARCHAR(80) NOT NULL,
redirect_uri VARCHAR(2000),
grant_types VARCHAR(80),
scope VARCHAR(4000),
user_id VARCHAR(80),
PRIMARY KEY (client_id)
);
CREATE TABLE {$this->config['access_token_table']} (
access_token VARCHAR(40) NOT NULL,
client_id VARCHAR(80) NOT NULL,
user_id VARCHAR(80),
expires TIMESTAMP NOT NULL,
scope VARCHAR(4000),
PRIMARY KEY (access_token)
);
CREATE TABLE {$this->config['code_table']} (
authorization_code VARCHAR(40) NOT NULL,
client_id VARCHAR(80) NOT NULL,
user_id VARCHAR(80),
redirect_uri VARCHAR(2000),
expires TIMESTAMP NOT NULL,
scope VARCHAR(4000),
id_token VARCHAR(1000),
PRIMARY KEY (authorization_code)
);
CREATE TABLE {$this->config['refresh_token_table']} (
refresh_token VARCHAR(40) NOT NULL,
client_id VARCHAR(80) NOT NULL,
user_id VARCHAR(80),
expires TIMESTAMP NOT NULL,
scope VARCHAR(4000),
PRIMARY KEY (refresh_token)
);
CREATE TABLE {$this->config['user_table']} (
username VARCHAR(80),
password VARCHAR(80),
first_name VARCHAR(80),
last_name VARCHAR(80),
email VARCHAR(80),
email_verified BOOLEAN,
scope VARCHAR(4000)
);
CREATE TABLE {$this->config['scope_table']} (
scope VARCHAR(80) NOT NULL,
is_default BOOLEAN,
PRIMARY KEY (scope)
);
CREATE TABLE {$this->config['jwt_table']} (
client_id VARCHAR(80) NOT NULL,
subject VARCHAR(80),
public_key VARCHAR(2000) NOT NULL
);
CREATE TABLE {$this->config['jti_table']} (
issuer VARCHAR(80) NOT NULL,
subject VARCHAR(80),
audiance VARCHAR(80),
expires TIMESTAMP NOT NULL,
jti VARCHAR(2000) NOT NULL
);
CREATE TABLE {$this->config['public_key_table']} (
client_id VARCHAR(80),
public_key VARCHAR(2000),
private_key VARCHAR(2000),
encryption_algorithm VARCHAR(100) DEFAULT 'RS256'
)
";
return $sql;
} | DDL to create OAuth2 database and tables for PDO storage
@see https://github.com/dsquier/oauth2-server-php-mysql | getBuildSql | php | boonex/dolphin.pro | plugins/OAuth2/Storage/Pdo.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Storage/Pdo.php | MIT |
public function __construct(PublicKeyInterface $publicKeyStorage, AccessTokenInterface $tokenStorage = null, EncryptionInterface $encryptionUtil = null)
{
$this->publicKeyStorage = $publicKeyStorage;
$this->tokenStorage = $tokenStorage;
if (is_null($encryptionUtil)) {
$encryptionUtil = new Jwt;
}
$this->encryptionUtil = $encryptionUtil;
} | @param OAuth2\Encryption\PublicKeyInterface $publicKeyStorage the public key encryption to use
@param OAuth2\Storage\AccessTokenInterface $tokenStorage OPTIONAL persist the access token to another storage. This is useful if
you want to retain access token grant information somewhere, but
is not necessary when using this grant type.
@param OAuth2\Encryption\EncryptionInterface $encryptionUtil OPTIONAL class to use for "encode" and "decode" functions. | __construct | php | boonex/dolphin.pro | plugins/OAuth2/Storage/JwtAccessToken.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Storage/JwtAccessToken.php | MIT |
public function getQuerystringIdentifier()
{
return 'urn:ietf:params:oauth:grant-type:jwt-bearer';
} | Returns the grant_type get parameter to identify the grant type request as JWT bearer authorization grant.
@return
The string identifier for grant_type.
@see OAuth2\GrantType\GrantTypeInterface::getQuerystringIdentifier() | getQuerystringIdentifier | php | boonex/dolphin.pro | plugins/OAuth2/GrantType/JwtBearer.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/GrantType/JwtBearer.php | MIT |
public function validateRequest(RequestInterface $request, ResponseInterface $response)
{
if (!$request->request("assertion")) {
$response->setError(400, 'invalid_request', 'Missing parameters: "assertion" required');
return null;
}
// Store the undecoded JWT for later use
$undecodedJWT = $request->request('assertion');
// Decode the JWT
$jwt = $this->jwtUtil->decode($request->request('assertion'), null, false);
if (!$jwt) {
$response->setError(400, 'invalid_request', "JWT is malformed");
return null;
}
// ensure these properties contain a value
// @todo: throw malformed error for missing properties
$jwt = array_merge(array(
'scope' => null,
'iss' => null,
'sub' => null,
'aud' => null,
'exp' => null,
'nbf' => null,
'iat' => null,
'jti' => null,
'typ' => null,
), $jwt);
if (!isset($jwt['iss'])) {
$response->setError(400, 'invalid_grant', "Invalid issuer (iss) provided");
return null;
}
if (!isset($jwt['sub'])) {
$response->setError(400, 'invalid_grant', "Invalid subject (sub) provided");
return null;
}
if (!isset($jwt['exp'])) {
$response->setError(400, 'invalid_grant', "Expiration (exp) time must be present");
return null;
}
// Check expiration
if (ctype_digit($jwt['exp'])) {
if ($jwt['exp'] <= time()) {
$response->setError(400, 'invalid_grant', "JWT has expired");
return null;
}
} else {
$response->setError(400, 'invalid_grant', "Expiration (exp) time must be a unix time stamp");
return null;
}
// Check the not before time
if ($notBefore = $jwt['nbf']) {
if (ctype_digit($notBefore)) {
if ($notBefore > time()) {
$response->setError(400, 'invalid_grant', "JWT cannot be used before the Not Before (nbf) time");
return null;
}
} else {
$response->setError(400, 'invalid_grant', "Not Before (nbf) time must be a unix time stamp");
return null;
}
}
// Check the audience if required to match
if (!isset($jwt['aud']) || ($jwt['aud'] != $this->audience)) {
$response->setError(400, 'invalid_grant', "Invalid audience (aud)");
return null;
}
// Check the jti (nonce)
// @see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-13#section-4.1.7
if (isset($jwt['jti'])) {
$jti = $this->storage->getJti($jwt['iss'], $jwt['sub'], $jwt['aud'], $jwt['exp'], $jwt['jti']);
//Reject if jti is used and jwt is still valid (exp parameter has not expired).
if ($jti && $jti['expires'] > time()) {
$response->setError(400, 'invalid_grant', "JSON Token Identifier (jti) has already been used");
return null;
} else {
$this->storage->setJti($jwt['iss'], $jwt['sub'], $jwt['aud'], $jwt['exp'], $jwt['jti']);
}
}
// Get the iss's public key
// @see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06#section-4.1.1
if (!$key = $this->storage->getClientKey($jwt['iss'], $jwt['sub'])) {
$response->setError(400, 'invalid_grant', "Invalid issuer (iss) or subject (sub) provided");
return null;
}
// Verify the JWT
if (!$this->jwtUtil->decode($undecodedJWT, $key, $this->allowedAlgorithms)) {
$response->setError(400, 'invalid_grant', "JWT failed signature verification");
return null;
}
$this->jwt = $jwt;
return true;
} | Validates the data from the decoded JWT.
@return
TRUE if the JWT request is valid and can be decoded. Otherwise, FALSE is returned.
@see OAuth2\GrantType\GrantTypeInterface::getTokenData() | validateRequest | php | boonex/dolphin.pro | plugins/OAuth2/GrantType/JwtBearer.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/GrantType/JwtBearer.php | MIT |
public function createAccessToken(AccessTokenInterface $accessToken, $client_id, $user_id, $scope)
{
$includeRefreshToken = false;
return $accessToken->createAccessToken($client_id, $user_id, $scope, $includeRefreshToken);
} | Creates an access token that is NOT associated with a refresh token.
If a subject (sub) the name of the user/account we are accessing data on behalf of.
@see OAuth2\GrantType\GrantTypeInterface::createAccessToken() | createAccessToken | php | boonex/dolphin.pro | plugins/OAuth2/GrantType/JwtBearer.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/GrantType/JwtBearer.php | MIT |
public function addGrantType(GrantTypeInterface $grantType, $identifier = null)
{
if (is_null($identifier) || is_numeric($identifier)) {
$identifier = $grantType->getQuerystringIdentifier();
}
$this->grantTypes[$identifier] = $grantType;
} | addGrantType
@param grantType - OAuth2\GrantTypeInterface
the grant type to add for the specified identifier
@param identifier - string
a string passed in as "grant_type" in the response that will call this grantType | addGrantType | php | boonex/dolphin.pro | plugins/OAuth2/Controller/TokenController.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Controller/TokenController.php | MIT |
public function revokeToken(RequestInterface $request, ResponseInterface $response)
{
if (strtolower($request->server('REQUEST_METHOD')) != 'post') {
$response->setError(405, 'invalid_request', 'The request method must be POST when revoking an access token', '#section-3.2');
$response->addHttpHeaders(array('Allow' => 'POST'));
return null;
}
$token_type_hint = $request->request('token_type_hint');
if (!in_array($token_type_hint, array(null, 'access_token', 'refresh_token'), true)) {
$response->setError(400, 'invalid_request', 'Token type hint must be either \'access_token\' or \'refresh_token\'');
return null;
}
$token = $request->request('token');
if ($token === null) {
$response->setError(400, 'invalid_request', 'Missing token parameter to revoke');
return null;
}
// @todo remove this check for v2.0
if (!method_exists($this->accessToken, 'revokeToken')) {
$class = get_class($this->accessToken);
throw new \RuntimeException("AccessToken {$class} does not implement required revokeToken method");
}
$this->accessToken->revokeToken($token, $token_type_hint);
return true;
} | Revoke a refresh or access token. Returns true on success and when tokens are invalid
Note: invalid tokens do not cause an error response since the client
cannot handle such an error in a reasonable way. Moreover, the
purpose of the revocation request, invalidating the particular token,
is already achieved.
@param RequestInterface $request
@param ResponseInterface $response
@return bool|null | revokeToken | php | boonex/dolphin.pro | plugins/OAuth2/Controller/TokenController.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Controller/TokenController.php | MIT |
protected function validateRedirectUri($inputUri, $registeredUriString)
{
if (!$inputUri || !$registeredUriString) {
return false; // if either one is missing, assume INVALID
}
$registered_uris = preg_split('/\s+/', $registeredUriString);
foreach ($registered_uris as $registered_uri) {
if ($this->config['require_exact_redirect_uri']) {
// the input uri is validated against the registered uri using exact match
if (strcmp($inputUri, $registered_uri) === 0) {
return true;
}
} else {
// the input uri is validated against the registered uri using case-insensitive match of the initial string
// i.e. additional query parameters may be applied
if (strcasecmp(substr($inputUri, 0, strlen($registered_uri)), $registered_uri) === 0) {
return true;
}
}
}
return false;
} | Internal method for validating redirect URI supplied
@param string $inputUri The submitted URI to be validated
@param string $registeredUriString The allowed URI(s) to validate against. Can be a space-delimited string of URIs to
allow for multiple URIs
@see http://tools.ietf.org/html/rfc6749#section-3.1.2 | validateRedirectUri | php | boonex/dolphin.pro | plugins/OAuth2/Controller/AuthorizeController.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Controller/AuthorizeController.php | MIT |
public function getScope()
{
return $this->scope;
} | Convenience methods to access the parameters derived from the validated request | getScope | php | boonex/dolphin.pro | plugins/OAuth2/Controller/AuthorizeController.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Controller/AuthorizeController.php | MIT |
protected function generateJwtHeader($payload, $algorithm)
{
return array(
'typ' => 'JWT',
'alg' => $algorithm,
);
} | Override to create a custom header | generateJwtHeader | php | boonex/dolphin.pro | plugins/OAuth2/Encryption/Jwt.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/Encryption/Jwt.php | MIT |
public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true)
{
$token = array(
"access_token" => $this->generateAccessToken(),
"expires_in" => $this->config['access_lifetime'],
"token_type" => $this->config['token_type'],
"scope" => $scope
);
$this->tokenStorage->setAccessToken($token["access_token"], $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope);
/*
* Issue a refresh token also, if we support them
*
* Refresh Tokens are considered supported if an instance of OAuth2\Storage\RefreshTokenInterface
* is supplied in the constructor
*/
if ($includeRefreshToken && $this->refreshStorage) {
$token["refresh_token"] = $this->generateRefreshToken();
$expires = 0;
if ($this->config['refresh_token_lifetime'] > 0) {
$expires = time() + $this->config['refresh_token_lifetime'];
}
$this->refreshStorage->setRefreshToken($token['refresh_token'], $client_id, $user_id, $expires, $scope);
}
return $token;
} | Handle the creation of access token, also issue refresh token if supported / desirable.
@param $client_id client identifier related to the access token.
@param $user_id user ID associated with the access token
@param $scope OPTIONAL scopes to be stored in space-separated string.
@param bool $includeRefreshToken if true, a new refresh_token will be added to the response
@see http://tools.ietf.org/html/rfc6749#section-5
@ingroup oauth2_section_5 | createAccessToken | php | boonex/dolphin.pro | plugins/OAuth2/ResponseType/AccessToken.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/ResponseType/AccessToken.php | MIT |
protected function generateAccessToken()
{
if (function_exists('mcrypt_create_iv')) {
$randomData = mcrypt_create_iv(20, MCRYPT_DEV_URANDOM);
if ($randomData !== false && strlen($randomData) === 20) {
return bin2hex($randomData);
}
}
if (function_exists('openssl_random_pseudo_bytes')) {
$randomData = openssl_random_pseudo_bytes(20);
if ($randomData !== false && strlen($randomData) === 20) {
return bin2hex($randomData);
}
}
if (@file_exists('/dev/urandom')) { // Get 100 bytes of random data
$randomData = file_get_contents('/dev/urandom', false, null, 0, 20);
if ($randomData !== false && strlen($randomData) === 20) {
return bin2hex($randomData);
}
}
// Last resort which you probably should just get rid of:
$randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
return substr(hash('sha512', $randomData), 0, 40);
} | Generates an unique access token.
Implementing classes may want to override this function to implement
other access token generation schemes.
@return
An unique access token.
@ingroup oauth2_section_4 | generateAccessToken | php | boonex/dolphin.pro | plugins/OAuth2/ResponseType/AccessToken.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/ResponseType/AccessToken.php | MIT |
protected function generateRefreshToken()
{
return $this->generateAccessToken(); // let's reuse the same scheme for token generation
} | Generates an unique refresh token
Implementing classes may want to override this function to implement
other refresh token generation schemes.
@return
An unique refresh.
@ingroup oauth2_section_4
@see OAuth2::generateAccessToken() | generateRefreshToken | php | boonex/dolphin.pro | plugins/OAuth2/ResponseType/AccessToken.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/ResponseType/AccessToken.php | MIT |
public function revokeToken($token, $tokenTypeHint = null)
{
if ($tokenTypeHint == 'refresh_token') {
if ($this->refreshStorage && $revoked = $this->refreshStorage->unsetRefreshToken($token)) {
return true;
}
}
/** @TODO remove in v2 */
if (!method_exists($this->tokenStorage, 'unsetAccessToken')) {
throw new \RuntimeException(
sprintf('Token storage %s must implement unsetAccessToken method', get_class($this->tokenStorage)
));
}
$revoked = $this->tokenStorage->unsetAccessToken($token);
// if a typehint is supplied and fails, try other storages
// @see https://tools.ietf.org/html/rfc7009#section-2.1
if (!$revoked && $tokenTypeHint != 'refresh_token') {
if ($this->refreshStorage) {
$revoked = $this->refreshStorage->unsetRefreshToken($token);
}
}
return $revoked;
} | Handle the revoking of refresh tokens, and access tokens if supported / desirable
RFC7009 specifies that "If the server is unable to locate the token using
the given hint, it MUST extend its search across all of its supported token types"
@param $token
@param null $tokenTypeHint
@return boolean | revokeToken | php | boonex/dolphin.pro | plugins/OAuth2/ResponseType/AccessToken.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/ResponseType/AccessToken.php | MIT |
public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true)
{
// token to encrypt
$expires = time() + $this->config['access_lifetime'];
$id = $this->generateAccessToken();
$jwtAccessToken = array(
'id' => $id, // for BC (see #591)
'jti' => $id,
'iss' => $this->config['issuer'],
'aud' => $client_id,
'sub' => $user_id,
'exp' => $expires,
'iat' => time(),
'token_type' => $this->config['token_type'],
'scope' => $scope
);
/*
* Encode the token data into a single access_token string
*/
$access_token = $this->encodeToken($jwtAccessToken, $client_id);
/*
* Save the token to a secondary storage. This is implemented on the
* OAuth2\Storage\JwtAccessToken side, and will not actually store anything,
* if no secondary storage has been supplied
*/
$token_to_store = $this->config['store_encrypted_token_string'] ? $access_token : $jwtAccessToken['id'];
$this->tokenStorage->setAccessToken($token_to_store, $client_id, $user_id, $this->config['access_lifetime'] ? time() + $this->config['access_lifetime'] : null, $scope);
// token to return to the client
$token = array(
'access_token' => $access_token,
'expires_in' => $this->config['access_lifetime'],
'token_type' => $this->config['token_type'],
'scope' => $scope
);
/*
* Issue a refresh token also, if we support them
*
* Refresh Tokens are considered supported if an instance of OAuth2\Storage\RefreshTokenInterface
* is supplied in the constructor
*/
if ($includeRefreshToken && $this->refreshStorage) {
$refresh_token = $this->generateRefreshToken();
$expires = 0;
if ($this->config['refresh_token_lifetime'] > 0) {
$expires = time() + $this->config['refresh_token_lifetime'];
}
$this->refreshStorage->setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope);
$token['refresh_token'] = $refresh_token;
}
return $token;
} | Handle the creation of access token, also issue refresh token if supported / desirable.
@param $client_id
Client identifier related to the access token.
@param $user_id
User ID associated with the access token
@param $scope
(optional) Scopes to be stored in space-separated string.
@param bool $includeRefreshToken
If true, a new refresh_token will be added to the response
@see http://tools.ietf.org/html/rfc6749#section-5
@ingroup oauth2_section_5 | createAccessToken | php | boonex/dolphin.pro | plugins/OAuth2/ResponseType/JwtAccessToken.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/ResponseType/JwtAccessToken.php | MIT |
public function createAuthorizationCode($client_id, $user_id, $redirect_uri, $scope = null)
{
$code = $this->generateAuthorizationCode();
$this->storage->setAuthorizationCode($code, $client_id, $user_id, $redirect_uri, time() + $this->config['auth_code_lifetime'], $scope);
return $code;
} | Handle the creation of the authorization code.
@param $client_id
Client identifier related to the authorization code
@param $user_id
User ID associated with the authorization code
@param $redirect_uri
An absolute URI to which the authorization server will redirect the
user-agent to when the end-user authorization step is completed.
@param $scope
(optional) Scopes to be stored in space-separated string.
@see http://tools.ietf.org/html/rfc6749#section-4
@ingroup oauth2_section_4 | createAuthorizationCode | php | boonex/dolphin.pro | plugins/OAuth2/ResponseType/AuthorizationCode.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/ResponseType/AuthorizationCode.php | MIT |
public function enforceRedirect()
{
return $this->config['enforce_redirect'];
} | @return
TRUE if the grant type requires a redirect_uri, FALSE if not | enforceRedirect | php | boonex/dolphin.pro | plugins/OAuth2/ResponseType/AuthorizationCode.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/OAuth2/ResponseType/AuthorizationCode.php | MIT |
public static function enableCORS($options = null){
if( is_null($options) ){
$options = array();
}
if( !isset($options['origin']) ){
$options['origin'] = $_SERVER['HTTP_ORIGIN'];
}
if( !isset($options['methods']) ){
$options['methods'] = 'POST, GET';
}
if( !isset($options['headers']) ){
$options['headers'] = array();
}
header('Access-Control-Allow-Origin: ' . $options['origin']);
header('Access-Control-Allow-Methods: ' . $options['methods']);
header('Access-Control-Allow-Headers: ' . implode(', ', array_merge($options['headers'], array('X-Requested-With', 'Content-Range', 'Content-Disposition'))));
if( !isset($options['cookie']) || $options['cookie'] ){
header('Access-Control-Allow-Credentials: true');
}
} | Enable CORS -- http://enable-cors.org/
@param array [$options] | enableCORS | php | boonex/dolphin.pro | plugins/file-api/server/FileAPI.class.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/file-api/server/FileAPI.class.php | MIT |
public function __construct($config = null)
{
$this->config = HTMLPurifier_Config::create($config);
$this->strategy = new HTMLPurifier_Strategy_Core();
} | Initializes the purifier.
@param HTMLPurifier_Config $config Optional HTMLPurifier_Config object
for all instances of the purifier, if omitted, a default
configuration is supplied (which can be overridden on a
per-use basis).
The parameter can also be any type that
HTMLPurifier_Config::create() supports. | __construct | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function addFilter($filter)
{
trigger_error(
'HTMLPurifier->addFilter() is deprecated, use configuration directives' .
' in the Filter namespace or Filter.Custom',
E_USER_WARNING
);
$this->filters[] = $filter;
} | Adds a filter to process the output. First come first serve
@param HTMLPurifier_Filter $filter HTMLPurifier_Filter object | addFilter | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function purify($html, $config = null)
{
// :TODO: make the config merge in, instead of replace
$config = $config ? HTMLPurifier_Config::create($config) : $this->config;
// implementation is partially environment dependant, partially
// configuration dependant
$lexer = HTMLPurifier_Lexer::create($config);
$context = new HTMLPurifier_Context();
// setup HTML generator
$this->generator = new HTMLPurifier_Generator($config, $context);
$context->register('Generator', $this->generator);
// set up global context variables
if ($config->get('Core.CollectErrors')) {
// may get moved out if other facilities use it
$language_factory = HTMLPurifier_LanguageFactory::instance();
$language = $language_factory->create($config, $context);
$context->register('Locale', $language);
$error_collector = new HTMLPurifier_ErrorCollector($context);
$context->register('ErrorCollector', $error_collector);
}
// setup id_accumulator context, necessary due to the fact that
// AttrValidator can be called from many places
$id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);
$context->register('IDAccumulator', $id_accumulator);
$html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context);
// setup filters
$filter_flags = $config->getBatch('Filter');
$custom_filters = $filter_flags['Custom'];
unset($filter_flags['Custom']);
$filters = array();
foreach ($filter_flags as $filter => $flag) {
if (!$flag) {
continue;
}
if (strpos($filter, '.') !== false) {
continue;
}
$class = "HTMLPurifier_Filter_$filter";
$filters[] = new $class;
}
foreach ($custom_filters as $filter) {
// maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat
$filters[] = $filter;
}
$filters = array_merge($filters, $this->filters);
// maybe prepare(), but later
for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) {
$html = $filters[$i]->preFilter($html, $config, $context);
}
// purified HTML
$html =
$this->generator->generateFromTokens(
// list of tokens
$this->strategy->execute(
// list of un-purified tokens
$lexer->tokenizeHTML(
// un-purified HTML
$html,
$config,
$context
),
$config,
$context
)
);
for ($i = $filter_size - 1; $i >= 0; $i--) {
$html = $filters[$i]->postFilter($html, $config, $context);
}
$html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context);
$this->context =& $context;
return $html;
} | Filters an HTML snippet/document to be XSS-free and standards-compliant.
@param string $html String of HTML to purify
@param HTMLPurifier_Config $config Config object for this operation,
if omitted, defaults to the config object specified during this
object's construction. The parameter can also be any type
that HTMLPurifier_Config::create() supports.
@return string Purified HTML | purify | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public static function getInstance($prototype = null)
{
return HTMLPurifier::instance($prototype);
} | Singleton for enforcing just one HTML Purifier in your system
@param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype
HTMLPurifier instance to overload singleton with,
or HTMLPurifier_Config instance to configure the
generated version with.
@return HTMLPurifier
@note Backwards compatibility, see instance() | getInstance | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function performInclusions(&$attr)
{
if (!isset($attr[0])) {
return;
}
$merge = $attr[0];
$seen = array(); // recursion guard
// loop through all the inclusions
for ($i = 0; isset($merge[$i]); $i++) {
if (isset($seen[$merge[$i]])) {
continue;
}
$seen[$merge[$i]] = true;
// foreach attribute of the inclusion, copy it over
if (!isset($this->info[$merge[$i]])) {
continue;
}
foreach ($this->info[$merge[$i]] as $key => $value) {
if (isset($attr[$key])) {
continue;
} // also catches more inclusions
$attr[$key] = $value;
}
if (isset($this->info[$merge[$i]][0])) {
// recursion
$merge = array_merge($merge, $this->info[$merge[$i]][0]);
}
}
unset($attr[0]);
} | Takes a reference to an attribute associative array and performs
all inclusions specified by the zero index.
@param array &$attr Reference to attribute array | performInclusions | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function expandIdentifiers(&$attr, $attr_types)
{
// because foreach will process new elements we add, make sure we
// skip duplicates
$processed = array();
foreach ($attr as $def_i => $def) {
// skip inclusions
if ($def_i === 0) {
continue;
}
if (isset($processed[$def_i])) {
continue;
}
// determine whether or not attribute is required
if ($required = (strpos($def_i, '*') !== false)) {
// rename the definition
unset($attr[$def_i]);
$def_i = trim($def_i, '*');
$attr[$def_i] = $def;
}
$processed[$def_i] = true;
// if we've already got a literal object, move on
if (is_object($def)) {
// preserve previous required
$attr[$def_i]->required = ($required || $attr[$def_i]->required);
continue;
}
if ($def === false) {
unset($attr[$def_i]);
continue;
}
if ($t = $attr_types->get($def)) {
$attr[$def_i] = $t;
$attr[$def_i]->required = $required;
} else {
unset($attr[$def_i]);
}
}
} | Expands all string identifiers in an attribute array by replacing
them with the appropriate values inside HTMLPurifier_AttrTypes
@param array &$attr Reference to attribute array
@param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance | expandIdentifiers | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function parseCDATA($string)
{
$string = trim($string);
$string = str_replace(array("\n", "\t", "\r"), ' ', $string);
return $string;
} | Convenience method that parses a string as if it were CDATA.
This method process a string in the manner specified at
<http://www.w3.org/TR/html4/types.html#h-6.2> by removing
leading and trailing whitespace, ignoring line feeds, and replacing
carriage returns and tabs with spaces. While most useful for HTML
attributes specified as CDATA, it can also be applied to most CSS
values.
@note This method is not entirely standards compliant, as trim() removes
more types of whitespace than specified in the spec. In practice,
this is rarely a problem, as those extra characters usually have
already been removed by HTMLPurifier_Encoder.
@warning This processing is inconsistent with XML's whitespace handling
as specified by section 3.3.3 and referenced XHTML 1.0 section
4.7. However, note that we are NOT necessarily
parsing XML, thus, this behavior may still be correct. We
assume that newlines have been normalized. | parseCDATA | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function make($string)
{
// default implementation, return a flyweight of this object.
// If $string has an effect on the returned object (i.e. you
// need to overload this method), it is best
// to clone or instantiate new copies. (Instantiation is safer.)
return $this;
} | Factory method for creating this class from a string.
@param string $string String construction info
@return HTMLPurifier_AttrDef Created AttrDef object corresponding to $string | make | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
protected function mungeRgb($string)
{
return preg_replace('/rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/', 'rgb(\1,\2,\3)', $string);
} | Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work
properly. THIS IS A HACK!
@param string $string a CSS colour definition
@return string | mungeRgb | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
protected function expandCSSEscape($string)
{
// flexibly parse it
$ret = '';
for ($i = 0, $c = strlen($string); $i < $c; $i++) {
if ($string[$i] === '\\') {
$i++;
if ($i >= $c) {
$ret .= '\\';
break;
}
if (ctype_xdigit($string[$i])) {
$code = $string[$i];
for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) {
if (!ctype_xdigit($string[$i])) {
break;
}
$code .= $string[$i];
}
// We have to be extremely careful when adding
// new characters, to make sure we're not breaking
// the encoding.
$char = HTMLPurifier_Encoder::unichr(hexdec($code));
if (HTMLPurifier_Encoder::cleanUTF8($char) === '') {
continue;
}
$ret .= $char;
if ($i < $c && trim($string[$i]) !== '') {
$i--;
}
continue;
}
if ($string[$i] === "\n") {
continue;
}
}
$ret .= $string[$i];
}
return $ret;
} | Parses a possibly escaped CSS string and returns the "pure"
version of it. | expandCSSEscape | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function prependCSS(&$attr, $css)
{
$attr['style'] = isset($attr['style']) ? $attr['style'] : '';
$attr['style'] = $css . $attr['style'];
} | Prepends CSS properties to the style attribute, creating the
attribute if it doesn't exist.
@param array &$attr Attribute array to process (passed by reference)
@param string $css CSS to prepend | prependCSS | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function confiscateAttr(&$attr, $key)
{
if (!isset($attr[$key])) {
return null;
}
$value = $attr[$key];
unset($attr[$key]);
return $value;
} | Retrieves and removes an attribute
@param array &$attr Attribute array to process (passed by reference)
@param mixed $key Key of attribute to confiscate
@return mixed | confiscateAttr | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function __construct()
{
// XXX This is kind of poor, since we don't actually /clone/
// instances; instead, we use the supplied make() attribute. So,
// the underlying class must know how to deal with arguments.
// With the old implementation of Enum, that ignored its
// arguments when handling a make dispatch, the IAlign
// definition wouldn't work.
// pseudo-types, must be instantiated via shorthand
$this->info['Enum'] = new HTMLPurifier_AttrDef_Enum();
$this->info['Bool'] = new HTMLPurifier_AttrDef_HTML_Bool();
$this->info['CDATA'] = new HTMLPurifier_AttrDef_Text();
$this->info['ID'] = new HTMLPurifier_AttrDef_HTML_ID();
$this->info['Length'] = new HTMLPurifier_AttrDef_HTML_Length();
$this->info['MultiLength'] = new HTMLPurifier_AttrDef_HTML_MultiLength();
$this->info['NMTOKENS'] = new HTMLPurifier_AttrDef_HTML_Nmtokens();
$this->info['Pixels'] = new HTMLPurifier_AttrDef_HTML_Pixels();
$this->info['Text'] = new HTMLPurifier_AttrDef_Text();
$this->info['URI'] = new HTMLPurifier_AttrDef_URI();
$this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang();
$this->info['Color'] = new HTMLPurifier_AttrDef_HTML_Color();
$this->info['IAlign'] = self::makeEnum('top,middle,bottom,left,right');
$this->info['LAlign'] = self::makeEnum('top,bottom,left,right');
$this->info['FrameTarget'] = new HTMLPurifier_AttrDef_HTML_FrameTarget();
// unimplemented aliases
$this->info['ContentType'] = new HTMLPurifier_AttrDef_Text();
$this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text();
$this->info['Charsets'] = new HTMLPurifier_AttrDef_Text();
$this->info['Character'] = new HTMLPurifier_AttrDef_Text();
// "proprietary" types
$this->info['Class'] = new HTMLPurifier_AttrDef_HTML_Class();
// number is really a positive integer (one or more digits)
// FIXME: ^^ not always, see start and value of list items
$this->info['Number'] = new HTMLPurifier_AttrDef_Integer(false, false, true);
} | Constructs the info array, supplying default implementations for attribute
types. | __construct | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function set($type, $impl)
{
$this->info[$type] = $impl;
} | Sets a new implementation for a type
@param string $type String type name
@param HTMLPurifier_AttrDef $impl Object AttrDef for type | set | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public static function autoload($class)
{
$file = HTMLPurifier_Bootstrap::getPath($class);
if (!$file) {
return false;
}
// Technically speaking, it should be ok and more efficient to
// just do 'require', but Antonio Parraga reports that with
// Zend extensions such as Zend debugger and APC, this invariant
// may be broken. Since we have efficient alternatives, pay
// the cost here and avoid the bug.
require_once HTMLPURIFIER_PREFIX . '/' . $file;
return true;
} | Autoload function for HTML Purifier
@param string $class Class to load
@return bool | autoload | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public static function getPath($class)
{
if (strncmp('HTMLPurifier', $class, 12) !== 0) {
return false;
}
// Custom implementations
if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) {
$code = str_replace('_', '-', substr($class, 22));
$file = 'HTMLPurifier/Language/classes/' . $code . '.php';
} else {
$file = str_replace('_', '/', $class) . '.php';
}
if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) {
return false;
}
return $file;
} | Returns the path for a specific class.
@param string $class Class path to get
@return string | getPath | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function setup($config)
{
if ($this->setup) {
return;
}
$this->setup = true;
$this->doSetup($config);
} | Setup function that aborts if already setup
@param HTMLPurifier_Config $config | setup | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function getAllowedElements($config)
{
return $this->elements;
} | Get lookup of tag names that should not close this element automatically.
All other elements will do so.
@param HTMLPurifier_Config $config HTMLPurifier_Config object
@return array | getAllowedElements | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function __construct($definition, $parent = null)
{
$parent = $parent ? $parent : $definition->defaultPlist;
$this->plist = new HTMLPurifier_PropertyList($parent);
$this->def = $definition; // keep a copy around for checking
$this->parser = new HTMLPurifier_VarParser_Flexible();
} | Constructor
@param HTMLPurifier_ConfigSchema $definition ConfigSchema that defines
what directives are allowed.
@param HTMLPurifier_PropertyList $parent | __construct | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public static function create($config, $schema = null)
{
if ($config instanceof HTMLPurifier_Config) {
// pass-through
return $config;
}
if (!$schema) {
$ret = HTMLPurifier_Config::createDefault();
} else {
$ret = new HTMLPurifier_Config($schema);
}
if (is_string($config)) {
$ret->loadIni($config);
} elseif (is_array($config)) $ret->loadArray($config);
return $ret;
} | Convenience constructor that creates a config object based on a mixed var
@param mixed $config Variable that defines the state of the config
object. Can be: a HTMLPurifier_Config() object,
an array of directives based on loadArray(),
or a string filename of an ini file.
@param HTMLPurifier_ConfigSchema $schema Schema object
@return HTMLPurifier_Config Configured object | create | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public static function inherit(HTMLPurifier_Config $config)
{
return new HTMLPurifier_Config($config->def, $config->plist);
} | Creates a new config object that inherits from a previous one.
@param HTMLPurifier_Config $config Configuration object to inherit from.
@return HTMLPurifier_Config object with $config as its parent. | inherit | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public static function createDefault()
{
$definition = HTMLPurifier_ConfigSchema::instance();
$config = new HTMLPurifier_Config($definition);
return $config;
} | Convenience constructor that creates a default configuration object.
@return HTMLPurifier_Config default object. | createDefault | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function get($key, $a = null)
{
if ($a !== null) {
$this->triggerError(
"Using deprecated API: use \$config->get('$key.$a') instead",
E_USER_WARNING
);
$key = "$key.$a";
}
if (!$this->finalized) {
$this->autoFinalize();
}
if (!isset($this->def->info[$key])) {
// can't add % due to SimpleTest bug
$this->triggerError(
'Cannot retrieve value of undefined directive ' . htmlspecialchars($key),
E_USER_WARNING
);
return;
}
if (isset($this->def->info[$key]->isAlias)) {
$d = $this->def->info[$key];
$this->triggerError(
'Cannot get value from aliased directive, use real name ' . $d->key,
E_USER_ERROR
);
return;
}
if ($this->lock) {
list($ns) = explode('.', $key);
if ($ns !== $this->lock) {
$this->triggerError(
'Cannot get value of namespace ' . $ns . ' when lock for ' .
$this->lock .
' is active, this probably indicates a Definition setup method ' .
'is accessing directives that are not within its namespace',
E_USER_ERROR
);
return;
}
}
return $this->plist->get($key);
} | Retrieves a value from the configuration.
@param string $key String key
@param mixed $a
@return mixed | get | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function getBatch($namespace)
{
if (!$this->finalized) {
$this->autoFinalize();
}
$full = $this->getAll();
if (!isset($full[$namespace])) {
$this->triggerError(
'Cannot retrieve undefined namespace ' .
htmlspecialchars($namespace),
E_USER_WARNING
);
return;
}
return $full[$namespace];
} | Retrieves an array of directives to values from a given namespace
@param string $namespace String namespace
@return array | getBatch | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function getBatchSerial($namespace)
{
if (empty($this->serials[$namespace])) {
$batch = $this->getBatch($namespace);
unset($batch['DefinitionRev']);
$this->serials[$namespace] = sha1(serialize($batch));
}
return $this->serials[$namespace];
} | Returns a SHA-1 signature of a segment of the configuration object
that uniquely identifies that particular configuration
@param string $namespace Namespace to get serial for
@return string
@note Revision is handled specially and is removed from the batch
before processing! | getBatchSerial | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function getSerial()
{
if (empty($this->serial)) {
$this->serial = sha1(serialize($this->getAll()));
}
return $this->serial;
} | Returns a SHA-1 signature for the entire configuration object
that uniquely identifies that particular configuration
@return string | getSerial | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
public function set($key, $value, $a = null)
{
if (strpos($key, '.') === false) {
$namespace = $key;
$directive = $value;
$value = $a;
$key = "$key.$directive";
$this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE);
} else {
list($namespace) = explode('.', $key);
}
if ($this->isFinalized('Cannot set directive after finalization')) {
return;
}
if (!isset($this->def->info[$key])) {
$this->triggerError(
'Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',
E_USER_WARNING
);
return;
}
$def = $this->def->info[$key];
if (isset($def->isAlias)) {
if ($this->aliasMode) {
$this->triggerError(
'Double-aliases not allowed, please fix '.
'ConfigSchema bug with' . $key,
E_USER_ERROR
);
return;
}
$this->aliasMode = true;
$this->set($def->key, $value);
$this->aliasMode = false;
$this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE);
return;
}
// Raw type might be negative when using the fully optimized form
// of stdclass, which indicates allow_null == true
$rtype = is_int($def) ? $def : $def->type;
if ($rtype < 0) {
$type = -$rtype;
$allow_null = true;
} else {
$type = $rtype;
$allow_null = isset($def->allow_null);
}
try {
$value = $this->parser->parse($value, $type, $allow_null);
} catch (HTMLPurifier_VarParserException $e) {
$this->triggerError(
'Value for ' . $key . ' is of invalid type, should be ' .
HTMLPurifier_VarParser::getTypeName($type),
E_USER_WARNING
);
return;
}
if (is_string($value) && is_object($def)) {
// resolve value alias if defined
if (isset($def->aliases[$value])) {
$value = $def->aliases[$value];
}
// check to see if the value is allowed
if (isset($def->allowed) && !isset($def->allowed[$value])) {
$this->triggerError(
'Value not supported, valid values are: ' .
$this->_listify($def->allowed),
E_USER_WARNING
);
return;
}
}
$this->plist->set($key, $value);
// reset definitions if the directives they depend on changed
// this is a very costly process, so it's discouraged
// with finalization
if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') {
$this->definitions[$namespace] = null;
}
$this->serials[$namespace] = false;
} | Sets a value to configuration.
@param string $key key
@param mixed $value value
@param mixed $a | set | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
private function _listify($lookup)
{
$list = array();
foreach ($lookup as $name => $b) {
$list[] = $name;
}
return implode(', ', $list);
} | Convenience function for error reporting
@param array $lookup
@return string | _listify | php | boonex/dolphin.pro | plugins/htmlpurifier/HTMLPurifier.standalone.php | https://github.com/boonex/dolphin.pro/blob/master/plugins/htmlpurifier/HTMLPurifier.standalone.php | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.