Version 5.0.0 beta 1

This commit is contained in:
Neo committed 2025-12-19 16:27:35 -08:00
1 parent 25ddeb65d6
commit 15c7beabc5
6736 files changed
+627902 -497943

No files matched your search

@@ -11,16 +11,24 @@
namespace IPS\core\Achievements\Actions;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
use IPS\Application;
use IPS\core\Achievements\Rule;
use IPS\Http\Url;
use IPS\Member;
use function defined;
use function get_called_class;
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
header( ( $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* Base class for AchievementAction extensions
*/
abstract class _AbstractAchievementAction
abstract class AchievementActionAbstract
{
/**
* Can use this rule?
@@ -29,19 +37,19 @@ abstract class _AbstractAchievementAction
*/
public function canUse(): bool
{
$exploded = explode( '\\', \get_called_class() );
$exploded = explode( '\\', get_called_class() );
return \IPS\Application::appIsEnabled( $exploded[1] );
return Application::appIsEnabled( $exploded[1] );
}
/**
* Get filter form elements
*
* @param array|NULL $filters Current filter values (if editing)
* @param \IPS\Http\Url $url The URL the form is being shown on
* @param Url $url The URL the form is being shown on
* @return array
*/
public function filters( ?array $filters, \IPS\Http\Url $url ): array
public function filters( ?array $filters, Url $url ): array
{
return [];
}
@@ -64,12 +72,12 @@ abstract class _AbstractAchievementAction
* calls that BEFORE making its change in the database (or there is read/write separation), you will need to add
* 1 to the value being considered for milestones
*
* @param \IPS\Member $subject The subject member
* @param Member $subject The subject member
* @param array $filters The value returned by formatFilterValues()
* @param mixed $extra Any additional information about what is happening (e.g. if a post is being made: the post object)
* @return bool
*/
public function filtersMatch( \IPS\Member $subject, array $filters, $extra = NULL ): bool
public function filtersMatch( Member $subject, array $filters, mixed $extra = NULL ): bool
{
return TRUE;
}
@@ -95,7 +103,7 @@ abstract class _AbstractAchievementAction
* @param array|NULL $filters Current filter values
* @return array
*/
public function awardOther( $extra = NULL, ?array $filters = NULL ): array
public function awardOther( mixed $extra = NULL, ?array $filters = NULL ): array
{
return [];
}
@@ -104,11 +112,11 @@ abstract class _AbstractAchievementAction
* Get identifier to prevent the member being awarded points for the same action twice
* Must be unique within within of this domain, must not exceed 32 chars.
*
* @param \IPS\Member $subject The subject member
* @param Member $subject The subject member
* @param mixed $extra Any additional information about what is happening (e.g. if a post is being made: the post object)
* @return string
*/
abstract public function identifier( \IPS\Member $subject, $extra = NULL ): string;
abstract public function identifier( Member $subject, mixed $extra = NULL ): string;
/**
* Return a description for this action to show in the log
@@ -122,8 +130,24 @@ abstract class _AbstractAchievementAction
/**
* Get "description" for rule
*
* @param \IPS\core\Achievements\Rule $rule The rule
* @param Rule $rule The rule
* @return string|null
*/
abstract public function ruleDescription( \IPS\core\Achievements\Rule $rule ): ?string;
abstract public function ruleDescription( Rule $rule ): ?string;
/**
* Process the rebuild row
*
* @param array $row Row from database
* @param array $data Data collected when starting rebuild [table, pkey...]
* @return void
*/
abstract public static function rebuildRow( array $row, array $data ) : void;
/**
* Get rebuild data
*
* @return array
*/
abstract public static function rebuildData(): array;
}
@@ -10,43 +10,63 @@
namespace IPS\core\Achievements\Actions;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
use IPS\Application;
use IPS\Content;
use IPS\core\Achievements\Rule;
use IPS\DateTime;
use IPS\Db;
use IPS\Helpers\Form\Node;
use IPS\Helpers\Form\Number;
use IPS\Helpers\Form\Select;
use IPS\Http\Url;
use IPS\Member;
use IPS\Theme;
use OutOfRangeException;
use UnderflowException;
use function count;
use function defined;
use function get_called_class;
use function get_class;
use function in_array;
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
header( ( $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* Abstract Achievement Action Extension for content-related things
*/
abstract class _AbstractContentAchievementAction extends AbstractAchievementAction
abstract class ContentAchievementActionAbstract extends AchievementActionAbstract
{
protected static $includeItems = TRUE;
protected static $includeComments = TRUE;
protected static $includeReviews = TRUE;
protected static bool $includeItems = TRUE;
protected static bool $includeComments = TRUE;
protected static bool $includeReviews = TRUE;
/**
* @var bool Exclude content items that require a first comment
*/
protected static $excludeItemsWithRequiredComment = FALSE;
protected static bool $excludeItemsWithRequiredComment = false;
/**
* Get filter form elements
*
* @param array|NULL $filters Current filter values (if editing)
* @param \IPS\Http\Url $url The URL the form is being shown on
* @param Url $url The URL the form is being shown on
* @return array
*/
public function filters( ?array $filters, \IPS\Http\Url $url ): array
public function filters( ?array $filters, Url $url ): array
{
$classKey = explode( '\\', \get_called_class() )[5];
$classKey = explode( '\\', get_called_class() )[5];
$contentTypeOptions = [];
$contentTypeToggles = [];
$_return = [];
$defaultApp = NULL;
foreach( \IPS\Application::applications() as $directory => $application )
foreach( Application::applications() as $directory => $application )
{
if( $application->default )
{
@@ -54,7 +74,7 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
break;
}
}
foreach ( \IPS\Application::allExtensions( 'core', 'ContentRouter', FALSE, $defaultApp ) as $extension )
foreach ( Application::allExtensions( 'core', 'ContentRouter', FALSE, $defaultApp ) as $extension )
{
foreach ( $extension->classes as $class )
{
@@ -92,34 +112,34 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
{
try
{
$nodeTitle = \IPS\Member::loggedIn()->language()->get( ($class::$containerNodeClass)::$nodeTitle . '_sg_lc' );
$nodeTitle = Member::loggedIn()->language()->get( ($class::$containerNodeClass)::$nodeTitle . '_sg_lc' );
}
catch( \UnderflowException $e )
catch( UnderflowException $e )
{
$nodeTitle = ($class::$containerNodeClass)::$nodeTitle . '_sg';
}
$nodeFilter = new \IPS\Helpers\Form\Node( $nodeFilterKey, ( $filters and isset( $filters[ 'nodes_' . str_replace( '\\', '-', $class ) ] ) and $filters[ 'nodes_' . str_replace( '\\', '-', $class ) ] ) ? $filters[ 'nodes_' . str_replace( '\\', '-', $class ) ] : 0, FALSE, [
$nodeFilter = new Node( $nodeFilterKey, ( $filters and isset( $filters[ 'nodes_' . str_replace( '\\', '-', $class ) ] ) and $filters[ 'nodes_' . str_replace( '\\', '-', $class ) ] ) ? $filters[ 'nodes_' . str_replace( '\\', '-', $class ) ] : 0, FALSE, [
'url' => $url,
'class' => $class::$containerNodeClass,
'showAllNodes' => TRUE,
'multiple' => TRUE,
], NULL, \IPS\Member::loggedIn()->language()->addToStack( 'achievement_filter_NewContentItem_node_prefix', FALSE, [ 'sprintf' => [
\IPS\Member::loggedIn()->language()->addToStack( $class::_definiteArticle(), FALSE ),
\IPS\Member::loggedIn()->language()->addToStack( $nodeTitle, FALSE )
], NULL, Member::loggedIn()->language()->addToStack( 'achievement_filter_NewContentItem_node_prefix', FALSE, [ 'sprintf' => [
Member::loggedIn()->language()->addToStack( $class::_definiteArticle(), FALSE ),
Member::loggedIn()->language()->addToStack( $nodeTitle, FALSE )
] ] ) );
$nodeFilter->label = \IPS\Member::loggedIn()->language()->addToStack( 'achievement_filter_NewContentItem_node', FALSE, [ 'sprintf' => [ \IPS\Member::loggedIn()->language()->addToStack( $nodeTitle, FALSE ) ] ] );
$nodeFilter->label = Member::loggedIn()->language()->addToStack( 'achievement_filter_NewContentItem_node', FALSE, [ 'sprintf' => [ Member::loggedIn()->language()->addToStack( $nodeTitle, FALSE ) ] ] );
$_return[ "nodes_" . str_replace( '\\', '-', $class ) ] = $nodeFilter;
}
}
}
}
$typeFilter = new \IPS\Helpers\Form\Select( 'achievement_filter_' . $classKey . '_type', ( $filters and isset( $filters['type'] ) and $filters['type'] ) ? $filters['type'] : NULL, FALSE, [ 'options' => $contentTypeOptions, 'toggles' => $contentTypeToggles ], NULL, \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_type_prefix') );
$typeFilter->label = \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_type');
$typeFilter = new Select( 'achievement_filter_' . $classKey . '_type', ( $filters and isset( $filters['type'] ) and $filters['type'] ) ? $filters['type'] : NULL, FALSE, [ 'options' => $contentTypeOptions, 'toggles' => $contentTypeToggles ], NULL, Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_type_prefix') );
$typeFilter->label = Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_type');
$nthFilter = new \IPS\Helpers\Form\Number( 'achievement_filter_' . $classKey . '_nth', ( $filters and isset( $filters['milestone'] ) and $filters['milestone'] ) ? $filters['milestone'] : 0, FALSE, [], NULL, \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_nth_their'), \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_' . $classKey . '_nth_suffix') );
$nthFilter->label = \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_nth');
$nthFilter = new Number( 'achievement_filter_' . $classKey . '_nth', ( $filters and isset( $filters['milestone'] ) and $filters['milestone'] ) ? $filters['milestone'] : 0, FALSE, [], NULL, Member::loggedIn()->language()->addToStack('achievement_filter_nth_their'), Member::loggedIn()->language()->addToStack('achievement_filter_' . $classKey . '_nth_suffix') );
$nthFilter->label = Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_nth');
$return = [ 'type' => $typeFilter ];
foreach ( $_return as $k => $v )
@@ -139,7 +159,7 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
*/
public function formatFilterValues( array $values ): array
{
$classKey = explode( '\\', \get_called_class() )[5];
$classKey = explode( '\\', get_called_class() )[5];
$return = [];
if ( isset( $values['achievement_filter_' . $classKey . '_type'] ) )
@@ -147,7 +167,7 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
$return['type'] = $values['achievement_filter_' . $classKey . '_type'];
$itemClass = $return['type'];
if ( \in_array( 'IPS\Content\Comment', class_parents( $return['type'] ) ) )
if ( in_array( 'IPS\Content\Comment', class_parents( $return['type'] ) ) )
{
$itemClass = $return['type']::$itemClass;
}
@@ -171,12 +191,12 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
* calls that BEFORE making its change in the database (or there is read/write separation), you will need to add
* 1 to the value being considered for milestones
*
* @param \IPS\Member $subject The subject member
* @param Member $subject The subject member
* @param array $filters The value returned by formatFilterValues()
* @param mixed $extra Any additional information about what is happening (e.g. if a post is being made: the post object)
* @return bool
*/
public function filtersMatch( \IPS\Member $subject, array $filters, $extra = NULL ): bool
public function filtersMatch( Member $subject, array $filters, mixed $extra = NULL ): bool
{
if ( isset( $filters['type'] ) )
{
@@ -186,14 +206,14 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
}
$item = $extra;
if ( \in_array( 'IPS\Content\Comment', class_parents( $filters['type'] ) ) )
if ( in_array( 'IPS\Content\Comment', class_parents( $filters['type'] ) ) )
{
$item = $extra->item();
}
if ( isset( $filters[ 'nodes_' . str_replace( '\\', '-', \get_class( $item ) ) ] ) )
if ( isset( $filters[ 'nodes_' . str_replace( '\\', '-', get_class( $item ) ) ] ) )
{
if ( !\in_array( $item->container()->_id, $filters[ 'nodes_' . str_replace( '\\', '-', \get_class( $item ) ) ] ) )
if ( !in_array( $item->container()->_id, $filters[ 'nodes_' . str_replace( '\\', '-', get_class( $item ) ) ] ) )
{
return FALSE;
}
@@ -204,19 +224,19 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
else
{
/* Make sure the class is a contentRouter approved class, mostly to stop private messages being awarded points */
foreach ( \IPS\Application::allExtensions( 'core', 'ContentRouter', FALSE ) as $extension )
foreach ( Application::allExtensions( 'core', 'ContentRouter', FALSE ) as $extension )
{
foreach ( $extension->classes as $class )
{
if ( \get_class( $extra ) == $class )
if ( get_class( $extra ) == $class )
{
return TRUE;
}
elseif ( isset( $class::$commentClass ) and \get_class( $extra ) == $class::$commentClass )
elseif ( isset( $class::$commentClass ) and get_class( $extra ) == $class::$commentClass )
{
return TRUE;
}
elseif ( isset( $class::$reviewClass ) and \get_class( $extra ) == $class::$reviewClass )
elseif ( isset( $class::$reviewClass ) and get_class( $extra ) == $class::$reviewClass )
{
return TRUE;
}
@@ -225,36 +245,33 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
return FALSE;
}
/* Stop PHPStorm from complaining about incorrect return types >_> */
return FALSE;
}
/**
* Get identifier to prevent the member being awarded points for the same action twice
* Must be unique within within of this domain, must not exceed 32 chars.
*
* @param \IPS\Member $subject The subject member
* @param Member $subject The subject member
* @param mixed $extra Any additional information about what is happening (e.g. if a post is being made: the post object)
* @return string
*/
public function identifier( \IPS\Member $subject, $extra = NULL ): string
public function identifier( Member $subject, mixed $extra = NULL ): string
{
return \get_class( $extra ) . ':' . $extra->{$extra::$databaseColumnId};
return get_class( $extra ) . ':' . $extra->{$extra::$databaseColumnId};
}
/**
* Get "description" for rule (usually a description of the rule's filters)
*
* @param \IPS\core\Achievements\Rule $rule The rule
* @param Rule $rule The rule
* @return string|NULL
*/
protected function _nodeFilterDescription( \IPS\core\Achievements\Rule $rule ): ?string
protected function _nodeFilterDescription( Rule $rule ): ?string
{
if ( isset( $rule->filters['type'] ) )
{
$itemClass = $rule->filters['type'];
if ( \in_array( 'IPS\Content\Comment', class_parents( $rule->filters['type'] ) ) )
if ( in_array( 'IPS\Content\Comment', class_parents( $rule->filters['type'] ) ) )
{
$itemClass = $itemClass::$itemClass;
}
@@ -270,18 +287,18 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
{
$nodeNames[] = $nodeClass::load( $id )->_title;
}
catch ( \OutOfRangeException $e ) {}
catch ( OutOfRangeException $e ) {}
}
if ( $nodeNames )
{
return \IPS\Member::loggedIn()->language()->addToStack( 'achievements_title_filter_location', FALSE, [
return Member::loggedIn()->language()->addToStack( 'achievements_title_filter_location', FALSE, [
'htmlsprintf' => [
\IPS\Theme::i()->getTemplate( 'achievements' )->ruleDescriptionBadge( 'location',
\count( $nodeNames ) === 1 ? $nodeNames[0] : \IPS\Member::loggedIn()->language()->addToStack( 'achievements_title_filter_location_val', FALSE, [ 'sprintf' => [
\count( $nodeNames ),
\IPS\Member::loggedIn()->language()->addToStack( $nodeClass::$nodeTitle, FALSE )
Theme::i()->getTemplate( 'achievements' )->ruleDescriptionBadge( 'location',
count( $nodeNames ) === 1 ? $nodeNames[0] : Member::loggedIn()->language()->addToStack( 'achievements_title_filter_location_val', FALSE, [ 'sprintf' => [
count( $nodeNames ),
Member::loggedIn()->language()->addToStack( $nodeClass::$nodeTitle, FALSE )
] ] ),
\count( $nodeNames ) === 1 ? NULL : $nodeNames
count( $nodeNames ) === 1 ? NULL : $nodeNames
)
],
] );
@@ -296,10 +313,10 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
*
* @return array
*/
static public function rebuildData()
static public function rebuildData() : array
{
$return = [];
foreach ( \IPS\Application::allExtensions( 'core', 'ContentRouter', FALSE ) as $extension )
foreach ( Application::allExtensions( 'core', 'ContentRouter', FALSE ) as $extension )
{
foreach ( $extension->classes as $class )
{
@@ -349,30 +366,32 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
*
* @param array $filters The value returned by formatFilterValues()
* @param string $class Class we are working with
* @param \IPS\DateTime|null $time Any time limit to add
* @param DateTime|null $time Any time limit to add
* @return array
*/
protected function getWherePerType( $filters, $class, $time=NULL ): array
protected function getWherePerType( array $filters, string $class, ?DateTime $time=NULL ): array
{
/* @var Content $class */
/* @var array $databaseColumnMap */
$where = ( $time ? [ [ $class::$databasePrefix . $class::$databaseColumnMap['date'] . ' >= ?', $time->getTimestamp() ] ] : [] );
$itemClass = $class;
if ( \in_array( 'IPS\Content\Comment', class_parents( $class ) ) )
if ( in_array( 'IPS\Content\Comment', class_parents( $class ) ) )
{
$itemClass = $class::$itemClass;
}
if ( isset( $filters[ 'nodes_' . str_replace( '\\', '-', $itemClass ) ] ) )
{
if ( \in_array( 'IPS\Content\Comment', class_parents( $class ) ) )
if ( in_array( 'IPS\Content\Comment', class_parents( $class ) ) )
{
$itemClass = $class::$itemClass;
$where[] = [ $class::$databasePrefix . $class::$databaseColumnMap['item'] . ' IN(?)',
\IPS\Db::i()->select( $itemClass::$databasePrefix . $itemClass::$databaseColumnId, $itemClass::$databaseTable, [ \IPS\Db::i()->in( $itemClass::$databasePrefix . $itemClass::$databaseColumnMap['container'], $filters[ 'nodes_' . str_replace( '\\', '-', $itemClass ) ] ) ] ) ];
Db::i()->select( $itemClass::$databasePrefix . $itemClass::$databaseColumnId, $itemClass::$databaseTable, [ Db::i()->in( $itemClass::$databasePrefix . $itemClass::$databaseColumnMap['container'], $filters[ 'nodes_' . str_replace( '\\', '-', $itemClass ) ] ) ] ) ];
}
else
{
$where[] = [ \IPS\Db::i()->in( $class::$databasePrefix . $class::$databaseColumnMap['container'], $filters[ 'nodes_' . str_replace( '\\', '-', $class ) ] ) ];
$where[] = [ Db::i()->in( $class::$databasePrefix . $class::$databaseColumnMap['container'], $filters[ 'nodes_' . str_replace( '\\', '-', $class ) ] ) ];
}
}
@@ -386,9 +405,9 @@ abstract class _AbstractContentAchievementAction extends AbstractAchievementActi
* @param array $data Data collected when starting rebuild [table, pkey...]
* @return void
*/
public static function rebuildRow( $row, $data )
public static function rebuildRow( array $row, array $data ) : void
{
$classCalled = explode( '\\', \get_called_class() );
$classCalled = explode( '\\', get_called_class() );
$class = $data['class'];
$item = $class::constructFromData( $row );
$item->author()->achievementAction( 'core', array_pop( $classCalled ), $item );
@@ -10,32 +10,47 @@
namespace IPS\core\Achievements\Actions;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
use IPS\Application;
use IPS\core\Achievements\Rule;
use IPS\Helpers\Form\Node;
use IPS\Helpers\Form\Number;
use IPS\Helpers\Form\Select;
use IPS\Http\Url;
use IPS\Member;
use IPS\Theme;
use OutOfRangeException;
use function count;
use function defined;
use function get_class;
use function in_array;
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
header( ( $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* Abstract Achievement Action Extension for content-related things
*/
abstract class _AbstractNodeAchievementAction extends AbstractAchievementAction
abstract class NodeAchievementActionAbstract extends AchievementActionAbstract
{
/**
* Get filter form elements
*
* @param array|NULL $filters Current filter values (if editing)
* @param \IPS\Http\Url $url The URL the form is being shown on
* @param Url $url The URL the form is being shown on
* @return array
*/
public function filters( ?array $filters, \IPS\Http\Url $url ): array
public function filters( ?array $filters, Url $url ): array
{
$contentTypeOptions = [];
$contentTypeToggles = [];
$_return = [];
$defaultApp = NULL;
foreach( \IPS\Application::applications() as $directory => $application )
foreach( Application::applications() as $directory => $application )
{
if( $application->default )
{
@@ -43,7 +58,7 @@ abstract class _AbstractNodeAchievementAction extends AbstractAchievementAction
break;
}
}
foreach ( \IPS\Application::allExtensions( 'core', 'ContentRouter', FALSE, $defaultApp ) as $extension )
foreach ( Application::allExtensions( 'core', 'ContentRouter', FALSE, $defaultApp ) as $extension )
{
foreach ( $extension->classes as $class )
{
@@ -51,27 +66,26 @@ abstract class _AbstractNodeAchievementAction extends AbstractAchievementAction
{
$nodeClass = $class::$containerNodeClass;
$nodeFilterKey = 'achievement_subfilter_Node_type_' . str_replace( '\\', '-', $nodeClass );
$contentTypeToggles[ $nodeClass ][] = $nodeFilterKey;
$contentTypeToggles[ $nodeClass ] = [ $nodeFilterKey ];
$contentTypeOptions[ $nodeClass ] = $nodeClass::fullyQualifiedType();
$nodeFilter = new \IPS\Helpers\Form\Node( $nodeFilterKey, ( $filters and isset( $filters[ 'nodes_' . str_replace( '\\', '-', $nodeClass ) ] ) and $filters[ 'nodes_' . str_replace( '\\', '-', $nodeClass ) ] ) ? $filters[ 'nodes_' . str_replace( '\\', '-', $nodeClass ) ] : 0, FALSE, [
$nodeFilter = new Node( $nodeFilterKey, ( $filters and isset( $filters[ 'nodes_' . str_replace( '\\', '-', $nodeClass ) ] ) and $filters[ 'nodes_' . str_replace( '\\', '-', $nodeClass ) ] ) ? $filters[ 'nodes_' . str_replace( '\\', '-', $nodeClass ) ] : 0, FALSE, [
'url' => $url,
'class' => $class::$containerNodeClass,
'showAllNodes' => TRUE,
'multiple' => TRUE,
], NULL, \IPS\Member::loggedIn()->language()->addToStack( 'achievement_filter_Node_node_prefix') );
$nodeFilter->label = \IPS\Member::loggedIn()->language()->addToStack( 'achievement_filter_Node_node', FALSE, [ 'sprintf' => [ \IPS\Member::loggedIn()->language()->addToStack( ($class::$containerNodeClass)::$nodeTitle . '_sg', FALSE, [ 'strtolower' => TRUE ] ) ] ] );
], NULL, Member::loggedIn()->language()->addToStack( 'achievement_filter_Node_node_prefix') );
$nodeFilter->label = Member::loggedIn()->language()->addToStack( 'achievement_filter_Node_node', FALSE, [ 'sprintf' => [ Member::loggedIn()->language()->addToStack( ($class::$containerNodeClass)::$nodeTitle . '_sg', FALSE, [ 'strtolower' => TRUE ] ) ] ] );
$_return[ "nodes_" . str_replace( '\\', '-', $nodeClass ) ] = $nodeFilter;
}
}
}
$typeFilter = new \IPS\Helpers\Form\Select( 'achievement_filter_Node_type', ( $filters and isset( $filters['type'] ) and $filters['type'] ) ? $filters['type'] : NULL, FALSE, [ 'options' => $contentTypeOptions, 'toggles' => $contentTypeToggles ], NULL, \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_type_prefix') );
$typeFilter->label = \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_type');
$typeFilter = new Select( 'achievement_filter_Node_type', ( $filters and isset( $filters['type'] ) and $filters['type'] ) ? $filters['type'] : NULL, FALSE, [ 'options' => $contentTypeOptions, 'toggles' => $contentTypeToggles ], NULL, Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_type_prefix') );
$typeFilter->label = Member::loggedIn()->language()->addToStack('achievement_filter_NewContentItem_type');
$nthFilter = new \IPS\Helpers\Form\Number( 'achievement_filter_Node_nth', ( $filters and isset( $filters['milestone'] ) and $filters['milestone'] ) ? $filters['milestone'] : 0, FALSE, [], NULL, \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_nth_their'), \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_Node_nth_suffix') );
$nthFilter->label = \IPS\Member::loggedIn()->language()->addToStack('achievement_filter_Node_nth');
$nthFilter = new Number( 'achievement_filter_Node_nth', ( $filters and isset( $filters['milestone'] ) and $filters['milestone'] ) ? $filters['milestone'] : 0, FALSE, [], NULL, Member::loggedIn()->language()->addToStack('achievement_filter_nth_their'), Member::loggedIn()->language()->addToStack('achievement_filter_Node_nth_suffix') );
$nthFilter->label = Member::loggedIn()->language()->addToStack('achievement_filter_Node_nth');
$return = [ 'type' => $typeFilter ];
foreach ( $_return as $k => $v )
@@ -117,12 +131,12 @@ abstract class _AbstractNodeAchievementAction extends AbstractAchievementAction
* calls that BEFORE making its change in the database (or there is read/write separation), you will need to add
* 1 to the value being considered for milestones
*
* @param \IPS\Member $subject The subject member
* @param Member $subject The subject member
* @param array $filters The value returned by formatFilterValues()
* @param mixed $extra Any additional information about what is happening (e.g. if a post is being made: the post object)
* @return bool
*/
public function filtersMatch( \IPS\Member $subject, array $filters, $extra = NULL ): bool
public function filtersMatch( Member $subject, array $filters, mixed $extra = NULL ): bool
{
if ( isset( $filters['type'] ) )
{
@@ -131,9 +145,9 @@ abstract class _AbstractNodeAchievementAction extends AbstractAchievementAction
return FALSE;
}
if ( isset( $filters[ 'nodes_' . str_replace( '\\', '-', \get_class( $extra ) ) ] ) )
if ( isset( $filters[ 'nodes_' . str_replace( '\\', '-', get_class( $extra ) ) ] ) )
{
if ( !\in_array( $extra->_id, $filters[ 'nodes_' . str_replace( '\\', '-', \get_class( $extra ) ) ] ) )
if ( !in_array( $extra->_id, $filters[ 'nodes_' . str_replace( '\\', '-', get_class( $extra ) ) ] ) )
{
return FALSE;
}
@@ -147,22 +161,22 @@ abstract class _AbstractNodeAchievementAction extends AbstractAchievementAction
* Get identifier to prevent the member being awarded points for the same action twice
* Must be unique within within of this domain, must not exceed 32 chars.
*
* @param \IPS\Member $subject The subject member
* @param Member $subject The subject member
* @param mixed $extra Any additional information about what is happening (e.g. if a post is being made: the post object)
* @return string
*/
public function identifier( \IPS\Member $subject, $extra = NULL ): string
public function identifier( Member $subject, mixed $extra = NULL ): string
{
return \get_class( $extra ) . ':' . $extra->{$extra::$databaseColumnId} . ':' . $subject->member_id;
return get_class( $extra ) . ':' . $extra->{$extra::$databaseColumnId} . ':' . $subject->member_id;
}
/**
* Get "description" for rule (usually a description of the rule's filters)
*
* @param \IPS\core\Achievements\Rule $rule The rule
* @param Rule $rule The rule
* @return string|NULL
*/
protected function _nodeFilterDescription( \IPS\core\Achievements\Rule $rule ): ?string
protected function _nodeFilterDescription( Rule $rule ): ?string
{
if ( isset( $rule->filters['type'] ) )
{
@@ -177,18 +191,18 @@ abstract class _AbstractNodeAchievementAction extends AbstractAchievementAction
{
$nodeNames[] = $nodeClass::load( $id )->_title;
}
catch ( \OutOfRangeException $e ) {}
catch ( OutOfRangeException $e ) {}
}
if ( $nodeNames )
{
return \IPS\Member::loggedIn()->language()->addToStack( 'achievements_title_filter_location', FALSE, [
return Member::loggedIn()->language()->addToStack( 'achievements_title_filter_location', FALSE, [
'htmlsprintf' => [
\IPS\Theme::i()->getTemplate( 'achievements' )->ruleDescriptionBadge( 'location',
\count( $nodeNames ) === 1 ? $nodeNames[0] : \IPS\Member::loggedIn()->language()->addToStack( 'achievements_title_filter_location_val', FALSE, [ 'sprintf' => [
\count( $nodeNames ),
\IPS\Member::loggedIn()->language()->addToStack( $nodeClass::$nodeTitle, FALSE, [ 'strtolower' => TRUE ] )
Theme::i()->getTemplate( 'achievements' )->ruleDescriptionBadge( 'location',
count( $nodeNames ) === 1 ? $nodeNames[0] : Member::loggedIn()->language()->addToStack( 'achievements_title_filter_location_val', FALSE, [ 'sprintf' => [
count( $nodeNames ),
Member::loggedIn()->language()->addToStack( $nodeClass::$nodeTitle, FALSE, [ 'strtolower' => TRUE ] )
] ] ),
\count( $nodeNames ) === 1 ? NULL : $nodeNames
count( $nodeNames ) === 1 ? NULL : $nodeNames
)
],
] );
+172 -84
View File
@@ -11,42 +11,78 @@
namespace IPS\core\Achievements;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
use DomainException;
use Exception;
use IPS\core\CustomBadge;
use IPS\Data\Store;
use IPS\Db;
use IPS\File;
use IPS\Helpers\Form;
use IPS\Helpers\Form\Translatable;
use IPS\Helpers\Form\Upload;
use IPS\Helpers\Form\YesNo;
use IPS\Image;
use IPS\Lang;
use IPS\Member;
use IPS\Node\Model;
use IPS\Patterns\ActiveRecord;
use IPS\Settings;
use IPS\Theme;
use OutOfRangeException;
use XMLReader;
use function count;
use function defined;
use function is_array;
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
header( ( $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* Badge Model (as in, a representation of a badge a member *can* earn, not a badge a particular member *has* earned)
*/
class _Badge extends \IPS\Node\Model
class Badge extends Model
{
/**
* @brief Database Table
*/
public static $databaseTable = 'core_badges';
public static ?string $databaseTable = 'core_badges';
/**
* @brief Multiton Store
*/
protected static $multitons;
protected static array $multitons;
/**
* @brief [Node] Node Title
*/
public static $nodeTitle = 'menu__core_achievements_badges';
public static string $nodeTitle = 'menu__core_achievements_badges';
/**
* @brief [Node] Title prefix. If specified, will look for a language key with "{$key}_title" as the key
*/
public static $titleLangPrefix = 'core_badges_';
public static ?string $titleLangPrefix = 'core_badges_';
/**
* @brief [ActiveRecord] Database ID Fields
* @note If using this, declare a static $multitonMap = array(); in the child class to prevent duplicate loading queries
*/
protected static $databaseIdFields = array('recognize');
protected static array $databaseIdFields = array('recognize');
/**
* @brief [ActiveRecord] Caches
* @note Defined cache keys will be cleared automatically as needed
*/
protected array $caches = array( 'badges' );
/**
* @brief [ActiveRecord] Attempt to load from cache
* @note If this is set to TRUE you should define a getStore() method to return the objects from cache
*/
protected static bool $loadFromCache = true;
/**
* @brief [Node] ACP Restrictions
@@ -64,21 +100,28 @@ class _Badge extends \IPS\Node\Model
'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(
protected static ?array $restrictions = array(
'app' => 'core',
'module' => 'achievements',
'prefix' => 'badges_',
'all' => 'badges_manage',
);
/**
* Determines if this class can be extended via UI Extension
*
* @var bool
*/
public static bool $canBeExtended = true;
/**
* Construct ActiveRecord from database row
*
* @param array $data Row from database table
* @param bool $updateMultitonStoreIfExists Replace current object in multiton store if it already exists there?
* @return static
* @param array $data Row from database table
* @param bool $updateMultitonStoreIfExists Replace current object in multiton store if it already exists there?
* @return ActiveRecord
*/
public static function constructFromData( $data, $updateMultitonStoreIfExists = TRUE )
public static function constructFromData( array $data, bool $updateMultitonStoreIfExists = TRUE ): ActiveRecord
{
$obj = parent::constructFromData( $data, $updateMultitonStoreIfExists );
@@ -86,9 +129,9 @@ class _Badge extends \IPS\Node\Model
{
try
{
$obj->recognize = \IPS\core\Achievements\Recognize::load( $obj->recognize );
$obj->recognize = Recognize::load( $obj->recognize );
}
catch( \Exception $e )
catch( Exception $e )
{
/* Problem loading, so reset to 0 */
$obj->recognize = 0;
@@ -106,7 +149,7 @@ class _Badge extends \IPS\Node\Model
/**
* @var null|array
*/
static $badgeAwardLangBits = NULL;
static ?array $badgeAwardLangBits = NULL;
/**
* Show the public reason for this badge award
@@ -119,7 +162,7 @@ class _Badge extends \IPS\Node\Model
{
if ( static::$badgeAwardLangBits === NULL )
{
foreach( \IPS\Db::i()->select( 'word_key, word_default, word_custom', 'core_sys_lang_words', [ 'lang_id=? AND (word_key LIKE \'core_award_subject_badge_%\' OR word_key LIKE \'core_award_other_badge_%\')', \IPS\Member::loggedIn()->language()->id ] ) as $row )
foreach( Db::i()->select( 'word_key, word_default, word_custom', 'core_sys_lang_words', [ 'lang_id=? AND (word_key LIKE \'core_award_subject_badge_%\' OR word_key LIKE \'core_award_other_badge_%\')', Member::loggedIn()->language()->id ] ) as $row )
{
static::$badgeAwardLangBits[ $row['word_key'] ] = $row['word_custom'] ?: $row['word_default'];
}
@@ -131,19 +174,23 @@ class _Badge extends \IPS\Node\Model
/**
* [Node] Add/Edit Form
*
* @param \IPS\Helpers\Form $form The form
* @param Form $form The form
* @return void
*/
public function form( &$form )
public function form( Form &$form ) : void
{
/* Allow SVGs without the obscure hash removing the file extension */
\IPS\File::$safeFileExtensions[] = 'svg';
File::$safeFileExtensions[] = 'svg';
$form->add( new \IPS\Helpers\Form\Translatable( 'badge_name', NULL, TRUE, array( 'app' => 'core', 'key' => ( $this->id ? "core_badges_{$this->id}" : NULL ) ) ) );
$form->add( new \IPS\Helpers\Form\Upload( 'badge_image', $this->image ? \IPS\File::get( 'core_Badges', $this->image ) : NULL, TRUE, array( 'obscure' => TRUE, 'checkImage' => TRUE, 'allowedFileTypes' => array_merge( \IPS\Image::supportedExtensions(), ['svg'] ), 'storageExtension' => 'core_Badges', 'allowStockPhotos' => FALSE ), function( $val ) {
$form->add( new Translatable( 'badge_name', NULL, TRUE, array( 'app' => 'core', 'key' => ( $this->id ? "core_badges_{$this->id}" : NULL ) ) ) );
$badge = CustomBadge::getRecordBadge( $this );
$badge->addBadgeFieldsToForm( $form, !$this->badge_use_image, ['badge_image'] );
$form->add( new Upload( 'badge_image', $this->image ? File::get( 'core_Badges', $this->image ) : NULL, TRUE, array( 'obscure' => TRUE, 'checkImage' => TRUE, 'allowedFileTypes' => array_merge( Image::supportedExtensions(), ['svg'] ), 'storageExtension' => 'core_Badges', 'allowStockPhotos' => FALSE ), function( $val ) {
if( !$val )
{
throw new \DomainException('achievements_bad_image');
throw new DomainException('achievements_bad_image');
}
/* Good luck with your fancy SVG */
@@ -152,16 +199,18 @@ class _Badge extends \IPS\Node\Model
{
try
{
$image = \IPS\Image::create( $val->contents() );
$image = Image::create( $val->contents() );
}
catch ( \Exception $e )
catch ( Exception $e )
{
throw new \DomainException( 'achievements_bad_image' );
throw new DomainException( 'achievements_bad_image' );
}
}
} ) );
}, null, null, 'badge_image' ) );
$form->add( new \IPS\Helpers\Form\YesNo( 'badge_manually_awarded', $this->manually_awarded ) );
$form->add( new YesNo( 'badge_manually_awarded', $this->manually_awarded ) );
parent::form( $form );
}
/**
@@ -170,30 +219,48 @@ class _Badge extends \IPS\Node\Model
* @param array $values Values from the form
* @return array
*/
public function formatFormValues( $values )
public function formatFormValues( array $values ): array
{
if ( !$this->id )
{
$this->save();
}
\IPS\Lang::saveCustom( 'core', "core_badges_{$this->id}", $values['badge_name'] );
Lang::saveCustom( 'core', "core_badges_{$this->id}", $values['badge_name'] );
unset( $values['badge_name'] );
$_values = $values;
$values = array();
foreach ( $_values as $k => $v )
{
if( mb_substr( $k, 0, 6 ) === 'badge_' )
if( in_array( $k, [ 'badge_image', 'badge_manually_awarded' ] ) )
{
$values[ mb_substr( $k, 6 ) ] = $v;
}
else if ( $k === 'badge_use_custom' )
{
$values['badge_use_image'] = !$v;
if( !$values['badge_use_image'] )
{
$values['image'] = null;
}
}
else
{
$values[ $k ] = $v;
}
}
/* Generate a custom SVG for this badge if we're not using a custom image */
if ( ( !array_key_exists( 'badge_use_image', $values ) and !$this->badge_use_image ) or ( array_key_exists( 'badge_use_image', $values ) and !$values['badge_use_image'] ) )
{
CustomBadge::saveRecordBadge( $this, CustomBadge::generateBadgeFromFormValues( $values ) );
}
else
{
CustomBadge::clearCustomBadgeFields( $values );
}
return $values;
}
@@ -203,21 +270,26 @@ class _Badge extends \IPS\Node\Model
* @note Return the class for the icon (e.g. 'globe', the 'fa fa-' is added automatically so you do not need this here)
* @return string|null
*/
protected function get__icon()
protected function get__icon(): mixed
{
return \IPS\File::get( 'core_Badges', $this->image );
if ( !$this->badge_use_image )
{
return CustomBadge::getRecordBadge( $this )->url();
}
return File::get( 'core_Badges', $this->image );
}
/**
* Get badge HTML
*
* @param string|null $cssClass Additional CSS class to apply
* @param bool|null $tooltip Whether or not to apply a tooltip to the badge
* @return string
* @param string|null $cssClass Additional CSS class to apply
* @param bool|null $tooltip Whether or not to apply a tooltip to the badge
* @param bool|null $showRare
* @return string
*/
public function html( ?string $cssClass = NULL, ?bool $tooltip = TRUE, ?bool $showRare = FALSE ): string
{
return \IPS\Theme::i()->getTemplate( 'global', 'core', 'global' )->badge( $this, $cssClass, $tooltip, $showRare );
return Theme::i()->getTemplate( 'global', 'core', 'global' )->badge( $this, $cssClass, $tooltip, $showRare );
}
/**
@@ -227,23 +299,23 @@ class _Badge extends \IPS\Node\Model
*/
public function isRare(): bool
{
if ( !\IPS\Settings::i()->rare_badge_percent )
if ( !Settings::i()->rare_badge_percent )
{
return FALSE;
}
$stats = $this->getBadgeStats();
return ( 100 / $stats['memberCount'] * $stats['badgeCount'][ $this->id ] ) < \IPS\Settings::i()->rare_badge_percent;
return ( 100 / $stats['memberCount'] * $stats['badgeCount'][ $this->id ] ) < Settings::i()->rare_badge_percent;
}
/**
* Return number of people who have this badge
*
* @param bool|null $roundUp Round number to nearest 100 to be less specific
* @return int
* @return int|null
*/
public function ownedByCount( bool $roundUp=FALSE )
public function ownedByCount( ?bool $roundUp=FALSE ) : ?int
{
if ( $stats = $this->getBadgeStats() and isset( $stats['badgeCount'][ $this->id ] ) )
{
@@ -270,9 +342,9 @@ class _Badge extends \IPS\Node\Model
/* Fetch the counts we need from the datastore. If they are old or non-existent, refresh and store in datastore for next time. */
$stats = NULL;
if( isset( \IPS\Data\Store::i()->badgeStats ) )
if( isset( Store::i()->badgeStats ) )
{
$stats = json_decode( \IPS\Data\Store::i()->badgeStats, true );
$stats = json_decode( Store::i()->badgeStats, true );
if( !isset( $stats['expiration'] ) OR time() > $stats['expiration'] OR !isset( $stats['badgeCount'][ $this->id ] ) )
{
@@ -282,35 +354,35 @@ class _Badge extends \IPS\Node\Model
if( $stats === NULL )
{
$exclude = json_decode( \IPS\Settings::i()->rules_exclude_groups, TRUE );
$exclude = json_decode( Settings::i()->rules_exclude_groups, TRUE );
$where = [ [ 'completed=?', true ] ];
$subQuery = NULL;
if ( \is_array( $exclude ) and \count( $exclude ) )
if ( is_array( $exclude ) and count( $exclude ) )
{
$subQuery = \IPS\Db::i()->select( 'member_id', 'core_members', [ \IPS\Db::i()->in( 'member_group_id', $exclude ) ] );
$where[] = [ \IPS\Db::i()->in( 'member_group_id', $exclude, TRUE ) ];
$subQuery = Db::i()->select( 'member_id', 'core_members', [ Db::i()->in( 'member_group_id', $exclude ) ] );
$where[] = [ Db::i()->in( 'member_group_id', $exclude, TRUE ) ];
}
$stats = array(
'expiration' => time() + ( 3600 * 6 ), // Cache for 6 hours
'memberCount' => \IPS\Db::i()->select( 'COUNT(*)', 'core_members', $where )->first(),
'memberCount' => Db::i()->select( 'COUNT(*)', 'core_members', $where )->first(),
'badgeCount' => array(),
);
foreach( \IPS\Db::i()->select( 'id', 'core_badges' ) as $badgeId )
foreach( Db::i()->select( 'id', 'core_badges' ) as $badgeId )
{
$where = [ [ 'badge=?', $badgeId ] ];
if ( \is_array( $exclude ) and \count( $exclude ) )
if ( is_array( $exclude ) and count( $exclude ) )
{
$where[] = [ \IPS\Db::i()->in( 'core_member_badges.member', $subQuery, TRUE ) ];
$where[] = [ Db::i()->in( 'core_member_badges.member', $subQuery, TRUE ) ];
}
$stats['badgeCount'][ $badgeId ] = \IPS\Db::i()->select( 'COUNT(*)', 'core_member_badges', $where )->first();
$stats['badgeCount'][ $badgeId ] = Db::i()->select( 'COUNT(*)', 'core_member_badges', $where )->first();
}
\IPS\Data\Store::i()->badgeStats = json_encode( $stats );
Store::i()->badgeStats = json_encode( $stats );
}
return $stats;
@@ -333,17 +405,17 @@ class _Badge extends \IPS\Node\Model
parent::__clone();
\IPS\Lang::saveCustom( 'core', "core_badges_{$this->id}", iterator_to_array( \IPS\Db::i()->select( 'word_custom, lang_id', 'core_sys_lang_words', array( 'word_key=?', "core_badges_{$oldId}" ) )->setKeyField( 'lang_id' )->setValueField('word_custom') ) );
Lang::saveCustom( 'core', "core_badges_{$this->id}", iterator_to_array( Db::i()->select( 'word_custom, lang_id', 'core_sys_lang_words', array( 'word_key=?', "core_badges_{$oldId}" ) )->setKeyField( 'lang_id' )->setValueField('word_custom') ) );
if ( $oldImage )
{
try
{
$image = \IPS\File::get( 'core_Badges', $oldImage );
$newImage = \IPS\File::create( 'core_Badges', $image->originalFilename, $image->contents() );
$image = File::get( 'core_Badges', $oldImage );
$newImage = File::create( 'core_Badges', $image->originalFilename, $image->contents() );
$this->image = (string) $newImage;
}
catch ( \Exception $e )
catch ( Exception $e )
{
$this->image = NULL;
}
@@ -355,29 +427,47 @@ class _Badge extends \IPS\Node\Model
/**
* Delete Record
*
* @return void
* @return void
*/
public function delete()
public function delete(): void
{
/* Remove from recognize where just the badge is used, and no points */
\IPS\Db::i()->delete( 'core_member_recognize', [ 'r_points=0 and r_badge=?', $this->id ] );
Db::i()->delete( 'core_member_recognize', [ 'r_points=0 and r_badge=?', $this->id ] );
/* Remove the badge from recognize, but leave points */
\IPS\Db::i()->update( 'core_member_recognize', [ 'r_badge' => 0 ], [ 'r_badge=?', $this->id ] );
Db::i()->update( 'core_member_recognize', [ 'r_badge' => 0 ], [ 'r_badge=?', $this->id ] );
if ( $this->image )
{
try
{
\IPS\File::get( 'core_Badges', $this->image )->delete();
File::get( 'core_Badges', $this->image )->delete();
}
catch( \Exception $ex ) { }
catch( Exception $ex ) { }
}
parent::delete();
\IPS\Db::i()->delete( 'core_member_badges', [ 'badge=?', $this->id ] );
\IPS\Lang::deleteCustom( 'core', "core_badges_{$this->id}" );
Db::i()->delete( 'core_member_badges', [ 'badge=?', $this->id ] );
Lang::deleteCustom( 'core', "core_badges_{$this->id}" );
}
/**
* Attempt to load cached data
*
* @note This should be overridden in your class if you define $cacheToLoadFrom
* @return array
*/
public static function getStore(): array
{
try
{
return Store::i()->badges;
}
catch( OutOfRangeException ){}
Store::i()->badges = iterator_to_array( Db::i()->select( '*', static::$databaseTable, NULL, static::$databasePrefix . static::$databaseColumnId )->setKeyField( static::$databasePrefix . static::$databaseColumnId ) );
return Store::i()->badges;
}
/**
@@ -387,7 +477,7 @@ class _Badge extends \IPS\Node\Model
*/
public static function show(): bool
{
return !( ( \IPS\Settings::i()->achievements_rebuilding or !\IPS\Settings::i()->achievements_enabled ) );
return !( ( Settings::i()->achievements_rebuilding or !Settings::i()->achievements_enabled ) );
}
/**
@@ -398,7 +488,7 @@ class _Badge extends \IPS\Node\Model
public static function getAssignedBadgeIds(): array
{
$assignedBadges = [];
foreach( \IPS\Db::i()->select( 'badge_subject, badge_other', 'core_achievements_rules', [ 'badge_subject > 0 or badge_other > 0' ] ) as $row )
foreach( Db::i()->select( 'badge_subject, badge_other', 'core_achievements_rules', [ 'badge_subject > 0 or badge_other > 0' ] ) as $row )
{
if ( $row['badge_subject'] )
{
@@ -422,14 +512,14 @@ class _Badge extends \IPS\Node\Model
*
* @return void
*/
public static function importXml( $file, $deleteExisting=FALSE )
public static function importXml( string $file, bool $deleteExisting=FALSE ) : void
{
/* Open XML file */
$xml = \IPS\Xml\XMLReader::safeOpen( $file );
if ( ! @$xml->read() )
{
throw new \DomainException( 'xml_upload_invalid' );
throw new DomainException( 'xml_upload_invalid' );
}
/* Did we want to wipe first? */
@@ -438,12 +528,12 @@ class _Badge extends \IPS\Node\Model
$assignedBadges = static::getAssignedBadgeIds();
$where = NULL;
if ( \count( $assignedBadges ) )
if ( count( $assignedBadges ) )
{
$where = [ \IPS\Db::i()->in( '`id`', $assignedBadges, TRUE ) ];
$where = [ Db::i()->in( '`id`', $assignedBadges, TRUE ) ];
}
foreach( \IPS\Db::i()->select('*', 'core_badges', $where ) as $row )
foreach( Db::i()->select('*', 'core_badges', $where ) as $row )
{
static::constructFromData( $row )->delete();
}
@@ -452,7 +542,7 @@ class _Badge extends \IPS\Node\Model
/* Start looping through each row */
while ( $xml->read() and $xml->name == 'badge' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
if( $xml->nodeType != XMLReader::ELEMENT )
{
continue;
}
@@ -462,7 +552,7 @@ class _Badge extends \IPS\Node\Model
while ( $xml->read() and $xml->name != 'badge' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
if( $xml->nodeType != XMLReader::ELEMENT )
{
continue;
}
@@ -486,17 +576,17 @@ class _Badge extends \IPS\Node\Model
if ( ! empty( $insert['icon_name'] ) and ! empty( $insert['icon_data'] ) )
{
$insert['image'] = (string) \IPS\File::create( 'core_Badges', $insert['icon_name'], $insert['icon_data'], NULL, TRUE, NULL, FALSE );
$insert['image'] = (string) File::create( 'core_Badges', $insert['icon_name'], $insert['icon_data'], NULL, TRUE, NULL, FALSE );
unset( $insert['icon_name'] );
unset( $insert['icon_data'] );
}
$insertId = \IPS\Db::i()->insert( 'core_badges', $insert );
$insertId = Db::i()->insert( 'core_badges', $insert );
if ( ! empty( $title ) )
{
\IPS\Lang::saveCustom( 'core', "core_badges_{$insertId}", $title );
Lang::saveCustom( 'core', "core_badges_{$insertId}", $title );
}
}
}
@@ -504,20 +594,18 @@ class _Badge extends \IPS\Node\Model
/**
* Get output for API
*
* @param \IPS\Member|NULL $authorizedMember The member making the API request or NULL for API Key / client_credentials
* @param Member|NULL $authorizedMember The member making the API request or NULL for API Key / client_credentials
* @return array
* @apiresponse int id ID number
* @apiresponse string name Name
* @apiresponse array statistcs Badge Statistics
*/
public function apiOutput( \IPS\Member $authorizedMember = NULL )
public function apiOutput( Member $authorizedMember = NULL ): array
{
$return = array(
return array(
'id' => $this->id,
'name' => $this->_title,
'statistics' => $this->getBadgeStats(),
);
return $return;
}
}
+109 -58
View File
@@ -11,46 +11,69 @@
namespace IPS\core\Achievements;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
use ArrayIterator;
use DomainException;
use Exception;
use IPS\core\CustomBadge;
use IPS\Data\Store;
use IPS\Db;
use IPS\File;
use IPS\Helpers\Form;
use IPS\Helpers\Form\Number;
use IPS\Helpers\Form\Translatable;
use IPS\Helpers\Form\Upload;
use IPS\Image;
use IPS\Lang;
use IPS\Member;
use IPS\Node\Model;
use IPS\Patterns\ActiveRecordIterator;
use IPS\Settings;
use IPS\Theme;
use XMLReader;
use function count;
use function defined;
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
header( ( $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* Rank Model
*/
class _Rank extends \IPS\Node\Model
class Rank extends Model
{
/**
* @brief Database Table
*/
public static $databaseTable = 'core_member_ranks';
public static ?string $databaseTable = 'core_member_ranks';
/**
* @brief [Node] Order Database Column
*/
public static $databaseColumnOrder = 'points';
public static ?string $databaseColumnOrder = 'points';
/**
* @brief [Node] Sortable?
*/
public static $nodeSortable = FALSE;
public static bool $nodeSortable = FALSE;
/**
* @brief Multiton Store
*/
protected static $multitons;
protected static array $multitons;
/**
* @brief [Node] Node Title
*/
public static $nodeTitle = 'menu__core_achievements_ranks';
public static string $nodeTitle = 'menu__core_achievements_ranks';
/**
* @brief [Node] Title prefix. If specified, will look for a language key with "{$key}_title" as the key
*/
public static $titleLangPrefix = 'core_member_rank_';
public static ?string $titleLangPrefix = 'core_member_rank_';
/**
* @brief [Node] ACP Restrictions
@@ -68,7 +91,7 @@ class _Rank extends \IPS\Node\Model
'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(
protected static ?array $restrictions = array(
'app' => 'core',
'module' => 'achievements',
'prefix' => 'ranks_',
@@ -78,7 +101,14 @@ class _Rank extends \IPS\Node\Model
* @brief [ActiveRecord] Caches
* @note Defined cache keys will be cleared automatically as needed
*/
protected $caches = ['achievementRanks'];
protected array $caches = ['achievementRanks'];
/**
* Determines if this class can be extended via UI Extension
*
* @var bool
*/
public static bool $canBeExtended = true;
/**
* [ActiveRecord] Get cached rules
@@ -87,21 +117,21 @@ class _Rank extends \IPS\Node\Model
*/
public static function getStore(): array
{
if ( !isset( \IPS\Data\Store::i()->achievementRanks ) )
if ( !isset( Store::i()->achievementRanks ) )
{
\IPS\Data\Store::i()->achievementRanks = iterator_to_array( \IPS\Db::i()->select( '*', static::$databaseTable, NULL, 'points' )->setKeyField( static::$databasePrefix . static::$databaseColumnId ) );
Store::i()->achievementRanks = iterator_to_array( Db::i()->select( '*', static::$databaseTable, NULL, 'points' )->setKeyField( static::$databasePrefix . static::$databaseColumnId ) );
}
return iterator_to_array( new \IPS\Patterns\ActiveRecordIterator( new \ArrayIterator( \IPS\Data\Store::i()->achievementRanks ), 'IPS\core\Achievements\Rank' ) );
return iterator_to_array( new ActiveRecordIterator( new ArrayIterator( Store::i()->achievementRanks ), 'IPS\core\Achievements\Rank' ) );
}
/**
* Work out the rank for a given number of points
*
* @param int $points Number of points
* @return \IPS\core\Achievements\Rank|NULL
* @return Rank|NULL
*/
public static function fromPoints( $points ): ?\IPS\core\Achievements\Rank
public static function fromPoints( int $points ): ?Rank
{
$return = NULL;
foreach ( static::getStore() as $rank )
@@ -124,19 +154,24 @@ class _Rank extends \IPS\Node\Model
* @note Return the class for the icon (e.g. 'globe', the 'fa fa-' is added automatically so you do not need this here)
* @return mixed
*/
protected function get__icon()
protected function get__icon(): mixed
{
if ( !$this->rank_use_image )
{
return CustomBadge::getRecordBadge( $this )->url();
}
if ( $this->icon )
{
return \IPS\File::get( 'core_Ranks', $this->icon );
return File::get( 'core_Ranks', $this->icon );
}
else
{
return \IPS\Theme::i()->resource( 'default_rank.png', 'core', 'global' );
return Theme::i()->resource( 'default_rank.png', 'core', 'global' );
}
}
protected static $rankPositions = [];
protected static array $rankPositions = [];
/**
* Fetch the rank position from all ranks
*
@@ -160,7 +195,7 @@ class _Rank extends \IPS\Node\Model
static::$rankPositions[ $this->id ] = [
'pos' => $pos,
'max' => \count( static::getStore() )
'max' => count( static::getStore() )
];
}
@@ -176,36 +211,40 @@ class _Rank extends \IPS\Node\Model
*/
public function html( ?string $cssClass = NULL ): string
{
return \IPS\Theme::i()->getTemplate( 'global', 'core', 'global' )->rank( $this, $cssClass );
return Theme::i()->getTemplate( 'global', 'core', 'global' )->rank( $this, $cssClass );
}
/**
* [Node] Get Node Description
*
* @return string
* @return string|null
*/
protected function get__description()
protected function get__description(): ?string
{
return \IPS\Member::loggedIn()->language()->addToStack( 'achievements_awards_points', FALSE, [ 'pluralize' => [ $this->points ] ] );
return Member::loggedIn()->language()->addToStack( 'achievements_awards_points', FALSE, [ 'pluralize' => [ $this->points ] ] );
}
/**
* [Node] Add/Edit Form
*
* @param \IPS\Helpers\Form $form The form
* @param Form $form The form
* @return void
*/
public function form( &$form )
public function form( Form &$form ) : void
{
/* Allow SVGs without the obscure hash removing the file extension */
\IPS\File::$safeFileExtensions[] = 'svg';
File::$safeFileExtensions[] = 'svg';
$form->add( new \IPS\Helpers\Form\Translatable( 'member_ranks_word_custom', NULL, TRUE, array( 'app' => 'core', 'key' => ( $this->id ? "core_member_rank_{$this->id}" : NULL ) ) ) );
$form->add( new \IPS\Helpers\Form\Number( 'member_ranks_points', $this->points ?: 0, TRUE, array( 'min' => 0 ) ) );
$form->add( new \IPS\Helpers\Form\Upload( 'member_ranks_icon', $this->icon ? \IPS\File::get( 'core_Ranks', $this->icon ) : NULL, TRUE, array( 'obscure' => TRUE, 'allowedFileTypes' => array_merge( \IPS\Image::supportedExtensions(), ['svg'] ), 'checkImage' => TRUE, 'storageExtension' => 'core_Ranks' ), function( $val ) {
$form->add( new Translatable( 'member_ranks_word_custom', NULL, TRUE, array( 'app' => 'core', 'key' => ( $this->id ? "core_member_rank_{$this->id}" : NULL ) ) ) );
$form->add( new Number( 'member_ranks_points', $this->points ?: 0, TRUE, array( 'min' => 0 ) ) );
$badge = CustomBadge::getRecordBadge( $this );
$badge->addBadgeFieldsToForm( $form, !$this->rank_use_image, ['member_ranks_icon'], 'rank', false );
$form->add( new Upload( 'member_ranks_icon', $this->icon ? File::get( 'core_Ranks', $this->icon ) : NULL, TRUE, array( 'obscure' => TRUE, 'allowedFileTypes' => array_merge( Image::supportedExtensions(), ['svg'] ), 'checkImage' => TRUE, 'storageExtension' => 'core_Ranks' ), function( $val ) {
if( !$val )
{
throw new \DomainException('achievements_bad_image');
throw new DomainException('achievements_bad_image');
}
/* Good luck with your fancy SVG */
@@ -214,14 +253,16 @@ class _Rank extends \IPS\Node\Model
{
try
{
$image = \IPS\Image::create( $val->contents() );
$image = Image::create( $val->contents() );
}
catch ( \Exception $e )
catch ( Exception $e )
{
throw new \DomainException( 'achievements_bad_image' );
throw new DomainException( 'achievements_bad_image' );
}
}
}, NULL, NULL, 'member_ranks_icon' ) );
parent::form( $form );
}
/**
@@ -230,14 +271,14 @@ class _Rank extends \IPS\Node\Model
* @param array $values Values from the form
* @return array
*/
public function formatFormValues( $values )
public function formatFormValues( array $values ): array
{
if ( !$this->id )
{
$this->save();
}
\IPS\Lang::saveCustom( 'core', "core_member_rank_{$this->id}", $values['member_ranks_word_custom'] );
Lang::saveCustom( 'core', "core_member_rank_{$this->id}", $values['member_ranks_word_custom'] );
unset( $values['member_ranks_word_custom'] );
$_values = $values;
@@ -248,11 +289,21 @@ class _Rank extends \IPS\Node\Model
{
$values[ mb_substr( $k, 13 ) ] = $v;
}
else if ( $k === 'rank_use_custom' )
{
$values[ 'rank_use_image' ] = !$v;
}
else
{
$values[ $k ] = $v;
}
}
/* Generate a custom SVG for this badge if we're not using a custom image */
if ( ( !array_key_exists( 'rank_use_image', $values ) and !$this->rank_use_image ) or ( array_key_exists( 'rank_use_image', $values ) and !$values['rank_use_image'] ) )
{
CustomBadge::saveRecordBadge( $this, CustomBadge::generateBadgeFromFormValues( $values, 'rank' ) );
}
return $values;
}
@@ -264,7 +315,7 @@ class _Rank extends \IPS\Node\Model
*/
public static function show(): bool
{
return !( ( \IPS\Settings::i()->achievements_rebuilding or !\IPS\Settings::i()->achievements_enabled ) );
return !( ( Settings::i()->achievements_rebuilding or !Settings::i()->achievements_enabled ) );
}
/**
@@ -288,11 +339,11 @@ class _Rank extends \IPS\Node\Model
{
try
{
$image = \IPS\File::get( 'core_Ranks', $oldImage );
$newImage = \IPS\File::create( 'core_Ranks', $image->originalFilename, $image->contents() );
$image = File::get( 'core_Ranks', $oldImage );
$newImage = File::create( 'core_Ranks', $image->originalFilename, $image->contents() );
$this->icon = (string) $newImage;
}
catch ( \Exception $e )
catch ( Exception $e )
{
$this->icon = NULL;
}
@@ -304,17 +355,17 @@ class _Rank extends \IPS\Node\Model
/**
* Delete Record
*
* @return void
* @return void
*/
public function delete()
public function delete(): void
{
if ( $this->icon )
{
try
{
\IPS\File::get( 'core_Ranks', $this->icon )->delete();
File::get( 'core_Ranks', $this->icon )->delete();
}
catch( \Exception $ex ) { }
catch( Exception $ex ) { }
}
parent::delete();
@@ -323,19 +374,19 @@ class _Rank extends \IPS\Node\Model
/**
* Get output for API
*
* @param \IPS\Member|NULL $authorizedMember The member making the API request or NULL for API Key / client_credentials
* @param Member|NULL $authorizedMember The member making the API request or NULL for API Key / client_credentials
* @return array
* @apiresponse int id ID number
* @apiresponse string name Name
* @apiresponse string url Path to the rank icon
* @apiresponse int points Points
*/
public function apiOutput( \IPS\Member $authorizedMember = NULL )
public function apiOutput( Member $authorizedMember = NULL ): array
{
return array(
'id' => $this->id,
'name' => $this->_title,
'icon' => $this->icon ? (string) $this->_icon->url : $this->_icon,
'icon' => ($this->rank_use_image and $this->icon) ? (string) $this->_icon->url : $this->_icon,
'points' => $this->points
);
}
@@ -348,20 +399,20 @@ class _Rank extends \IPS\Node\Model
*
* @return void
*/
public static function importXml( $file, $option=NULL )
public static function importXml( string $file, ?bool $option=NULL ) : void
{
/* Open XML file */
$xml = \IPS\Xml\XMLReader::safeOpen( $file );
if ( ! @$xml->read() )
{
throw new \DomainException( 'xml_upload_invalid' );
throw new DomainException( 'xml_upload_invalid' );
}
/* Did we want to wipe first? */
if ( $option == 'wipe' )
{
foreach( \IPS\core\Achievements\Rank::getStore() as $rank )
foreach(Rank::getStore() as $rank )
{
$rank->delete();
}
@@ -370,7 +421,7 @@ class _Rank extends \IPS\Node\Model
/* Start looping through each row */
while ( $xml->read() and $xml->name == 'rank' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
if( $xml->nodeType != XMLReader::ELEMENT )
{
continue;
}
@@ -383,7 +434,7 @@ class _Rank extends \IPS\Node\Model
while ( $xml->read() and $xml->name != 'rank' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
if( $xml->nodeType != XMLReader::ELEMENT )
{
continue;
}
@@ -411,7 +462,7 @@ class _Rank extends \IPS\Node\Model
/* Did we want to wipe existing ranks with the same points? */
if ( $option == 'replace' )
{
foreach( \IPS\core\Achievements\Rank::getStore() as $rank )
foreach(Rank::getStore() as $rank )
{
if ( $rank->points == $insert['points'] )
{
@@ -422,20 +473,20 @@ class _Rank extends \IPS\Node\Model
if ( ! empty( $insert['icon_name'] ) and ! empty( $insert['icon_data'] ) )
{
$insert['icon'] = (string) \IPS\File::create( 'core_Ranks', $insert['icon_name'], $insert['icon_data'], NULL, TRUE, NULL, FALSE );
$insert['icon'] = (string) File::create( 'core_Ranks', $insert['icon_name'], $insert['icon_data'], NULL, TRUE, NULL, FALSE );
unset( $insert['icon_name'] );
unset( $insert['icon_data'] );
}
$insertId = \IPS\Db::i()->insert( 'core_member_ranks', $insert );
$insertId = Db::i()->insert( 'core_member_ranks', $insert );
if ( ! empty( $insert['title'] ) )
{
\IPS\Lang::saveCustom( 'core', "core_member_rank_{$insertId}", $insert['title'] );
Lang::saveCustom( 'core', "core_member_rank_{$insertId}", $insert['title'] );
}
}
unset( \IPS\Data\Store::i()->achievementRanks );
unset( Store::i()->achievementRanks );
}
}
@@ -11,77 +11,92 @@
namespace IPS\core\Achievements;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
use BadMethodCallException;
use Exception;
use IPS\Application;
use IPS\Content;
use IPS\Db;
use IPS\Member;
use IPS\Notification;
use IPS\Patterns\ActiveRecord;
use OutOfRangeException;
use function defined;
use function get_class;
use function intval;
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
header( ( $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* Recognize
*/
class _Recognize extends \IPS\Patterns\ActiveRecord
class Recognize extends ActiveRecord
{
/**
* @brief Database Table
*/
public static $databaseTable = 'core_member_recognize';
public static ?string $databaseTable = 'core_member_recognize';
/**
* @brief [ActiveRecord] Database Prefix
*/
public static $databasePrefix = 'r_';
public static string $databasePrefix = 'r_';
/**
* @brief Multiton Store
*/
protected static $multitons = array();
protected static array $multitons = array();
/**
* Get member object
*
* @return \IPS\Member
* @return Member
*/
public function get__given_by(): \IPS\Member
public function get__given_by(): Member
{
return \IPS\Member::load( $this->given_by );
return Member::load( $this->given_by );
}
/**
* Load a recognize row from the content item
*
* @param \IPS\Content $content Content item that has been rewarded
* @return \IPS\core\Achievements\Recognize
* @param Content $content Content item that has been rewarded
* @return ActiveRecord
*/
public static function loadFromContent( $content ): \IPS\core\Achievements\Recognize
public static function loadFromContent( Content $content ): ActiveRecord
{
$idField = $content::$databaseColumnId;
/* Let any exceptions bubble up */
return static::constructFromData(
\IPS\Db::i()->select( '*', 'core_member_recognize', [ 'r_content_class=? and r_content_id=?', \get_class( $content ), $content->$idField ] )->first()
Db::i()->select( '*', 'core_member_recognize', [ 'r_content_class=? and r_content_id=?', get_class( $content ), $content->$idField ] )->first()
);
}
/**
* Add a new recognize entry
*
* @param \IPS\Content $content Content item that is being rewarded
* @param \IPS\Member $member Member to award
* @param Content $content Content item that is being rewarded
* @param Member $member Member to award
* @param int $points Number of points to add
* @param \IPS\core\Achievements\Badge|NULL $badge Badge to assign (if any)
* @param Badge|NULL $badge Badge to assign (if any)
* @param string $message Custom message (if any)
* @param \IPS\Member $awardedBy Awarded by
* @param Member $awardedBy Awarded by
* @param bool $showPublicly Show this message to everyone
* @return void
*/
public static function add( $content, \IPS\Member $member, $points, $badge, $message, \IPS\Member $awardedBy, $showPublicly=FALSE )
public static function add( Content $content, Member $member, int $points, ?Badge $badge, string $message, Member $awardedBy, bool $showPublicly=FALSE ) : void
{
$idField = $content::$databaseColumnId;
/* Add to database */
$recognize = new static;
$recognize->member_id = $member->member_id;
$recognize->content_class = \get_class( $content );
$recognize->content_class = get_class( $content );
$recognize->content_id = $content->$idField;
$recognize->added = time();
$recognize->points = $points;
@@ -102,7 +117,7 @@ class _Recognize extends \IPS\Patterns\ActiveRecord
$member->awardPoints( $points, 0, [], ['subject'], $recognize->id );
}
$notification = new \IPS\Notification( \IPS\Application::load( 'core' ), 'new_recognize', $member, [ $member, $recognize ], [ $recognize->id ] );
$notification = new Notification( Application::load( 'core' ), 'new_recognize', $member, [ $member, $recognize ], [ $recognize->id ] );
$notification->recipients->attach( $member );
$notification->send();
}
@@ -110,9 +125,9 @@ class _Recognize extends \IPS\Patterns\ActiveRecord
/**
* Return the content object
*
* @return \IPS\Content
* @return Content
*/
public function content()
public function content(): Content
{
$class = $this->content_class;
return $class::loadAndCheckPerms( $this->content_id );
@@ -121,35 +136,32 @@ class _Recognize extends \IPS\Patterns\ActiveRecord
/**
* Wrapper to get content.
*
* @return \IPS\Content\Item|NULL
* @return Content|NULL
* @note This simply wraps content()
*/
public function contentWrapper()
public function contentWrapper() : Content|null
{
/* Get container, if valid */
$content = NULL;
try
{
$content = $this->content();
return $this->content();
}
catch( \BadMethodCallException | \OutOfRangeException $e ) { }
catch( BadMethodCallException | OutOfRangeException ) { }
return $content;
return null;
}
/**
* Return a badge, or null
*
* @return NULL|\IPS\core\Achievements\Badge
* @return NULL|Badge
*/
public function badge()
public function badge() : Badge|null
{
try
{
return \IPS\core\Achievements\Badge::load( $this->badge );
return Badge::load( $this->badge );
}
catch( \Exception $e ) { }
catch( OutOfRangeException ) { }
return NULL;
}
@@ -157,15 +169,15 @@ class _Recognize extends \IPS\Patterns\ActiveRecord
/**
* Return a member or NULL if the member no longer exists
*
* @return NULL|\IPS\Member
* @return NULL|Member
*/
public function awardedBy()
public function awardedBy() : Member|null
{
try
{
return \IPS\Member::load( $this->given_by );
return Member::load( $this->given_by );
}
catch( \Exception $e ) { }
catch( OutOfRangeException ) { }
return NULL;
}
@@ -175,28 +187,26 @@ class _Recognize extends \IPS\Patterns\ActiveRecord
*
* @return void
*/
public function delete()
public function delete(): void
{
try
{
$author = \IPS\Member::load( $this->member_id );
if ( $this->points )
{
/* Wade does it this way so I guess there's a reason. And let the reason be love */
\IPS\Db::i()->update( 'core_members', "achievements_points = achievements_points - " . \intval( $this->points ), [ 'member_id=?', $this->member_id ] );
\IPS\Db::i()->delete( 'core_points_log', [ 'recognize=?', $this->id ] );
Db::i()->update( 'core_members', "achievements_points = achievements_points - " . intval( $this->points ), [ 'member_id=?', $this->member_id ] );
Db::i()->delete( 'core_points_log', [ 'recognize=?', $this->id ] );
}
if ( $this->badge )
{
\IPS\Db::i()->delete( 'core_member_badges', [ 'member=? and recognize=?', $this->member_id, $this->id ] );
Db::i()->delete( 'core_member_badges', [ 'member=? and recognize=?', $this->member_id, $this->id ] );
}
/* Remove notifications */
\IPS\Db::i()->delete( 'core_notifications', array( 'item_class=? and notification_key=? and item_id=? and extra=?', 'IPS\Member', 'new_recognize', $this->member_id, '[' . $this->id . ']' ) );
Db::i()->delete( 'core_notifications', array( 'item_class=? and notification_key=? and item_id=? and extra=?', 'IPS\Member', 'new_recognize', $this->member_id, '[' . $this->id . ']' ) );
}
catch( \Exception $e ) {}
catch( Exception ) {}
parent::delete();
}
+137 -109
View File
@@ -11,31 +11,60 @@
namespace IPS\core\Achievements;
/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
use DomainException;
use IPS\Application;
use IPS\core\Achievements\Actions\AchievementActionAbstract;
use IPS\Data\Store;
use IPS\DateTime;
use IPS\Db;
use IPS\Dispatcher;
use IPS\File;
use IPS\Helpers\Form;
use IPS\Helpers\Form\Custom;
use IPS\Helpers\Form\Select;
use IPS\Helpers\Form\Translatable;
use IPS\Http\Url;
use IPS\Lang;
use IPS\Member;
use IPS\Node\Model;
use IPS\Request;
use IPS\Task;
use IPS\Theme;
use OutOfRangeException;
use XMLReader;
use function count;
use function defined;
use function get_class;
use function intval;
use function is_array;
use function is_numeric;
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
header( ( $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.0' ) . ' 403 Forbidden' );
exit;
}
/**
* Achievements Rule Model
*/
class _Rule extends \IPS\Node\Model
class Rule extends Model
{
/**
* @brief Database Table
*/
public static $databaseTable = 'core_achievements_rules';
public static ?string $databaseTable = 'core_achievements_rules';
/**
* @brief Multiton Store
*/
protected static $multitons;
protected static array $multitons;
/**
* @brief [Node] Node Title
*/
public static $nodeTitle = 'achievements_rules';
public static string $nodeTitle = 'achievements_rules';
/**
* @brief [Node] ACP Restrictions
@@ -53,7 +82,7 @@ class _Rule extends \IPS\Node\Model
'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(
protected static ?array $restrictions = array(
'app' => 'core',
'module' => 'achievements',
'prefix' => 'rules_',
@@ -63,7 +92,7 @@ class _Rule extends \IPS\Node\Model
* @brief [ActiveRecord] Caches
* @note Defined cache keys will be cleared automatically as needed
*/
protected $caches = ['achievementRules'];
protected array $caches = ['achievementRules'];
/**
* [ActiveRecord] Get cached rules
@@ -72,7 +101,7 @@ class _Rule extends \IPS\Node\Model
*/
public static function getStore(): array
{
if ( !isset( \IPS\Data\Store::i()->achievementRules ) )
if ( !isset( Store::i()->achievementRules ) )
{
$v = [];
foreach ( static::roots() as $rule )
@@ -90,21 +119,21 @@ class _Rule extends \IPS\Node\Model
'enabled' => $rule->enabled
];
}
\IPS\Data\Store::i()->achievementRules = $v;
Store::i()->achievementRules = $v;
}
return \IPS\Data\Store::i()->achievementRules;
return Store::i()->achievementRules;
}
/**
* Get the extension
*
* @return \IPS\core\Achievements\Actions\AbstractAchievementAction
* @return AchievementActionAbstract
*/
public function extension(): \IPS\core\Achievements\Actions\AbstractAchievementAction
public function extension(): AchievementActionAbstract
{
$exploded = explode( '_', $this->action );
return \IPS\Application::load( $exploded[0] )->extensions( 'core', 'AchievementAction' )[ $exploded[1] ];
return Application::load( $exploded[0] )->extensions( 'core', 'AchievementAction' )[ $exploded[1] ];
}
/**
@@ -112,9 +141,9 @@ class _Rule extends \IPS\Node\Model
*
* @return array|NULL
*/
protected function get_filters()
protected function get_filters() : ?array
{
if ( isset( $this->_data['filters'] ) and \is_array( $this->_data['filters'] ) )
if ( isset( $this->_data['filters'] ) and is_array( $this->_data['filters'] ) )
{
return $this->_data['filters'];
}
@@ -125,31 +154,29 @@ class _Rule extends \IPS\Node\Model
/**
* [Node] Add/Edit Form
*
* @param \IPS\Helpers\Form $form The form
* @param Form $form The form
* @return void
*/
public function form( &$form )
public function form( Form &$form ) : void
{
$form->_activeFilters = [];
$options = [];
$toggles = [];
$extraElements = [];
foreach ( \IPS\Application::allExtensions( 'core', 'AchievementAction' ) as $achievementAction )
foreach ( Application::allExtensions( 'core', 'AchievementAction' ) as $achievementAction )
{
if ( ! $achievementAction->canUse() )
{
continue;
}
$exploded = explode( '\\', \get_class( $achievementAction ) );
$exploded = explode( '\\', get_class( $achievementAction ) );
$options[ "{$exploded[1]}_{$exploded[5]}" ] = "AchievementAction__{$exploded[5]}";
$toggles[ "{$exploded[1]}_{$exploded[5]}" ] = [ "{$exploded[1]}_{$exploded[5]}_award_subject" ];
$toggles[ "{$exploded[1]}_{$exploded[5]}" ][] = "{$exploded[1]}_{$exploded[5]}_award_subject_badge";
foreach ( $achievementAction->filters( $this->filters, \IPS\Http\Url::internal( $this->id ? "app=core&module=achievements&controller=rules&do=form&id={$this->id}" : 'app=core&module=achievements&controller=rules&do=form' ) ) as $filterKey => $filterElement )
foreach ($achievementAction->filters( $this->filters, Url::internal( $this->id ? "app=core&module=achievements&controller=rules&do=form&id={$this->id}" : 'app=core&module=achievements&controller=rules&do=form' ) ) as $filterKey => $filterElement )
{
if ( $this->filters and array_key_exists( $filterKey, $this->filters ) )
if ( is_array( $this->filters ) and array_key_exists( $filterKey, $this->filters ) )
{
$form->_activeFilters[] = $filterElement->name;
}
@@ -162,34 +189,34 @@ class _Rule extends \IPS\Node\Model
}
$awardTo = $achievementAction->awardOptions( $this->filters );
$awardSubjectField = new \IPS\Helpers\Form\Custom( "{$exploded[1]}_{$exploded[5]}_award_subject", [ 'points' => $this->points_subject, 'badge' => $this->badge_subject ], FALSE, [
$awardSubjectField = new Custom( "{$exploded[1]}_{$exploded[5]}_award_subject", [ 'points' => $this->points_subject, 'badge' => $this->badge_subject ], FALSE, [
'getHtml' => function( $field ) {
return \IPS\Theme::i()->getTemplate('achievements')->awardField( $field->name, $field->value );
return Theme::i()->getTemplate('achievements')->awardField( $field->name, $field->value );
}
], NULL, NULL, NULL, "{$exploded[1]}_{$exploded[5]}_award_subject" );
if ( isset( $awardTo['subject'] ) )
{
$awardSubjectField->label = \IPS\Member::loggedIn()->language()->addToStack( $awardTo['subject'] );
$awardSubjectField->label = Member::loggedIn()->language()->addToStack( $awardTo['subject'] );
}
$extraElements[] = $awardSubjectField;
$extraElements[] = new \IPS\Helpers\Form\Translatable( "{$exploded[1]}_{$exploded[5]}_award_subject_badge", NULL, NULL, [ 'app' => 'core', 'key' => ( $this->id ) ? "core_award_subject_badge_" . $this->id : NULL ], NULL, NULL, NULL, "{$exploded[1]}_{$exploded[5]}_award_subject_badge" );
$extraElements[] = new Translatable( "{$exploded[1]}_{$exploded[5]}_award_subject_badge", NULL, NULL, [ 'app' => 'core', 'key' => ( $this->id ) ? "core_award_subject_badge_" . $this->id : NULL ], NULL, NULL, NULL, "{$exploded[1]}_{$exploded[5]}_award_subject_badge" );
if ( isset( $awardTo['other'] ) )
{
$awardOtherField = new \IPS\Helpers\Form\Custom( "{$exploded[1]}_{$exploded[5]}_award_other", [ 'points' => $this->points_other, 'badge' => $this->badge_other ], FALSE, [
$awardOtherField = new Custom( "{$exploded[1]}_{$exploded[5]}_award_other", [ 'points' => $this->points_other, 'badge' => $this->badge_other ], FALSE, [
'getHtml' => function( $field ) {
return \IPS\Theme::i()->getTemplate('achievements')->awardField( $field->name, $field->value );
return Theme::i()->getTemplate('achievements')->awardField( $field->name, $field->value );
}
], NULL, NULL, NULL, "{$exploded[1]}_{$exploded[5]}_award_other" );
$awardOtherField->label = \IPS\Member::loggedIn()->language()->addToStack( $awardTo['other'] );
$awardOtherField->label = Member::loggedIn()->language()->addToStack( $awardTo['other'] );
$extraElements[] = $awardOtherField;
$extraElements[] = new \IPS\Helpers\Form\Translatable( "{$exploded[1]}_{$exploded[5]}_award_other_badge", NULL, NULL, [ 'app' => 'core', 'key' => ( $this->id ) ? "core_award_other_badge_" . $this->id : NULL ], NULL, NULL, NULL, "{$exploded[1]}_{$exploded[5]}_award_other_badge" );
$extraElements[] = new Translatable( "{$exploded[1]}_{$exploded[5]}_award_other_badge", NULL, NULL, [ 'app' => 'core', 'key' => ( $this->id ) ? "core_award_other_badge_" . $this->id : NULL ], NULL, NULL, NULL, "{$exploded[1]}_{$exploded[5]}_award_other_badge" );
$toggles[ "{$exploded[1]}_{$exploded[5]}" ][] = "{$exploded[1]}_{$exploded[5]}_award_other";
$toggles[ "{$exploded[1]}_{$exploded[5]}" ][] = "{$exploded[1]}_{$exploded[5]}_award_other_badge";
}
}
$form->add( new \IPS\Helpers\Form\Select( 'achievement_rule_action', $this->action, TRUE, [ 'options' => $options, 'toggles' => $toggles, 'sort' => TRUE ] ) );
$form->add( new Select( 'achievement_rule_action', $this->action, TRUE, [ 'options' => $options, 'toggles' => $toggles, 'sort' => TRUE ] ) );
foreach ( $extraElements as $element )
{
@@ -203,22 +230,22 @@ class _Rule extends \IPS\Node\Model
* @param array $values Values from the form
* @return array
*/
public function formatFormValues( $values )
public function formatFormValues( array $values ): array
{
if ( !$this->id )
{
$this->action = '';
$this->filters = NULL;
$this->filters = null;
$this->points_other = 0;
$this->points_subject = 0;
$this->save();
}
$exploded = explode( '_', $values['achievement_rule_action'] );
$extension = \IPS\Application::load( $exploded[0] )->extensions( 'core', 'AchievementAction' )[ $exploded[1] ];
$extension = Application::load( $exploded[0] )->extensions( 'core', 'AchievementAction' )[ $exploded[1] ];
$filterValues = [];
foreach ( \IPS\Request::i()->activeFilters ?: [] as $k => $v )
foreach ( Request::i()->activeFilters ?: [] as $k => $v )
{
$filterValues[ $k ] = $values[ $k ];
}
@@ -230,39 +257,37 @@ class _Rule extends \IPS\Node\Model
{
if ( $values[$values['achievement_rule_action'] . '_award_' . $type]['badge'] )
{
\IPS\Lang::saveCustom( 'core', "core_award_" . $type . "_badge_{$this->id}", $values[$values['achievement_rule_action'] . '_award_' . $type . '_badge'] );
Lang::saveCustom( 'core', "core_award_" . $type . "_badge_{$this->id}", $values[$values['achievement_rule_action'] . '_award_' . $type . '_badge'] );
}
else
{
\IPS\Lang::deleteCustom( 'core', "core_award_" . $type . "_badge_{$this->id}" );
Lang::deleteCustom( 'core', "core_award_" . $type . "_badge_{$this->id}" );
}
unset( $values[$values['achievement_rule_action'] . '_award_' . $type . '_badge'] );
}
}
$return = [
return [
'action' => $values['achievement_rule_action'],
'filters' => $filters ? json_encode( $filters ) : NULL,
'milestone' => ( isset( $filters['milestone'] ) and \is_numeric( $filters['milestone'] ) ) ? $filters['milestone'] : NULL,
'points_subject'=> \intval( $values[ $values['achievement_rule_action'] . '_award_subject' ]['points'] ),
'badge_subject' => $values[ $values['achievement_rule_action'] . '_award_subject' ]['badge'] ? \intval( $values[ $values['achievement_rule_action'] . '_award_subject' ]['badge'] ): NULL,
'points_other' => \intval( isset( $values[ $values['achievement_rule_action'] . '_award_other' ] ) ? $values[ $values['achievement_rule_action'] . '_award_other' ]['points'] : 0 ),
'badge_other' => isset( $values[ $values['achievement_rule_action'] . '_award_other' ] ) ? ( $values[ $values['achievement_rule_action'] . '_award_other' ]['badge'] ? \intval( $values[ $values['achievement_rule_action'] . '_award_other' ]['badge'] ) : NULL ) : NULL,
'milestone' => ( isset( $filters['milestone'] ) and is_numeric( $filters['milestone'] ) ) ? $filters['milestone'] : NULL,
'points_subject'=> intval( $values[ $values['achievement_rule_action'] . '_award_subject' ]['points'] ),
'badge_subject' => $values[ $values['achievement_rule_action'] . '_award_subject' ]['badge'] ? intval( $values[ $values['achievement_rule_action'] . '_award_subject' ]['badge'] ): NULL,
'points_other' => intval( isset( $values[ $values['achievement_rule_action'] . '_award_other' ] ) ? $values[ $values['achievement_rule_action'] . '_award_other' ]['points'] : 0 ),
'badge_other' => isset( $values[ $values['achievement_rule_action'] . '_award_other' ] ) ? ( $values[ $values['achievement_rule_action'] . '_award_other' ]['badge'] ? intval( $values[ $values['achievement_rule_action'] . '_award_other' ]['badge'] ) : NULL ) : NULL,
];
return $return;
}
/**
* [Node] Get buttons to display in tree
* Example code explains return value
*
* @param string $url Base URL
* @param bool $subnode Is this a subnode?
* @return array
* @param Url $url Base URL
* @param bool $subnode Is this a subnode?
* @return array
*/
public function getButtons( $url, $subnode=FALSE )
public function getButtons( Url $url, bool $subnode=FALSE ): array
{
$buttons = parent::getButtons( $url, $subnode );
@@ -270,7 +295,7 @@ class _Rule extends \IPS\Node\Model
$buttons['toggleEnabled'] = array(
'icon' => ( $this->enabled ) ? 'pause-circle' : 'play-circle',
'title' => ( $this->enabled ) ? 'acp_disable_rule' : 'acp_enable_rule',
'link' => \IPS\Http\Url::internal( "app=core&module=achievements&controller=rules&do=toggleEnabled&id={$this->_id}&enable=" . ( $this->enabled ? 0 : 1 ) )->csrf(),
'link' => Url::internal( "app=core&module=achievements&controller=rules&do=toggleEnabled&id={$this->_id}&enable=" . ( $this->enabled ? 0 : 1 ) )->csrf(),
'data' => [ 'data-confirm' => 'true' ]
);
@@ -280,17 +305,17 @@ class _Rule extends \IPS\Node\Model
/**
* Get badge for subject
*
* @return \IPS\core\Achievements\Badge|NULL
* @return Badge|NULL
*/
public function badgeSubject(): ?\IPS\core\Achievements\Badge
public function badgeSubject(): ?Badge
{
if ( $this->badge_subject )
{
try
{
return \IPS\core\Achievements\Badge::load( $this->badge_subject );
return Badge::load( $this->badge_subject );
}
catch( \OutOfRangeException $e ) { }
catch( OutOfRangeException $e ) { }
}
return NULL;
}
@@ -298,17 +323,17 @@ class _Rule extends \IPS\Node\Model
/**
* Get badge for others
*
* @return \IPS\core\Achievements\Badge|NULL
* @return Badge|NULL
*/
public function badgeOther(): ?\IPS\core\Achievements\Badge
public function badgeOther(): ?Badge
{
if ( $this->badge_other )
{
try
{
return \IPS\core\Achievements\Badge::load( $this->badge_other );
return Badge::load( $this->badge_other );
}
catch( \OutOfRangeException $e ) { }
catch( OutOfRangeException $e ) { }
}
return NULL;
}
@@ -316,16 +341,16 @@ class _Rule extends \IPS\Node\Model
/**
* Delete Record
*
* @return void
* @return void
*/
public function delete()
public function delete(): void
{
parent::delete();
\IPS\Db::i()->delete( 'core_achievements_log_milestones', array( 'milestone_rule=?', $this->id ) );
Db::i()->delete( 'core_achievements_log_milestones', array( 'milestone_rule=?', $this->id ) );
\IPS\Lang::deleteCustom( 'core', "core_award_subject_badge_{$this->id}" );
\IPS\Lang::deleteCustom( 'core', "core_award_other_badge_{$this->id}" );
Lang::deleteCustom( 'core', "core_award_subject_badge_{$this->id}" );
Lang::deleteCustom( 'core', "core_award_other_badge_{$this->id}" );
}
/**
@@ -345,7 +370,7 @@ class _Rule extends \IPS\Node\Model
foreach ( array( 'subject' => "core_award_subject_badge_{$this->id}", 'other' => "core_award_other_badge_{$this->id}") as $fieldKey => $langKey ) {
$oldLangKey = str_replace( $this->id, $oldId, $langKey );
\IPS\Lang::saveCustom( 'core', $langKey, iterator_to_array(\IPS\Db::i()->select( 'word_custom, lang_id', 'core_sys_lang_words', array('word_key=?', $oldLangKey ) )->setKeyField('lang_id')->setValueField('word_custom' ) ) );
Lang::saveCustom( 'core', $langKey, iterator_to_array(Db::i()->select( 'word_custom, lang_id', 'core_sys_lang_words', array('word_key=?', $oldLangKey ) )->setKeyField('lang_id')->setValueField('word_custom' ) ) );
}
}
@@ -358,7 +383,7 @@ class _Rule extends \IPS\Node\Model
{
$return = [ 'count' => 0, 'processed' => 0 ];
$rebuilding = FALSE;
foreach( \IPS\Db::i()->select( '*', 'core_queue', [ [ '`key`=?', 'RebuildAchievements' ] ] ) as $rebuild )
foreach( Db::i()->select( '*', 'core_queue', [ [ '`key`=?', 'RebuildAchievements' ] ] ) as $rebuild )
{
$data = json_decode( $rebuild['data'], TRUE );
@@ -378,33 +403,30 @@ class _Rule extends \IPS\Node\Model
/**
* Rebuild all cheeeeeevs
*
* @param \IPS\DateTime|null $time
* @param DateTime|null $time
*/
public static function rebuildAllAchievements( ?\IPS\DateTime $time )
public static function rebuildAllAchievements( ?DateTime $time ) : void
{
\IPS\Db::i()->delete( 'core_achievements_log' );
\IPS\Db::i()->delete( 'core_achievements_log_milestones' );
\IPS\Db::i()->delete( 'core_points_log' );
\IPS\Db::i()->delete( 'core_member_badges', [ 'rule > 0' ] ); /* 0 is a manually awarded badge. Don't hate the coder, hate the player */
\IPS\Db::i()->update( 'core_members', [ 'achievements_points' => 0 ] );
Db::i()->delete( 'core_achievements_log' );
Db::i()->delete( 'core_achievements_log_milestones' );
Db::i()->delete( 'core_points_log' );
Db::i()->delete( 'core_member_badges', [ 'rule > 0' ] ); /* 0 is a manually awarded badge. Don't hate the coder, hate the player */
Db::i()->update( 'core_members', [ 'achievements_points' => 0 ] );
/* Remove all previous tasks */
\IPS\Db::i()->delete( 'core_queue', [ '`key`=?', 'RebuildAchievements' ] );
Db::i()->delete( 'core_queue', [ '`key`=?', 'RebuildAchievements' ] );
foreach( \IPS\Application::applications() as $app )
foreach( Application::applications() as $app )
{
foreach ( \IPS\Application::load( $app->directory )->extensions( 'core', 'AchievementAction' ) as $extension )
foreach ( Application::load( $app->directory )->extensions( 'core', 'AchievementAction' ) as $extension )
{
if ( method_exists( $extension, 'rebuildData' ) )
{
$bits = explode( '\\', \get_class( $extension ) );
$className = array_pop( $bits );
\IPS\Task::queue( 'core', 'RebuildAchievements', [
'extension' => $app->directory . '_' . $className,
'data' => $extension::rebuildData(),
'time' => ( $time ) ? $time->getTimestamp() : NULL,
], 4 );
}
$bits = explode( '\\', get_class( $extension ) );
$className = array_pop( $bits );
Task::queue( 'core', 'RebuildAchievements', [
'extension' => $app->directory . '_' . $className,
'data' => $extension::rebuildData(),
'time' => ( $time ) ? $time->getTimestamp() : NULL,
], 4 );
}
}
}
@@ -417,20 +439,20 @@ class _Rule extends \IPS\Node\Model
*
* @return void
*/
public static function importXml( $file, $deleteExisting=FALSE )
public static function importXml( string $file, bool $deleteExisting=FALSE ) : void
{
/* Open XML file */
$xml = \IPS\Xml\XMLReader::safeOpen( $file );
if ( ! @$xml->read() )
{
throw new \DomainException( 'xml_upload_invalid' );
throw new DomainException( 'xml_upload_invalid' );
}
/* Did we want to wipe first? */
if ( $deleteExisting )
{
foreach( \IPS\core\Achievements\Rule::getStore() as $action => $rules )
foreach(Rule::getStore() as $action => $rules )
{
foreach( $rules as $ruleId => $rule )
{
@@ -438,7 +460,7 @@ class _Rule extends \IPS\Node\Model
{
static::load( $ruleId )->delete();
}
catch( \OutOfRangeException $e ){}
catch( OutOfRangeException $e ){}
}
}
@@ -450,7 +472,7 @@ class _Rule extends \IPS\Node\Model
/* Rules: Start looping through each row */
while ( $xml->read() )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
if( $xml->nodeType != XMLReader::ELEMENT )
{
continue;
}
@@ -474,7 +496,7 @@ class _Rule extends \IPS\Node\Model
while ( $xml->read() and $xml->name != 'rule' )
{
if ( $xml->nodeType != \XMLReader::ELEMENT )
if ( $xml->nodeType != XMLReader::ELEMENT )
{
continue;
}
@@ -510,23 +532,23 @@ class _Rule extends \IPS\Node\Model
}
}
$insertId = \IPS\Db::i()->insert( 'core_achievements_rules', $insert );
$insertId = Db::i()->insert( 'core_achievements_rules', $insert );
$allBadges[ $insertId ] = $badgesToUpdate;
if ( ! empty( $awardSubject ) )
{
\IPS\Lang::saveCustom( 'core', "core_award_subject_badge_{$insertId}", $awardSubject );
Lang::saveCustom( 'core', "core_award_subject_badge_{$insertId}", $awardSubject );
}
if ( ! empty( $awardOther ) )
{
\IPS\Lang::saveCustom( 'core', "core_award_other_badge_{$insertId}", $awardOther );
Lang::saveCustom( 'core', "core_award_other_badge_{$insertId}", $awardOther );
}
}
/* Badges: Start looping through each row */
else if ( $xml->name == 'badge' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
if( $xml->nodeType != XMLReader::ELEMENT )
{
continue;
}
@@ -537,7 +559,7 @@ class _Rule extends \IPS\Node\Model
while ( $xml->read() and $xml->name != 'badge' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
if( $xml->nodeType != XMLReader::ELEMENT )
{
continue;
}
@@ -564,22 +586,22 @@ class _Rule extends \IPS\Node\Model
if ( ! empty( $insert['icon_name'] ) and ! empty( $insert['icon_data'] ) )
{
$insert['image'] = (string) \IPS\File::create( 'core_Badges', $insert['icon_name'], $insert['icon_data'], NULL, TRUE, NULL, FALSE );
$insert['image'] = (string) File::create( 'core_Badges', $insert['icon_name'], $insert['icon_data'], NULL, TRUE, NULL, FALSE );
unset( $insert['icon_name'] );
unset( $insert['icon_data'] );
}
$insertId = \IPS\Db::i()->insert( 'core_badges', $insert );
$insertId = Db::i()->insert( 'core_badges', $insert );
$badgeMap[ $id ] = $insertId;
if ( ! empty( $title ) )
{
\IPS\Lang::saveCustom( 'core', "core_badges_{$insertId}", $title );
Lang::saveCustom( 'core', "core_badges_{$insertId}", $title );
}
}
}
if ( \count( $allBadges ) )
if ( count( $allBadges ) )
{
foreach( $allBadges as $ruleId => $data )
{
@@ -592,14 +614,14 @@ class _Rule extends \IPS\Node\Model
}
}
if ( \count( $update ) )
if ( count( $update ) )
{
\IPS\Db::i()->update( 'core_achievements_rules', $update, ['`id`=?', $ruleId ] );
Db::i()->update( 'core_achievements_rules', $update, ['`id`=?', $ruleId ] );
}
}
}
unset( \IPS\Data\Store::i()->achievementRules );
unset( Store::i()->achievementRules );
}
/**
@@ -610,8 +632,14 @@ class _Rule extends \IPS\Node\Model
*/
public static function canImport( string $value ) : bool
{
/* If we are in the middle of an installation, we can always import */
if( Dispatcher::hasInstance() and Dispatcher::i()->controllerLocation == 'setup' )
{
return true;
}
$appKey = explode( '_', $value );
return \IPS\Application::appIsEnabled( $appKey[0] );
return Application::appIsEnabled( $appKey[0] );
}
/**
@@ -622,7 +650,7 @@ class _Rule extends \IPS\Node\Model
*/
public static function ruleHasMilestone( ?array $filters ): bool
{
if ( \is_array( $filters ) and \count( $filters ) )
if ( is_array( $filters ) and count( $filters ) )
{
foreach( $filters as $key => $value )
{
@@ -641,9 +669,9 @@ class _Rule extends \IPS\Node\Model
*
* @return string|null
*/
public function titleForLog()
public function titleForLog(): ?string
{
$exploded = explode( '_', $this->action );
return \IPS\Lang::load( \IPS\Lang::defaultLanguage() )->get( 'AchievementAction__' . $exploded[1] . '_title' ) . " #" . $this->id;
return Lang::load( Lang::defaultLanguage() )->get( 'AchievementAction__' . $exploded[1] . '_title' ) . " #" . $this->id;
}
}