Version 4.1.19

This commit is contained in:
Neo committed 2025-12-19 05:38:56 -08:00
1 parent 28bd025b35
commit 2bd5025018
2674 files changed
+233518 -77766

No files matched your search

+222
View File
@@ -0,0 +1,222 @@
<?php
/**
* @brief Base API Controller
* @author <a href='http://www.invisionpower.com'>Invision Power Services, Inc.</a>
* @copyright (c) 2001 - 2016 Invision Power Services, Inc.
* @license http://www.invisionpower.com/legal/standards/
* @package IPS Community Suite
* @since 3 Dec 2015
* @version SVN_VERSION_NUMBER
*/
namespace IPS\Api;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* Base API Controller
*/
abstract class _Controller
{
/**
* @brief API Key
*/
protected $apiKey;
/**
* Constructor
*
* @param \IPS\Api\Key $apiKey The API key being used to access
* @return void
*/
public function __construct( \IPS\Api\Key $apiKey )
{
$this->apiKey = $apiKey;
}
/**
* Execute
*
* @param array $pathBits The parts to the path called
* @param bool $shouldLog Gets set to TRUE if this call should log
* @return \IPS\Api\Response
* @throws \IPS\Api\Exception
*/
public function execute( $pathBits, &$shouldLog )
{
$method = ( isset( $_SERVER['REQUEST_METHOD'] ) and in_array( mb_strtoupper( $_SERVER['REQUEST_METHOD'] ), array( 'GET', 'POST', 'PUT', 'DELETE' ) ) ) ? mb_strtoupper( $_SERVER['REQUEST_METHOD'] ) : 'GET';
$params = array();
try
{
$endpointData = $this->_getEndpoint( $pathBits );
}
catch ( \RuntimeException $e )
{
throw new \IPS\Api\Exception( 'NO_ENDPOINT', '2S291/1', 404 );
}
if ( method_exists( $this, "{$method}{$endpointData['endpoint']}" ) )
{
preg_match( '/^IPS\\\(.+?)\\\api\\\(.+?)$/', get_called_class(), $matches );
if ( !$this->apiKey->canAccess( $matches[1], $matches[2], "{$method}{$endpointData['endpoint']}" ) )
{
throw new \IPS\Api\Exception( 'NO_PERMISSION', '2S291/3', 403 );
}
$shouldLog = $this->apiKey->shouldLog( $matches[1], $matches[2], "{$method}{$endpointData['endpoint']}" );
return call_user_func_array( array( $this, "{$method}{$endpointData['endpoint']}" ), $endpointData['params'] );
}
else
{
throw new \IPS\Api\Exception( 'BAD_METHOD', '3S291/2', 405 );
}
}
/**
* Get endpoint data
*
* @param array $pathBits The parts to the path called
* @return array
* @throws \RuntimeException
*/
protected function _getEndpoint( $pathBits )
{
$endpoint = NULL;
$params = array();
if ( count( $pathBits ) === 0 )
{
$endpoint = 'index';
}
elseif ( count( $pathBits ) === 1 )
{
$params[] = array_shift( $pathBits );
$endpoint = 'item';
}
elseif ( count( $pathBits ) === 2 )
{
$params[] = array_shift( $pathBits );
$endpoint = 'item_' . array_shift( $pathBits );
}
elseif ( count( $pathBits ) === 3 )
{
$params[] = array_shift( $pathBits );
$endpoint = 'item_' . array_shift( $pathBits );
$params[] = array_shift( $pathBits );
}
else
{
throw new \RuntimeException;
}
return array( 'endpoint' => $endpoint, 'params' => $params );
}
/**
* Get all endpoints
*
* @return array
*/
public static function getAllEndpoints()
{
$return = array();
foreach ( \IPS\Application::applications() as $app )
{
$apiDir = \IPS\ROOT_PATH . '/applications/' . $app->directory . '/api';
if ( file_exists( $apiDir ) )
{
$directory = new \DirectoryIterator( $apiDir );
foreach ( $directory as $file )
{
if ( !$file->isDot() and mb_substr( $file, 0, 1 ) != '.' )
{
$controllerName = mb_substr( $file, 0, -4 );
$class = 'IPS\\' . $app->directory . '\\api\\' . $controllerName;
$reflection = new \ReflectionClass( $class );
foreach ( $reflection->getMethods() as $method )
{
if ( $method->getName() != 'execute' and !$method->isStatic() and $method->isPublic() and mb_substr( $method->getName(), 0, 1 ) != '_' )
{
$return[ $app->directory . '/' . $controllerName . '/' . $method->getName() ] = static::decodeDocblock( $method->getDocComment() );
}
}
}
}
}
}
return $return;
}
/**
* Decode docblock
*
* @param string $comment The docblock comment
* @return array
*/
public static function decodeDocblock( $comment )
{
$comment = explode( "\n", $comment );
array_shift( $comment );
$title = preg_replace( '/^\s*\*\s+?/', '', array_shift( $comment ) );
$description = '';
while ( $nextLine = array_shift( $comment ) )
{
if ( preg_match( '/^\s*\*\s*\/?\s*$/', $nextLine ) )
{
break;
}
$description .= preg_replace( '/^\s*\*\s+?/', '', $nextLine ) . "\n";
}
$params = array();
while ( $nextLine = array_shift( $comment ) )
{
if ( preg_match( '/^\s*\*\s*@([a-z]*)(\t+([^\t]*))?(\t+([^\t]*))?(\t+([^\t]*))?$/', $nextLine, $matches ) )
{
$details = array();
foreach ( array( 3, 5, 7 ) as $k )
{
if ( isset( $matches[ $k ] ) )
{
$details[] = $matches[ $k ];
}
}
$params[ $matches[1] ][] = $details;
}
}
return array(
'title' => $title,
'description' => trim( $description ),
'details' => $params
);
}
/**
* Parses an endpoint key and modifies it for display
*
* @param string $endpoint The endpoint (e.g: GET /core/members)
* @param string $size Size of badge to show
* @return array
*/
public static function parseEndpointForDisplay( $endpoint, $size='small' )
{
$badgeStyles = array(
'GET' => 'ipsBadge_positive',
'POST' => 'ipsBadge_style2',
'DELETE' => 'ipsBadge_negative',
'PUT' => 'ipsBadge_intermediary'
);
$pieces = explode( ' ', $endpoint );
$pieces[0] = "<span class='ipsBadge ipsBadge_{$size} " . $badgeStyles[ $pieces[0] ] . "'>" . $pieces[0] . "</span>";
return implode( ' ', $pieces );
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
/**
* @brief API Exception
* @author <a href='http://www.invisionpower.com'>Invision Power Services, Inc.</a>
* @copyright (c) 2001 - 2016 Invision Power Services, Inc.
* @license http://www.invisionpower.com/legal/standards/
* @package IPS Community Suite
* @since 3 Dec 2015
* @version SVN_VERSION_NUMBER
*/
namespace IPS\Api;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* API Exception
*/
class _Exception extends \Exception
{
/**
* @brief Exception code
*/
public $exceptionCode;
/**
* Constructor
*
* @param string $message Error Message
* @param string $code Code
* @param int $httpCode HTTP Error code
* @return void
*/
public function __construct( $message, $code, $httpCode )
{
$this->exceptionCode = $code;
return parent::__construct( $message, $httpCode );
}
}
+227
View File
@@ -0,0 +1,227 @@
<?php
/**
* @brief API Key
* @author <a href='http://www.invisionpower.com'>Invision Power Services, Inc.</a>
* @copyright (c) 2001 - 2016 Invision Power Services, Inc.
* @license http://www.invisionpower.com/legal/standards/
* @package IPS Community Suite
* @since 3 Dec 2015
* @version SVN_VERSION_NUMBER
*/
namespace IPS\Api;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* API Key
*/
class _Key extends \IPS\Node\Model
{
/**
* @brief [ActiveRecord] Multiton Store
*/
protected static $multitons;
/**
* @brief [ActiveRecord] Database Table
*/
public static $databaseTable = 'core_api_keys';
/**
* @brief Database Prefix
*/
public static $databasePrefix = 'api_';
/**
* @brief [Node] Node Title
*/
public static $nodeTitle = 'api_keys';
/**
* @brief [Node] ACP Restrictions
* @code
array(
'app' => 'core', // The application key which holds the restrictrions
'module' => 'foo', // The module key which holds the restrictions
'map' => array( // [Optional] The key for each restriction - can alternatively use "prefix"
'add' => 'foo_add',
'edit' => 'foo_edit',
'permissions' => 'foo_perms',
'delete' => 'foo_delete'
),
'all' => 'foo_manage', // [Optional] The key to use for any restriction not provided in the map (only needed if not providing all 4)
'prefix' => 'foo_', // [Optional] Rather than specifying each key in the map, you can specify a prefix, and it will automatically look for restrictions with the key "[prefix]_add/edit/permissions/delete"
* @endcode
*/
protected static $restrictions = array(
'app' => 'core',
'module' => 'applications',
'prefix' => 'api_',
);
/**
* @brief [Node] Title prefix. If specified, will look for a language key with "{$key}_title" as the key
*/
public static $titleLangPrefix = 'core_api_name_';
/**
* Get description
*
* @return string
*/
public function get__description()
{
return \IPS\Theme::i()->getTemplate('api')->apiKey( $this->id );
}
/**
* Check access
*
* @param string $app Application key
* @param string $controller Controller
* @param string $method Method
* @return bool
*/
public function canAccess( $app, $controller, $method )
{
$permissions = json_decode( $this->permissions, TRUE );
return isset( $permissions["{$app}/{$controller}/{$method}"] ) and $permissions["{$app}/{$controller}/{$method}"]['access'] == TRUE;
}
/**
* Should log?
*
* @param string $app Application key
* @param string $controller Controller
* @param string $method Method
* @return bool
*/
public function shouldLog( $app, $controller, $method )
{
$permissions = json_decode( $this->permissions, TRUE );
return isset( $permissions["{$app}/{$controller}/{$method}"] ) and isset( $permissions["{$app}/{$controller}/{$method}"]['log'] ) and $permissions["{$app}/{$controller}/{$method}"]['log'] == TRUE;
}
/**
* [Node] Add/Edit Form
*
* @param \IPS\Helpers\Form $form The form
* @return void
*/
public function form( &$form )
{
/* API Key */
$form->add( new \IPS\Helpers\Form\Custom( 'api_id', $this->id ?: md5( uniqid() ), TRUE, array(
'getHtml' => function( $field )
{
return \IPS\Theme::i()->getTemplate('api')->apiKeyField( $field->name, $field->value );
},
'disableCopy' => TRUE
) ) );
/* Description */
$form->add( new \IPS\Helpers\Form\Translatable( 'api_name', NULL, TRUE, array( 'app' => 'core', 'key' => ( $this->id ? "core_api_name_{$this->id}" : NULL ) ) ) );
/* Allowed IPs */
$form->add( new \IPS\Helpers\Form\Radio( 'api_enable_ip_restriction', intval( $this->allowed_ips !== NULL ), FALSE, array(
'options' => array(
0 => 'api_enable_ip_restriction_off',
1 => 'api_enable_ip_restriction_on',
),
'toggles' => array(
1 => array( 'api_allowed_ips' )
)
) ) );
if ( \IPS\Request::i()->isCgi() )
{
\IPS\Member::loggedIn()->language()->words['api_enable_ip_restriction_warning'] = \IPS\Member::loggedIn()->language()->addToStack('api_enable_ip_restriction__warning');
}
$form->add( new \IPS\Helpers\Form\Stack( 'api_allowed_ips', explode( ',', $this->allowed_ips ), NULL, array(), function( $val )
{
if ( $val )
{
foreach ( array_filter( is_array( $val ) ? $val : array( $val ) ) as $ip )
{
if ( filter_var( $ip, FILTER_VALIDATE_IP ) === FALSE )
{
throw new \DomainException( \IPS\Member::loggedIn()->language()->addToStack( 'api_allowed_ips_err', FALSE, array( 'sprintf' => array( $ip ) ) ) );
}
}
}
}, NULL, NULL, 'api_allowed_ips' ) );
/* Permissions */
$form->add( new \IPS\Helpers\Form\Custom( 'api_permissions', $this->permissions ? json_decode( $this->permissions, TRUE ) : array(), FALSE, array(
'rowHtml' => function( $field )
{
$endpoints = \IPS\Api\Controller::getAllEndpoints();
foreach ( $endpoints as $key => $endpoint )
{
$pieces = explode('/', $key);
$endpointTree[ $pieces[0] ][ $pieces[1] ][ $key ] = $endpoint;
}
return \IPS\Theme::i()->getTemplate( 'api' )->permissionsField( $endpointTree, $field->name, $field->value );
}
) ) );
}
/**
* [Node] Format form values from add/edit form for save
*
* @param array $values Values from the form
* @return array
*/
public function formatFormValues( $values )
{
$values['api_permissions'] = json_encode( $values['api_permissions'] );
if ( !$values['api_enable_ip_restriction'] )
{
$values['api_allowed_ips'] = NULL;
}
unset( $values['api_enable_ip_restriction'] );
if ( !$this->id )
{
$this->id = $values['api_id'];
$this->save();
}
\IPS\Lang::saveCustom( 'core', "core_api_name_{$this->id}", $values['api_name'] );
unset( $values['api_name'] );
return $values;
}
/**
* [ActiveRecord] Duplicate
*
* @return void
*/
public function __clone()
{
if ( $this->skipCloneDuplication === TRUE )
{
return;
}
$oldId = $this->id;
$this->id = md5( uniqid() );
$this->_new = TRUE;
$this->save();
/* ...and language */
\IPS\Lang::saveCustom( 'core', 'core_api_name_' . $this->id, iterator_to_array( \IPS\Db::i()->select( 'word_custom, lang_id', 'core_sys_lang_words', array( 'word_key=?', 'core_api_name_' . $oldId ) )->setKeyField( 'lang_id' )->setValueField( 'word_custom' ) ) );
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
/**
* @brief PaginatedAPI Response
* @author <a href='http://www.invisionpower.com'>Invision Power Services, Inc.</a>
* @copyright (c) 2001 - 2016 Invision Power Services, Inc.
* @license http://www.invisionpower.com/legal/standards/
* @package IPS Community Suite
* @since 3 Dec 2015
* @version SVN_VERSION_NUMBER
*/
namespace IPS\Api;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* API Response
*/
class _PaginatedResponse extends Response
{
/**
* @brief HTTP Response Code
*/
public $httpCode;
/**
* @brief Select query
*/
protected $select;
/**
* @brief Current page
*/
protected $page = 1;
/**
* @brief Results per page
*/
protected $resultsPerPage = 25;
/**
* @brief ActiveRecord class
*/
protected $activeRecordClass;
/**
* @brief Total Count
*/
protected $count;
/**
* Constructor
*
* @param int $httpCode HTTP Response code
* @param \IPS\Db\Select $select Select query
* @param int $page Current page
* @param string $activeRecordClass ActiveRecord class
* @param int $count Total Count
* @return void
*/
public function __construct( $httpCode, $select, $page, $activeRecordClass, $count )
{
$this->httpCode = $httpCode;
$this->page = $page;
$this->select = $select;
$this->activeRecordClass = $activeRecordClass;
$this->count = $count;
}
/**
* Data to output
*
* @retrun string
*/
public function getOutput()
{
$results = array();
$this->select->query .= \IPS\Db::i()->compileLimitClause( array( ( $this->page - 1 ) * $this->resultsPerPage, $this->resultsPerPage ) );
if ( $this->activeRecordClass )
{
foreach ( new \IPS\Patterns\ActiveRecordIterator( $this->select, $this->activeRecordClass ) as $result )
{
$results[] = $result->apiOutput();
}
}
else
{
foreach ( $this->select as $result )
{
$results[] = $result;
}
}
return array(
'page' => $this->page,
'perPage' => $this->resultsPerPage,
'totalResults' => $this->count,
'totalPages' => ceil( $this->count / $this->resultsPerPage ),
'results' => $results
);
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
/**
* @brief API Response
* @author <a href='http://www.invisionpower.com'>Invision Power Services, Inc.</a>
* @copyright (c) 2001 - 2016 Invision Power Services, Inc.
* @license http://www.invisionpower.com/legal/standards/
* @package IPS Community Suite
* @since 3 Dec 2015
* @version SVN_VERSION_NUMBER
*/
namespace IPS\Api;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* API Response
*/
class _Response
{
/**
* @brief HTTP Response Code
*/
public $httpCode;
/**
* @brief Data
*/
protected $data;
/**
* Constructor
*
* @param int $httpCode HTTP Response code
* @param array $data Data to return
* @return void
*/
public function __construct( $httpCode, $data )
{
$this->httpCode = $httpCode;
$this->data = $data;
}
/**
* Data to output
*
* @retrun string
*/
public function getOutput()
{
return $this->data;
}
}