Version 4.6.0

This commit is contained in:
Neo committed 2025-12-19 05:55:31 -08:00
1 parent f79dcf067a
commit 517a5e1f70
2036 files changed
+110041 -26162

No files matched your search

@@ -0,0 +1,126 @@
<?php
/**
* @brief Achievements Rule Model
* @author <a href='https://www.invisioncommunity.com'>Invision Power Services, Inc.</a>
* @copyright (c) Invision Power Services, Inc.
* @license https://www.invisioncommunity.com/legal/standards/
* @package Invision Community
* @since 24 Feb 2021
*/
namespace IPS\core\Achievements\Actions;
/* 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 class for AchievementAction extensions
*/
abstract class _AbstractAchievementAction
{
/**
* Can use this rule?
*
* @return boolean
*/
public function canUse(): bool
{
$exploded = explode( '\\', \get_called_class() );
return \IPS\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
* @return array
*/
public function filters( ?array $filters, \IPS\Http\Url $url ): array
{
return [];
}
/**
* Format filter form values
*
* @param array $values The values from the form
* @return array
*/
public function formatFilterValues( array $values ): array
{
return [];
}
/**
* Work out if the filters applies for a given action
*
* Important note for milestones: consider the context. This method is called by \IPS\Member::achievementAction(). If your code
* 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 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
{
return TRUE;
}
/**
* Get the labels for the people this action might give awards to
*
* @return array
*/
public function awardOptions(): array
{
return [
'subject' => '',
];
}
/**
* Get the "other" people we need to award =stuff to
*
* @param mixed $extra Any additional information about what is happening (e.g. if a post is being made: the post object)
* @return array
*/
public function awardOther( $extra = NULL ): array
{
return [];
}
/**
* 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 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;
/**
* Return a description for this action to show in the log
*
* @param string $identifier The identifier as returned by identifier()
* @param array $actor If the member was the "subject", "other", or both
* @return string
*/
abstract public function logRow( string $identifier, array $actor ): string;
/**
* Get "description" for rule
*
* @param \IPS\core\Achievements\Rule $rule The rule
* @return string|null
*/
abstract public function ruleDescription( \IPS\core\Achievements\Rule $rule ): ?string;
}
@@ -0,0 +1,364 @@
<?php
/**
* @brief Abstract Achievement Action Extension for content-related things
* @author <a href='https://www.invisioncommunity.com'>Invision Power Services, Inc.</a>
* @copyright (c) Invision Power Services, Inc.
* @license https://www.invisioncommunity.com/legal/standards/
* @since 24 Feb 2021
*/
namespace IPS\core\Achievements\Actions;
/* 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;
}
/**
* Abstract Achievement Action Extension for content-related things
*/
abstract class _AbstractContentAchievementAction extends AbstractAchievementAction
{
protected static $includeItems = TRUE;
protected static $includeComments = TRUE;
protected static $includeReviews = TRUE;
/**
* 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
* @return array
*/
public function filters( ?array $filters, \IPS\Http\Url $url ): array
{
$classKey = explode( '\\', \get_called_class() )[5];
$contentTypeOptions = [];
$contentTypeToggles = [];
$_return = [];
$defaultApp = NULL;
foreach( \IPS\Application::applications() as $directory => $application )
{
if( $application->default )
{
$defaultApp = $directory;
break;
}
}
foreach ( \IPS\Application::allExtensions( 'core', 'ContentRouter', FALSE, $defaultApp ) as $extension )
{
foreach ( $extension->classes as $class )
{
if ( isset( $class::$databaseColumnMap['author'] ) )
{
$nodeFilterKey = NULL;
$haveMatchingClass = FALSE;
if ( isset( $class::$containerNodeClass ) )
{
$nodeFilterKey = 'achievement_subfilter_' . $classKey . '_type_' . str_replace( '\\', '-', $class );
$contentTypeToggles[ $class ][] = $nodeFilterKey;
}
if ( static::$includeItems )
{
$contentTypeOptions[ $class ] = $class::$title;
$contentTypeToggles[ $class ] = $nodeFilterKey ? [ $nodeFilterKey ] : [];
$haveMatchingClass = TRUE;
}
if ( static::$includeComments and isset( $class::$commentClass ) )
{
$commentClass = $class::$commentClass;
$contentTypeOptions[ $commentClass ] = $commentClass::$title;
$contentTypeToggles[ $commentClass ] = $nodeFilterKey ? [ $nodeFilterKey ] : [];
$haveMatchingClass = TRUE;
}
if ( static::$includeReviews and isset( $class::$reviewClass ) )
{
$reviewClass = $class::$reviewClass;
$contentTypeOptions[ $reviewClass ] = $reviewClass::$title;
$contentTypeToggles[ $reviewClass ] = $nodeFilterKey ? [ $nodeFilterKey ] : [];
$haveMatchingClass = TRUE;
}
if ( $nodeFilterKey and $haveMatchingClass )
{
try
{
$nodeTitle = \IPS\Member::loggedIn()->language()->get( ($class::$containerNodeClass)::$nodeTitle . '_sg_lc' );
}
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, [
'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 )
] ] ) );
$nodeFilter->label = \IPS\Member::loggedIn()->language()->addToStack( 'achievement_filter_NewContentItem_node', FALSE, [ 'sprintf' => [ \IPS\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');
$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');
$return = [ 'type' => $typeFilter ];
foreach ( $_return as $k => $v )
{
$return[ $k ] = $v;
}
$return['milestone'] = $nthFilter;
return $return;
}
/**
* Format filter form values
*
* @param array $values The values from the form
* @return array
*/
public function formatFilterValues( array $values ): array
{
$classKey = explode( '\\', \get_called_class() )[5];
$return = [];
if ( isset( $values['achievement_filter_' . $classKey . '_type'] ) )
{
$return['type'] = $values['achievement_filter_' . $classKey . '_type'];
$itemClass = $return['type'];
if ( \in_array( 'IPS\Content\Comment', class_parents( $return['type'] ) ) )
{
$itemClass = $return['type']::$itemClass;
}
if ( isset( $values[ 'achievement_subfilter_' . $classKey . '_type_' . str_replace( '\\', '-', $itemClass ) ] ) )
{
$return[ 'nodes_' . str_replace( '\\', '-', $itemClass ) ] = array_keys( $values[ 'achievement_subfilter_' . $classKey . '_type_' . str_replace( '\\', '-', $itemClass ) ] );
}
}
if ( isset( $values['achievement_filter_' . $classKey . '_nth'] ) )
{
$return['milestone'] = $values['achievement_filter_' . $classKey . '_nth'];
}
return $return;
}
/**
* Work out if the filters applies for a given action
*
* Important note for milestones: consider the context. This method is called by \IPS\Member::achievementAction(). If your code
* 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 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
{
if ( isset( $filters['type'] ) )
{
if ( !( $extra instanceof $filters['type'] ) )
{
return FALSE;
}
$item = $extra;
if ( \in_array( 'IPS\Content\Comment', class_parents( $filters['type'] ) ) )
{
$item = $extra->item();
}
if ( isset( $filters[ 'nodes_' . str_replace( '\\', '-', \get_class( $item ) ) ] ) )
{
if ( !\in_array( $item->container()->_id, $filters[ 'nodes_' . str_replace( '\\', '-', \get_class( $item ) ) ] ) )
{
return FALSE;
}
}
}
return TRUE;
}
/**
* 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 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
{
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
* @return string|NULL
*/
protected function _nodeFilterDescription( \IPS\core\Achievements\Rule $rule ): ?string
{
if ( isset( $rule->filters['type'] ) )
{
$itemClass = $rule->filters['type'];
if ( \in_array( 'IPS\Content\Comment', class_parents( $rule->filters['type'] ) ) )
{
$itemClass = $itemClass::$itemClass;
}
if ( isset( $rule->filters[ 'nodes_' . str_replace( '\\', '-', $itemClass ) ] ) )
{
$nodeClass = $itemClass::$containerNodeClass;
$nodeNames = [];
foreach ( $rule->filters[ 'nodes_' . str_replace( '\\', '-', $itemClass ) ] as $id )
{
try
{
$nodeNames[] = $nodeClass::load( $id )->_title;
}
catch ( \OutOfRangeException $e ) {}
}
if ( $nodeNames )
{
return \IPS\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 )
] ] ),
\count( $nodeNames ) === 1 ? NULL : $nodeNames
)
],
] );
}
}
}
return NULL;
}
/**
* Get rebuild data
*
* @return array
*/
static public function rebuildData()
{
$return = [];
foreach ( \IPS\Application::allExtensions( 'core', 'ContentRouter', FALSE ) as $extension )
{
foreach ( $extension->classes as $class )
{
if ( isset( $class::$databaseColumnMap['author'] ) )
{
if ( static::$includeItems )
{
$return[] = [
'table' => $class::$databaseTable,
'pkey' => $class::$databasePrefix . $class::$databaseColumnId,
'date' => ( isset( $class::$databaseColumnMap['date'] ) ) ? $class::$databasePrefix . $class::$databaseColumnMap['date'] : NULL,
'where' => [],
'class' => $class
];
}
if ( static::$includeComments and isset( $class::$commentClass ) )
{
$commentClass = $class::$commentClass;
$return[] = [
'table' => $commentClass::$databaseTable,
'pkey' => $commentClass::$databasePrefix . $commentClass::$databaseColumnId,
'date' => ( isset( $commentClass::$databaseColumnMap['date'] ) ) ? $commentClass::$databasePrefix . $commentClass::$databaseColumnMap['date'] : NULL,
'where' => [],
'class' => $commentClass
];
}
if ( static::$includeReviews and isset( $class::$reviewClass ) )
{
$reviewClass = $class::$reviewClass;
$return[] = [
'table' => $reviewClass::$databaseTable,
'pkey' => $reviewClass::$databasePrefix . $reviewClass::$databaseColumnId,
'date' => ( isset( $reviewClass::$databaseColumnMap['date'] ) ) ? $reviewClass::$databasePrefix . $reviewClass::$databaseColumnMap['date'] : NULL,
'where' => [],
'class' => $reviewClass
];
}
}
}
}
return $return;
}
/**
* Get a where clause to check based on the type/class
*
* @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
* @return array
*/
protected function getWherePerType( $filters, $class, $time=NULL ): array
{
$where = ( $time ? [ [ $class::$databasePrefix . $class::$databaseColumnMap['date'] . ' >= ?', $time->getTimestamp() ] ] : [] );
$itemClass = $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 ) ) )
{
$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 ) ] ) ] ) ];
}
else
{
$where[] = [ \IPS\Db::i()->in( $class::$databasePrefix . $class::$databaseColumnMap['container'], $filters[ 'nodes_' . str_replace( '\\', '-', $class ) ] ) ];
}
}
return $where;
}
/**
* Process the rebuild row
*
* @param array $row Row from database
* @param array $data Data collected when starting rebuild [table, pkey...]
* @return void
*/
public static function rebuildRow( $row, $data )
{
$classCalled = explode( '\\', \get_called_class() );
$class = $data['class'];
$item = $class::constructFromData( $row );
$item->author()->achievementAction( 'core', array_pop( $classCalled ), $item );
}
}
@@ -0,0 +1,200 @@
<?php
/**
* @brief Abstract Achievement Action Extension for node-related things
* @author <a href='https://www.invisioncommunity.com'>Invision Power Services, Inc.</a>
* @copyright (c) Invision Power Services, Inc.
* @license https://www.invisioncommunity.com/legal/standards/
* @since 24 Feb 2021
*/
namespace IPS\core\Achievements\Actions;
/* 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;
}
/**
* Abstract Achievement Action Extension for content-related things
*/
abstract class _AbstractNodeAchievementAction extends AbstractAchievementAction
{
/**
* 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
* @return array
*/
public function filters( ?array $filters, \IPS\Http\Url $url ): array
{
$contentTypeOptions = [];
$contentTypeToggles = [];
$_return = [];
$defaultApp = NULL;
foreach( \IPS\Application::applications() as $directory => $application )
{
if( $application->default )
{
$defaultApp = $directory;
break;
}
}
foreach ( \IPS\Application::allExtensions( 'core', 'ContentRouter', FALSE, $defaultApp ) as $extension )
{
foreach ( $extension->classes as $class )
{
if ( isset( $class::$containerNodeClass ) )
{
$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, [
'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 ] ) ] ] );
$_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');
$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');
$return = [ 'type' => $typeFilter ];
foreach ( $_return as $k => $v )
{
$return[ $k ] = $v;
}
$return['milestone'] = $nthFilter;
return $return;
}
/**
* Format filter form values
*
* @param array $values The values from the form
* @return array
*/
public function formatFilterValues( array $values ): array
{
$return = [];
if ( isset( $values['achievement_filter_Node_type'] ) )
{
$return['type'] = $values['achievement_filter_Node_type'];
$nodeClass = $return['type'];
if ( isset( $values[ 'achievement_subfilter_Node_type_' . str_replace( '\\', '-', $nodeClass ) ] ) )
{
$return[ 'nodes_' . str_replace( '\\', '-', $nodeClass ) ] = array_keys( $values[ 'achievement_subfilter_Node_type_' . str_replace( '\\', '-', $nodeClass ) ] );
}
}
if ( isset( $values['achievement_filter_Node_nth'] ) )
{
$return['milestone'] = $values['achievement_filter_Node_nth'];
}
return $return;
}
/**
* Work out if the filters applies for a given action
*
* Important note for milestones: consider the context. This method is called by \IPS\Member::achievementAction(). If your code
* 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 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
{
if ( isset( $filters['type'] ) )
{
if ( !( $extra instanceof $filters['type'] ) )
{
return FALSE;
}
if ( isset( $filters[ 'nodes_' . str_replace( '\\', '-', \get_class( $extra ) ) ] ) )
{
if ( !\in_array( $extra->_id, $filters[ 'nodes_' . str_replace( '\\', '-', \get_class( $extra ) ) ] ) )
{
return FALSE;
}
}
}
return TRUE;
}
/**
* 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 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
{
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
* @return string|NULL
*/
protected function _nodeFilterDescription( \IPS\core\Achievements\Rule $rule ): ?string
{
if ( isset( $rule->filters['type'] ) )
{
$nodeClass = $rule->filters['type'];
if ( isset( $rule->filters[ 'nodes_' . str_replace( '\\', '-', $nodeClass ) ] ) )
{
$nodeNames = [];
foreach ( $rule->filters[ 'nodes_' . str_replace( '\\', '-', $nodeClass ) ] as $id )
{
try
{
$nodeNames[] = $nodeClass::load( $id )->_title;
}
catch ( \OutOfRangeException $e ) {}
}
if ( $nodeNames )
{
return \IPS\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 ] )
] ] ),
\count( $nodeNames ) === 1 ? NULL : $nodeNames
)
],
] );
}
}
}
return NULL;
}
}
@@ -0,0 +1,447 @@
<?php
/**
* @brief Badge Model (as in, a representation of a badge a member *can* earn, not a badge a particular member *has* earned)
* @author <a href='https://www.invisioncommunity.com'>Invision Power Services, Inc.</a>
* @copyright (c) Invision Power Services, Inc.
* @license https://www.invisioncommunity.com/legal/standards/
* @package Invision Community
* @since 22 Feb 2021
*/
namespace IPS\core\Achievements;
/* 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;
}
/**
* 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
{
/**
* @brief Database Table
*/
public static $databaseTable = 'core_badges';
/**
* @brief Multiton Store
*/
protected static $multitons;
/**
* @brief [Node] Node Title
*/
public static $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_';
/**
* @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');
/**
* @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' => 'achievements',
'prefix' => 'badges_',
);
/**
* 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
*/
public static function constructFromData( $data, $updateMultitonStoreIfExists = TRUE )
{
$obj = parent::constructFromData( $data, $updateMultitonStoreIfExists );
if ( isset( $obj->recognize ) and ! empty( $obj->recognize ) )
{
try
{
$obj->recognize = \IPS\core\Achievements\Recognize::load( $obj->recognize );
}
catch( \Exception $e )
{
/* Problem loading, so reset to 0 */
$obj->recognize = 0;
}
}
if ( isset( $obj->rule ) and ! empty( $obj->rule ) )
{
$obj->awardDescription = $obj->awardDescription( $obj->rule, $obj->actor );
}
return $obj;
}
/**
* @var null|array
*/
static $badgeAwardLangBits = NULL;
/**
* Show the public reason for this badge award
*
* @param int $ruleId
* @param $actor
* @return string|null
*/
public function awardDescription( int $ruleId, $actor ):? string
{
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 )
{
static::$badgeAwardLangBits[ $row['word_key'] ] = $row['word_custom'] ?: $row['word_default'];
}
}
return static::$badgeAwardLangBits['core_award_' . $actor . '_badge_' . $ruleId] ?? NULL;
}
/**
* [Node] Add/Edit Form
*
* @param \IPS\Helpers\Form $form The form
* @return void
*/
public function form( &$form )
{
$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' => FALSE, 'checkImage' => TRUE, 'allowedFileTypes' => array_merge( \IPS\Image::$imageExtensions, ['svg'] ), 'storageExtension' => 'core_Badges', 'allowStockPhotos' => FALSE ), function( $val ) {
if( !$val )
{
throw new \DomainException('achievements_bad_image');
}
/* Good luck with your fancy SVG */
$ext = mb_substr( $val->originalFilename, ( mb_strrpos( $val->originalFilename, '.' ) + 1 ) );
if( $ext !== 'svg' )
{
try
{
$image = \IPS\Image::create( $val->contents() );
}
catch ( \Exception $e )
{
throw new \DomainException( 'achievements_bad_image' );
}
}
} ) );
$form->add( new \IPS\Helpers\Form\YesNo( 'badge_manually_awarded', $this->manually_awarded ) );
}
/**
* [Node] Format form values from add/edit form for save
*
* @param array $values Values from the form
* @return array
*/
public function formatFormValues( $values )
{
if ( !$this->id )
{
$this->save();
}
\IPS\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_' )
{
$values[ mb_substr( $k, 6 ) ] = $v;
}
else
{
$values[ $k ] = $v;
}
}
return $values;
}
/**
* [Node] Get Icon for tree
*
* @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()
{
return \IPS\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
*/
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 );
}
/**
* Is this badge rare?
*
* @return bool
*/
public function isRare(): bool
{
if ( !\IPS\Settings::i()->rare_badge_percent )
{
return FALSE;
}
/* 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()->badgeRarityStats ) )
{
$stats = json_decode( \IPS\Data\Store::i()->badgeRarityStats, true );
if( !isset( $stats['expiration'] ) OR time() > $stats['expiration'] OR !isset( $stats['badgeCount'][ $this->id ] ) )
{
$stats = NULL;
}
}
if( $stats === NULL )
{
$stats = array(
'expiration' => time() + 3600, // Cache for 60 minutes
'memberCount' => \IPS\Db::i()->select( 'COUNT(*)', 'core_members', [ 'completed=?', true ] )->first(),
'badgeCount' => array(),
);
foreach( \IPS\Db::i()->select( 'id', 'core_badges' ) as $badgeId )
{
$stats['badgeCount'][ $badgeId ] = \IPS\Db::i()->select( 'COUNT(*)', 'core_member_badges', [ 'badge=?', $badgeId ] )->first();
}
\IPS\Data\Store::i()->badgeRarityStats = json_encode( $stats );
}
return ( 100 / $stats['memberCount'] * $stats['badgeCount'][ $this->id ] ) < \IPS\Settings::i()->rare_badge_percent;
}
/**
* [ActiveRecord] Duplicate
*
* @return void
*/
public function __clone()
{
if ( $this->skipCloneDuplication === TRUE )
{
return;
}
$oldId = $this->id;
$oldImage = $this->image;
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') ) );
if ( $oldImage )
{
try
{
$image = \IPS\File::get( 'core_Badges', $oldImage );
$newImage = \IPS\File::create( 'core_Badges', $image->originalFilename, $image->contents() );
$this->image = (string) $newImage;
}
catch ( \Exception $e )
{
$this->image = NULL;
}
$this->save();
}
}
/**
* Delete Record
*
* @return void
*/
public function delete()
{
/* 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 ] );
/* Remove the badge from recognize, but leave points */
\IPS\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();
}
catch( \Exception $ex ) { }
}
parent::delete();
\IPS\Db::i()->delete( 'core_member_badges', [ 'badge=?', $this->id ] );
\IPS\Lang::deleteCustom( 'core', "core_badges_{$this->id}" );
}
/**
* Show badges on the front end?
*
* @return bool
*/
public static function show(): bool
{
return !( ( \IPS\Settings::i()->achievements_rebuilding or !\IPS\Settings::i()->achievements_enabled ) );
}
/**
* Fetch assigned (to rules) badge IDs
*
* @return array
*/
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 )
{
if ( $row['badge_subject'] )
{
$assignedBadges[] = $row['badge_subject'];
}
if ( $row['badge_other'] )
{
$assignedBadges[] = $row['badge_other'];
}
}
return $assignedBadges;
}
/**
* Import from Xml
*
* @param string $file The file to import data from
* @param boolean $deleteExisting Remove existing rules first?
*
* @return void
*/
public static function importXml( $file, $deleteExisting=FALSE )
{
/* Open XML file */
$xml = \IPS\Xml\XMLReader::safeOpen( $file );
if ( ! @$xml->read() )
{
throw new \DomainException( 'xml_upload_invalid' );
}
/* Did we want to wipe first? */
if ( $deleteExisting )
{
$assignedBadges = static::getAssignedBadgeIds();
$where = NULL;
if ( \count( $assignedBadges ) )
{
$where = [ \IPS\Db::i()->in( '`id`', $assignedBadges, TRUE ) ];
}
foreach( \IPS\Db::i()->select('*', 'core_badges', $where ) as $row )
{
static::constructFromData( $row )->delete();
}
}
/* Start looping through each row */
while ( $xml->read() and $xml->name == 'badge' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
$insert = [];
$title = NULL;
while ( $xml->read() and $xml->name != 'badge' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
switch( $xml->name )
{
case 'manually_awarded':
$insert[ $xml->name ] = (int) $xml->readString();
break;
case 'title':
$title = $xml->readString();
break;
case 'icon_name':
$insert['icon_name'] = $xml->readString();
break;
case 'icon_data':
$insert['icon_data'] = base64_decode( $xml->readString() );
break;
}
}
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 );
unset( $insert['icon_name'] );
unset( $insert['icon_data'] );
}
$insertId = \IPS\Db::i()->insert( 'core_badges', $insert );
if ( ! empty( $title ) )
{
\IPS\Lang::saveCustom( 'core', "core_badges_{$insertId}", $title );
}
}
}
}
@@ -0,0 +1,438 @@
<?php
/**
* @brief Rank Model
* @author <a href='https://www.invisioncommunity.com'>Invision Power Services, Inc.</a>
* @copyright (c) Invision Power Services, Inc.
* @license https://www.invisioncommunity.com/legal/standards/
* @package Invision Community
* @since 3 Mar 2021
*/
namespace IPS\core\Achievements;
/* 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;
}
/**
* Rank Model
*/
class _Rank extends \IPS\Node\Model
{
/**
* @brief Database Table
*/
public static $databaseTable = 'core_member_ranks';
/**
* @brief [Node] Order Database Column
*/
public static $databaseColumnOrder = 'points';
/**
* @brief [Node] Sortable?
*/
public static $nodeSortable = FALSE;
/**
* @brief Multiton Store
*/
protected static $multitons;
/**
* @brief [Node] Node Title
*/
public static $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_';
/**
* @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' => 'achievements',
'prefix' => 'ranks_',
);
/**
* @brief [ActiveRecord] Caches
* @note Defined cache keys will be cleared automatically as needed
*/
protected $caches = ['achievementRanks'];
/**
* [ActiveRecord] Get cached rules
*
* @return array
*/
public static function getStore(): array
{
if ( !isset( \IPS\Data\Store::i()->achievementRanks ) )
{
\IPS\Data\Store::i()->achievementRanks = iterator_to_array( \IPS\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' ) );
}
/**
* Work out the rank for a given number of points
*
* @param int $points Number of points
* @return \IPS\core\Achievements\Rank|NULL
*/
public static function fromPoints( $points ): ?\IPS\core\Achievements\Rank
{
$return = NULL;
foreach ( static::getStore() as $rank )
{
if ( $points >= $rank->points )
{
$return = $rank;
}
else
{
break;
}
}
return $return;
}
/**
* [Node] Get Icon for tree
*
* @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()
{
if ( $this->icon )
{
return \IPS\File::get( 'core_Badges', $this->icon );
}
else
{
return \IPS\Theme::i()->resource( 'default_rank.png', 'core', 'global' );
}
}
protected static $rankPositions = [];
/**
* Fetch the rank position from all ranks
*
* @return array
*/
public function rankPosition(): array
{
if ( ! isset( static::$rankPositions[ $this->id ] ) )
{
$pos = 1;
foreach( static::getStore() as $rank )
{
if ( $rank->id == $this->id )
{
break;
}
$pos++;
}
static::$rankPositions[ $this->id ] = [
'pos' => $pos,
'max' => \count( static::getStore() )
];
}
return static::$rankPositions[ $this->id ];
}
/**
* Get rank image HTML
*
* @param string|NULL $cssClass Optional CSS class to apply
* @return string
*/
public function html( ?string $cssClass = NULL ): string
{
return \IPS\Theme::i()->getTemplate( 'global', 'core', 'global' )->rank( $this, $cssClass );
}
/**
* [Node] Get Node Description
*
* @return string
*/
protected function get__description()
{
return \IPS\Member::loggedIn()->language()->addToStack( 'achievements_awards_points', FALSE, [ 'pluralize' => [ $this->points ] ] );
}
/**
* [Node] Add/Edit Form
*
* @param \IPS\Helpers\Form $form The form
* @return void
*/
public function form( &$form )
{
$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_Badges', $this->icon ) : NULL, TRUE, array( 'obscure' => FALSE, 'allowedFileTypes' => array_merge( \IPS\Image::$imageExtensions, ['svg'] ), 'checkImage' => TRUE, 'storageExtension' => 'core_Badges' ), function( $val ) {
if( !$val )
{
throw new \DomainException('achievements_bad_image');
}
/* Good luck with your fancy SVG */
$ext = mb_substr( $val->originalFilename, ( mb_strrpos( $val->originalFilename, '.' ) + 1 ) );
if( $ext !== 'svg' )
{
try
{
$image = \IPS\Image::create( $val->contents() );
}
catch ( \Exception $e )
{
throw new \DomainException( 'achievements_bad_image' );
}
}
}, NULL, NULL, 'member_ranks_icon' ) );
}
/**
* [Node] Format form values from add/edit form for save
*
* @param array $values Values from the form
* @return array
*/
public function formatFormValues( $values )
{
if ( !$this->id )
{
$this->save();
}
\IPS\Lang::saveCustom( 'core', "core_member_rank_{$this->id}", $values['member_ranks_word_custom'] );
unset( $values['member_ranks_word_custom'] );
$_values = $values;
$values = array();
foreach ( $_values as $k => $v )
{
if( mb_substr( $k, 0, 13 ) === 'member_ranks_' )
{
$values[ mb_substr( $k, 13 ) ] = $v;
}
else
{
$values[ $k ] = $v;
}
}
return $values;
}
/**
* Show ranks on the community?
*
* @return bool
*/
public static function show(): bool
{
return !( ( \IPS\Settings::i()->achievements_rebuilding or !\IPS\Settings::i()->achievements_enabled ) );
}
/**
* [ActiveRecord] Duplicate
*
* @return void
*/
public function __clone()
{
if ( $this->skipCloneDuplication === TRUE )
{
return;
}
$oldImage = $this->icon;
parent::__clone();
if ( $oldImage )
{
try
{
$image = \IPS\File::get( 'core_Badges', $oldImage );
$newImage = \IPS\File::create( 'core_Badges', $image->originalFilename, $image->contents() );
$this->icon = (string) $newImage;
}
catch ( \Exception $e )
{
$this->icon = NULL;
}
$this->save();
}
}
/**
* Delete Record
*
* @return void
*/
public function delete()
{
if ( $this->icon )
{
try
{
\IPS\File::get( 'core_Badges', $this->icon )->delete();
}
catch( \Exception $ex ) { }
}
parent::delete();
}
/**
* Get output for API
*
* @param \IPS\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 )
{
return array(
'id' => $this->id,
'name' => $this->_title,
'icon' => $this->icon ? $this->_icon->url : $this->_icon,
'points' => $this->points
);
}
/**
* Import from Xml
*
* @param string $file The file to import data from
* @param boolean $option How to handle existing ranks
*
* @return void
*/
public static function importXml( $file, $option=NULL )
{
/* Open XML file */
$xml = \IPS\Xml\XMLReader::safeOpen( $file );
if ( ! @$xml->read() )
{
throw new \DomainException( 'xml_upload_invalid' );
}
/* Did we want to wipe first? */
if ( $option == 'wipe' )
{
foreach( \IPS\core\Achievements\Rank::getStore() as $rank )
{
$rank->delete();
}
}
/* Start looping through each row */
while ( $xml->read() and $xml->name == 'rank' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
$insert = array(
'points' => 0,
'title' => NULL,
'icon' => NULL
);
while ( $xml->read() and $xml->name != 'rank' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
switch( $xml->name )
{
case 'title':
$insert['title'] = $xml->readString();
break;
case 'points':
$insert['points'] = $xml->readString();
break;
case 'icon_name':
$insert['icon_name'] = $xml->readString();
break;
case 'icon_data':
$insert['icon_data'] = base64_decode( $xml->readString() );
break;
}
}
/* Did we want to wipe existing ranks with the same points? */
if ( $option == 'replace' )
{
foreach( \IPS\core\Achievements\Rank::getStore() as $rank )
{
if ( $rank->points == $insert['points'] )
{
$rank->delete();
}
}
}
if ( ! empty( $insert['icon_name'] ) and ! empty( $insert['icon_data'] ) )
{
$insert['icon'] = (string) \IPS\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_member_ranks', $insert );
if ( ! empty( $insert['title'] ) )
{
\IPS\Lang::saveCustom( 'core', "core_member_rank_{$insertId}", $insert['title'] );
}
}
unset( \IPS\Data\Store::i()->achievementRanks );
}
}
@@ -0,0 +1,198 @@
<?php
/**
* @brief Badge Model (as in, a representation of a badge a member *can* earn, not a badge a particular member *has* earned)
* @author <a href='https://www.invisioncommunity.com'>Invision Power Services, Inc.</a>
* @copyright (c) Invision Power Services, Inc.
* @license https://www.invisioncommunity.com/legal/standards/
* @package Invision Community
* @since 25 Mar 21
*/
namespace IPS\core\Achievements;
/* 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;
}
/**
* Recognize
*/
class _Recognize extends \IPS\Patterns\ActiveRecord
{
/**
* @brief Database Table
*/
public static $databaseTable = 'core_member_recognize';
/**
* @brief [ActiveRecord] Database Prefix
*/
public static $databasePrefix = 'r_';
/**
* @brief Multiton Store
*/
protected static $multitons = array();
/**
* Get member object
*
* @return \IPS\Member
*/
public function get__given_by(): \IPS\Member
{
return \IPS\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
*/
public static function loadFromContent( $content ): \IPS\core\Achievements\Recognize
{
$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()
);
}
/**
* Add a new recognize entry
*
* @param \IPS\Content $content Content item that is being rewarded
* @param \IPS\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 string $message Custom message (if any)
* @param \IPS\Member $awardedBy Awarded by
* @param bool $showPublicly Show this message to everyone
*/
public static function add( $content, \IPS\Member $member, $points, $badge, $message, \IPS\Member $awardedBy, $showPublicly=FALSE )
{
$idField = $content::$databaseColumnId;
/* Add to database */
$recognize = new static;
$recognize->member_id = $member->member_id;
$recognize->content_class = \get_class( $content );
$recognize->content_id = $content->$idField;
$recognize->added = time();
$recognize->points = $points;
$recognize->badge = $badge ? $badge->_id : 0;
$recognize->message = $message;
$recognize->given_by = $awardedBy->member_id;
$recognize->public = $showPublicly;
$recognize->save();
if ( $badge )
{
$member->awardBadge( $badge, 0, 0, ['subject'], $recognize->id );
$member->logHistory( 'core', 'badges', [ 'action' => 'manual', 'id' => $badge->_id, 'recognize' => $recognize->id ] );
}
if ( $points )
{
$member->logHistory( 'core', 'points', array('by' => 'manual', 'points' => $points, 'recognize' => $recognize->id ) );
$member->awardPoints( $points, 0, [], ['subject'], $recognize->id );
}
$notification = new \IPS\Notification( \IPS\Application::load( 'core' ), 'new_recognize', $member, [ $recognize ], [ $recognize->id ] );
$notification->recipients->attach( $member );
$notification->send();
}
/**
* Return the content object
*
* @return \IPS\Content
*/
public function content()
{
$class = $this->content_class;
return $class::loadAndCheckPerms( $this->content_id );
}
/**
* Wrapper to get content.
*
* @return \IPS\Content\Item|NULL
* @note This simply wraps content()
*/
public function contentWrapper()
{
/* Get container, if valid */
$content = NULL;
try
{
$content = $this->content();
}
catch( \BadMethodCallException | \OutOfRangeException $e ) { }
return $content;
}
/**
* Return a badge, or null
*
* @return NULL|\IPS\core\Achievements\Badge
*/
public function badge()
{
try
{
return \IPS\core\Achievements\Badge::load( $this->badge );
}
catch( \Exception $e ) { }
return NULL;
}
/**
* Return a member or NULL if the member no longer exists
*
* @return NULL|\IPS\Member
*/
public function awardedBy()
{
try
{
return \IPS\Member::load( $this->given_by );
}
catch( \Exception $e ) { }
return NULL;
}
/**
* Remove the recognize and remove points / badges earned
*
* @return void
*/
public function delete()
{
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 ] );
}
if ( $this->badge )
{
\IPS\Db::i()->delete( 'core_member_badges', [ 'member_id=? and recognize_id=?', $this->member_id, $this->id ] );
}
}
catch( \Exception $e ) { }
parent::delete();
}
}
@@ -0,0 +1,569 @@
<?php
/**
* @brief Achievements Rule Model
* @author <a href='https://www.invisioncommunity.com'>Invision Power Services, Inc.</a>
* @copyright (c) Invision Power Services, Inc.
* @license https://www.invisioncommunity.com/legal/standards/
* @package Invision Community
* @since 24 Feb 2021
*/
namespace IPS\core\Achievements;
/* 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;
}
/**
* Achievements Rule Model
*/
class _Rule extends \IPS\Node\Model
{
/**
* @brief Database Table
*/
public static $databaseTable = 'core_achievements_rules';
/**
* @brief Multiton Store
*/
protected static $multitons;
/**
* @brief [Node] Node Title
*/
public static $nodeTitle = 'achievements_rules';
/**
* @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' => 'achievements',
'prefix' => 'rules_',
);
/**
* @brief [ActiveRecord] Caches
* @note Defined cache keys will be cleared automatically as needed
*/
protected $caches = ['achievementRules'];
/**
* [ActiveRecord] Get cached rules
*
* @return array
*/
public static function getStore(): array
{
if ( !isset( \IPS\Data\Store::i()->achievementRules ) )
{
$v = [];
foreach ( static::roots() as $rule )
{
if ( !isset( $v[ $rule->action ] ) )
{
$v[ $rule->action ] = [];
}
$v[ $rule->action ][ $rule->id ] = [
'filters' => $rule->filters,
'points_subject'=> $rule->points_subject,
'badge_subject' => $rule->badge_subject,
'points_other' => $rule->points_other,
'badge_other' => $rule->badge_other,
'enabled' => $rule->enabled
];
}
\IPS\Data\Store::i()->achievementRules = $v;
}
return \IPS\Data\Store::i()->achievementRules;
}
/**
* Get the extension
*
* @return \IPS\core\Achievements\Actions\AbstractAchievementAction
*/
public function extension(): \IPS\core\Achievements\Actions\AbstractAchievementAction
{
$exploded = explode( '_', $this->action );
return \IPS\Application::load( $exploded[0] )->extensions( 'core', 'AchievementAction' )[ $exploded[1] ];
}
/**
* Get JSON-decoded filters
*
* @return array|NULL
*/
protected function get_filters()
{
if ( isset( $this->_data['filters'] ) and \is_array( $this->_data['filters'] ) )
{
return $this->_data['filters'];
}
return ( isset( $this->_data['filters'] ) and $this->_data['filters'] ) ? json_decode( $this->_data['filters'], TRUE ) : NULL;
}
/**
* [Node] Add/Edit Form
*
* @param \IPS\Helpers\Form $form The form
* @return void
*/
public function form( &$form )
{
$form->_activeFilters = [];
$options = [];
$toggles = [];
$extraElements = [];
foreach ( \IPS\Application::allExtensions( 'core', 'AchievementAction' ) as $achievementAction )
{
if ( ! $achievementAction->canUse() )
{
continue;
}
$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 )
{
if ( $this->filters and array_key_exists( $filterKey, $this->filters ) )
{
$form->_activeFilters[] = $filterElement->name;
}
if ( !$filterElement->htmlId )
{
$filterElement->htmlId = $filterElement->name;
}
$toggles[ "{$exploded[1]}_{$exploded[5]}" ][] = $filterElement->htmlId;
$extraElements[] = $filterElement;
}
$awardTo = $achievementAction->awardOptions();
$awardSubjectField = new \IPS\Helpers\Form\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 );
}
], NULL, NULL, NULL, "{$exploded[1]}_{$exploded[5]}_award_subject" );
if ( isset( $awardTo['subject'] ) )
{
$awardSubjectField->label = \IPS\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" );
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, [
'getHtml' => function( $field ) {
return \IPS\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'] );
$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" );
$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 ] ) );
foreach ( $extraElements as $element )
{
$form->add( $element );
}
}
/**
* [Node] Format form values from add/edit form for save
*
* @param array $values Values from the form
* @return array
*/
public function formatFormValues( $values )
{
if ( !$this->id )
{
$this->action = '';
$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] ];
$filterValues = [];
foreach ( \IPS\Request::i()->activeFilters ?: [] as $k => $v )
{
$filterValues[ $k ] = $values[ $k ];
}
$filters = $extension->formatFilterValues( $filterValues );
foreach( [ 'subject', 'other' ] as $type )
{
if ( isset( $values[$values['achievement_rule_action'] . '_award_' . $type . '_badge'] ) )
{
if ( $values[$values['achievement_rule_action'] . '_award_subject']['badge'] )
{
\IPS\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}" );
}
unset( $values[$values['achievement_rule_action'] . '_award_' . $type . '_badge'] );
}
}
$return = [
'action' => $values['achievement_rule_action'],
'filters' => $filters ? json_encode( $filters ) : NULL,
'milestone' => isset( $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
*/
public function getButtons( $url, $subnode=FALSE )
{
$buttons = parent::getButtons( $url, $subnode );
/* Enable/Disable */
$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(),
'data' => [ 'data-confirm' => 'true' ]
);
return $buttons;
}
/**
* Get badge for subject
*
* @return \IPS\core\Achievements\Badge|NULL
*/
public function badgeSubject(): ?\IPS\core\Achievements\Badge
{
if ( $this->badge_subject )
{
try
{
return \IPS\core\Achievements\Badge::load( $this->badge_subject );
}
catch( \OutOfRangeException $e ) { }
}
return NULL;
}
/**
* Get badge for others
*
* @return \IPS\core\Achievements\Badge|NULL
*/
public function badgeOther(): ?\IPS\core\Achievements\Badge
{
if ( $this->badge_other )
{
try
{
return \IPS\core\Achievements\Badge::load( $this->badge_other );
}
catch( \OutOfRangeException $e ) { }
}
return NULL;
}
/**
* Delete Record
*
* @return void
*/
public function delete()
{
parent::delete();
\IPS\Lang::deleteCustom( 'core', "core_award_subject_badge_{$this->id}" );
\IPS\Lang::deleteCustom( 'core', "core_award_other_badge_{$this->id}" );
}
/**
* Get details about the rebuild progress so far
*
* @return array|NULL
*/
public static function getRebuildProgress(): ?array
{
$return = [ 'count' => 0, 'processed' => 0 ];
$rebuilding = FALSE;
foreach( \IPS\Db::i()->select( '*', 'core_queue', [ [ '`key`=?', 'RebuildAchievements' ] ] ) as $rebuild )
{
$data = json_decode( $rebuild['data'], TRUE );
if ( isset( $data['processed'] ) and isset( $data['count'] ) )
{
$rebuilding = TRUE;
$return['processed'] += (int) $data['processed'];
$return['count'] += (int) $data['count'];
}
}
$return['percentage'] = ( $return['count'] ? ( round( 100 / $return['count'] * $return['processed'], 2 ) ) : 100 );
return $rebuilding ? $return : NULL;
}
/**
* Rebuild all cheeeeeevs
*
* @param \IPS\DateTime|null $time
*/
public static function rebuildAllAchievements( ?\IPS\DateTime $time )
{
\IPS\Db::i()->delete( 'core_achievements_log' );
\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 ] );
/* Remove all previous tasks */
\IPS\Db::i()->delete( 'core_queue', [ '`key`=?', 'RebuildAchievements' ] );
foreach( \IPS\Application::applications() as $app )
{
foreach ( \IPS\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 );
}
}
}
}
/**
* Import from Xml
*
* @param string $file The file to import data from
* @param boolean $deleteExisting Remove existing rules first?
*
* @return void
*/
public static function importXml( $file, $deleteExisting=FALSE )
{
/* Open XML file */
$xml = \IPS\Xml\XMLReader::safeOpen( $file );
if ( ! @$xml->read() )
{
throw new \DomainException( 'xml_upload_invalid' );
}
/* Did we want to wipe first? */
if ( $deleteExisting )
{
foreach( \IPS\core\Achievements\Rule::getStore() as $action => $rules )
{
foreach( $rules as $ruleId => $rule )
{
static::load( $ruleId )->delete();
}
}
}
$allBadges = [];
$badgeMap = [];
/* Rules: Start looping through each row */
while ( $xml->read() )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
if ( $xml->name == 'rule' )
{
$badgesToUpdate = [];
$insert = array(
'action' => NULL,
'filters' => NULL,
'milestone' => 0,
'points_subject' => 0,
'points_other' => 0,
'badge_subject' => 0,
'badge_other' => 0,
'enabled' => 1,
);
$awardSubject = NULL;
$awardOther = NULL;
while ( $xml->read() and $xml->name != 'rule' )
{
if ( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
switch ( $xml->name )
{
case 'action':
case 'filters':
$insert[$xml->name] = $xml->readString();
break;
case 'milestone':
case 'points_subject':
case 'points_other':
case 'enabled':
$insert[$xml->name] = (int)$xml->readString();
break;
case 'badge_subject':
case 'badge_other':
$badgesToUpdate[$xml->name] = $xml->readString();
break;
case 'award_subject_lang':
$awardSubject = $xml->readString();
break;
case 'award_other_lang':
$awardOther = $xml->readString();
break;
}
}
$insertId = \IPS\Db::i()->insert( 'core_achievements_rules', $insert );
$allBadges[ $insertId ] = $badgesToUpdate;
if ( ! empty( $awardSubject ) )
{
\IPS\Lang::saveCustom( 'core', "core_award_subject_badge_{$insertId}", $awardSubject );
}
if ( ! empty( $awardOther ) )
{
\IPS\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 )
{
continue;
}
$insert = [];
$title = NULL;
$id = NULL;
while ( $xml->read() and $xml->name != 'badge' )
{
if( $xml->nodeType != \XMLReader::ELEMENT )
{
continue;
}
switch( $xml->name )
{
case 'manually_awarded':
$insert[ $xml->name ] = (int) $xml->readString();
break;
case 'title':
$title = $xml->readString();
break;
case 'icon_name':
$insert['icon_name'] = $xml->readString();
break;
case 'icon_data':
$insert['icon_data'] = base64_decode( $xml->readString() );
break;
case 'id':
$id = $xml->readString();
break;
}
}
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 );
unset( $insert['icon_name'] );
unset( $insert['icon_data'] );
}
$insertId = \IPS\Db::i()->insert( 'core_badges', $insert );
$badgeMap[ $id ] = $insertId;
if ( ! empty( $title ) )
{
\IPS\Lang::saveCustom( 'core', "core_badges_{$insertId}", $title );
}
}
}
if ( \count( $allBadges ) )
{
foreach( $allBadges as $ruleId => $data )
{
$update = [];
foreach( [ 'badge_subject', 'badge_other' ] as $type )
{
if ( isset( $data[ $type ] ) and isset( $badgeMap[ $data[ $type ] ] ) )
{
$update[ $type ] = $badgeMap[ $data[ $type ] ];
}
}
if ( \count( $update ) )
{
\IPS\Db::i()->update( 'core_achievements_rules', $update, ['`id`=?', $ruleId ] );
}
}
}
unset( \IPS\Data\Store::i()->achievementRules );
}
}
@@ -268,7 +268,7 @@ abstract class _AdminNotification extends \IPS\Patterns\ActiveRecord
* @param string|null $extra Any additional information
* @return void
*/
protected static function find( $app, $extension, $extra = NULL )
public static function find( $app, $extension, $extra = NULL )
{
foreach ( static::allNotifications() as $notification )
{
@@ -665,8 +665,16 @@ abstract class _AdminNotification extends \IPS\Patterns\ActiveRecord
'time' => time()
), TRUE );
$notificationCache = \IPS\Data\Store::i()->acpNotificationIds;
unset( $notificationCache[ $member->member_id ] );
\IPS\Data\Store::i()->acpNotificationIds = $notificationCache;
if( isset( \IPS\Data\Store::i()->acpNotificationIds ) )
{
$notificationCache = \IPS\Data\Store::i()->acpNotificationIds;
if( isset( $notificationCache[ $member->member_id ] ) )
{
unset( $notificationCache[ $member->member_id ] );
}
\IPS\Data\Store::i()->acpNotificationIds = $notificationCache;
}
}
}
@@ -98,7 +98,7 @@ class _Advertisement extends \IPS\Patterns\ActiveRecord
$where[] = array( "ad_start<?", time() );
$where[] = array( "(ad_end=0 OR ad_end>?)", time() );
if( !isset( \IPS\Dispatcher::i()->dispatcherController ) OR !\IPS\Dispatcher::i()->dispatcherController->isContentPage )
if( \IPS\Dispatcher::hasInstance() AND ( !isset( \IPS\Dispatcher::i()->dispatcherController ) OR !\IPS\Dispatcher::i()->dispatcherController->isContentPage ) )
{
$where[] =array( 'ad_nocontent_page_output=?', 1 );
}
@@ -440,7 +440,7 @@ class _Advertisement extends \IPS\Patterns\ActiveRecord
{
if( \count( static::$advertisementIds ) )
{
\IPS\Db::i()->update( 'core_advertisements', "ad_impressions=ad_impressions+1", "ad_id IN(" . implode( ',', static::$advertisementIds ) . ")" );
static::updateCounter( static::$advertisementIds );
/* Reset in case execution continues and more ads are shown */
static::$advertisementIds = array();
@@ -457,10 +457,43 @@ class _Advertisement extends \IPS\Patterns\ActiveRecord
{
if( \count( static::$advertisementIdsEmail ) )
{
\IPS\Db::i()->update( 'core_advertisements', "ad_impressions=ad_impressions+" . $impressions, "ad_id IN(" . implode( ',', static::$advertisementIdsEmail ) . ")" );
static::updateCounter( static::$advertisementIdsEmail, $impressions );
/* Reset in case execution continues and more ads are sent */
static::$advertisementIdsEmail = array();
}
}
}
/**
* Update the advert impression counters
*
* @param array $ids Array of IDs
* @param int $by Number to increment by
* @return void
*/
protected static function updateCounter( array $ids, $by=1 )
{
$countUpdated = false;
if ( \IPS\REDIS_ENABLED and \IPS\CACHE_METHOD == 'Redis' and ( \IPS\CACHE_CONFIG or \IPS\REDIS_CONFIG ) )
{
foreach( $ids as $id )
{
try
{
\IPS\Redis::i()->zIncrBy( 'advert_impressions', $by, $id );
$countUpdated = true;
}
catch ( \Exception $e )
{
}
}
}
if ( ! $countUpdated )
{
\IPS\Db::i()->update( 'core_advertisements', "ad_impressions=ad_impressions+" . $by, "ad_id IN(" . implode( ',', $ids ) . ")" );
}
}
}
@@ -128,6 +128,12 @@ class _Announcement extends \IPS\Content\Item
*/
public static function loadAllByLocation( $location )
{
/* Are we banned? If so, do not return any announcements */
if ( \IPS\Member::loggedIn()->isBanned() )
{
return [];
}
$announcements = static::getStore();
$return = array();
@@ -252,8 +258,8 @@ class _Announcement extends \IPS\Content\Item
{
if ( $key != 'core' )
{
/* Don't list apps without front modules */
if( !\count( $data->modules( 'front' ) ) )
/* Don't list apps without front modules or that are not being revealed */
if( !\count( $data->modules( 'front' ) ) OR $data->hide_tab )
{
continue;
}
@@ -292,7 +298,7 @@ class _Announcement extends \IPS\Content\Item
$groups[ $group->g_id ] = $group->name;
}
$form->add( new \IPS\Helpers\Form\Select( 'announce_permissions', $announcement ? ( $announcement->permissions == '*' ? '*' : explode( ',', $announcement->permissions ) ) : '*', NULL, array( 'multiple' => TRUE, 'options' => $groups, 'unlimited' => '*', 'unlimitedLang' => 'everyone' ) ) );
$form->add( new \IPS\Helpers\Form\CheckboxSet( 'announce_permissions', $announcement ? ( $announcement->permissions == '*' ? '*' : explode( ',', $announcement->permissions ) ) : '*', NULL, array( 'multiple' => TRUE, 'options' => $groups, 'unlimited' => '*', 'unlimitedLang' => 'everyone', 'impliedUnlimited' => TRUE ) ) );
$form->add( new \IPS\Helpers\Form\Custom( 'announce_color', $announcement ? $announcement->color : 'information', NULL, array( 'getHtml' => function( $element )
{
return \IPS\Theme::i()->getTemplate( 'forms', 'core', 'front' )->colorSelection( $element->name, $element->value );
@@ -317,7 +317,7 @@ class _Conversation extends \IPS\Content\Item
protected function processBeforeCreate( $values )
{
$this->maps = array();
$this->to_count = \count( $values['messenger_to'] );
$this->to_count = ( $values['messenger_to'] instanceof \IPS\Member ) ? 1 : \count( $values['messenger_to'] );
parent::processBeforeCreate( $values );
}
@@ -94,6 +94,11 @@ class _Profanity extends \IPS\Patterns\ActiveRecord implements \JsonSerializable
}
else
{
if ( $row['min_posts'] )
{
return \IPS\Member::loggedIn()->language()->addToStack( 'profanity_filter_action_moderate_min_posts', NULL, array( 'pluralize' => array( $row['min_posts'] ) ) );
}
return \IPS\Member::loggedIn()->language()->addToStack('profanity_filter_action_moderate');
}
},
@@ -167,9 +172,11 @@ class _Profanity extends \IPS\Patterns\ActiveRecord implements \JsonSerializable
),
'toggles' => array(
'swap' => array( 'profanity_swop' ),
'moderate' => array()
'moderate' => array( 'profanity_min_posts' )
)
) ) );
$form->add( new \IPS\Helpers\Form\Number( 'profanity_min_posts', ( $current ) ? $current->min_posts : 0, FALSE, array( 'unlimited' => 0, 'unlimitedLang' => 'profanity_min_posts_unlimited' ), NULL, \IPS\Member::loggedIn()->language()->addToStack('profanity_min_posts_prefix'), \IPS\Member::loggedIn()->language()->addToStack('profanity_min_posts_suffix'), 'profanity_min_posts' ) );
$form->add( new \IPS\Helpers\Form\Text( 'profanity_swop', ( $current ) ? $current->swop : NULL, NULL, array(), NULL, NULL, NULL, 'profanity_swop' ) );
$form->add( new \IPS\Helpers\Form\Radio( 'profanity_m_exact', ( $current ) ? $current->m_exact : NULL, FALSE, array(
'options' => array(
@@ -218,6 +225,16 @@ class _Profanity extends \IPS\Patterns\ActiveRecord implements \JsonSerializable
{
$obj->m_exact = $values['m_exact'];
}
if ( array_key_exists( 'm_exact', $values ) )
{
$obj->m_exact = $values['m_exact'];
}
if ( array_key_exists( 'min_posts', $values ) )
{
$obj->min_posts = $values['min_posts'];
}
if ( array_key_exists( 'action', $values ) )
{
@@ -226,7 +243,7 @@ class _Profanity extends \IPS\Patterns\ActiveRecord implements \JsonSerializable
$obj->action = $values['action'];
}
}
$obj->save();
return $obj;
@@ -267,12 +284,13 @@ class _Profanity extends \IPS\Patterns\ActiveRecord implements \JsonSerializable
/**
* Check if the content should be hidden by profanity or url filters
*
* @param string $content The content to check
* @param string $content The content to check
* @param \IPS\Member|NULL $member The author of the content
* @return bool
*/
public static function hiddenByFilters( $content )
public static function hiddenByFilters( $content, $member=NULL )
{
$return = static::_checkProfanityFilters( $content );
$return = static::_checkProfanityFilters( $content, $member );
if ( $return == FALSE )
{
@@ -285,10 +303,11 @@ class _Profanity extends \IPS\Patterns\ActiveRecord implements \JsonSerializable
/**
* Check Profanity Filters
*
* @param string $content The content to check
* @param string $content The content to check
* @param \IPS\Member|NULL $member The author of the content
* @return bool
*/
protected static function _checkProfanityFilters( $content )
protected static function _checkProfanityFilters( $content, $member=NULL )
{
$looseProfanity = array();
$exactProfanity = array();
@@ -296,6 +315,11 @@ class _Profanity extends \IPS\Patterns\ActiveRecord implements \JsonSerializable
{
if ( $profanity->action == 'moderate' )
{
if ( ( $member and $profanity->min_posts ) and $member->member_posts > $profanity->min_posts )
{
continue;
}
if ( $profanity->m_exact )
{
$exactProfanity[] = $profanity->type;
@@ -330,12 +354,12 @@ class _Profanity extends \IPS\Patterns\ActiveRecord implements \JsonSerializable
}
$split = preg_split( '/((?=<^|\b)(?:' . implode( '|', $words ) . ')(?=\b|$))/iu', $content, null, PREG_SPLIT_DELIM_CAPTURE );
if ( \is_array( $split ) )
{
foreach( $split AS $section )
{
if ( \in_array( $section, $exactProfanity ) )
if ( \in_array( mb_strtolower( $section ), array_map( 'mb_strtolower', $exactProfanity ) ) )
{
return TRUE;
break;
@@ -395,7 +419,7 @@ class _Profanity extends \IPS\Patterns\ActiveRecord implements \JsonSerializable
foreach( $tags AS $tag )
{
if ( ( $tag->hasAttribute( 'href' ) and !$tag->hasAttribute( 'data-mentionid' ) ) OR ( ( $tag->hasAttribute( 'src' ) OR $tag->hasAttribute( 'data-embed-src' ) ) AND !$tag->hasAttribute( 'data-emoticon' ) ) )
if ( ( $tag->hasAttribute( 'href' ) and !$tag->hasAttribute( 'data-mentionid' ) AND !$tag->hasAttribute( 'data-fileid' ) ) OR ( ( $tag->hasAttribute( 'src' ) OR $tag->hasAttribute( 'data-embed-src' ) ) AND !$tag->hasAttribute( 'data-emoticon' ) AND !$tag->hasAttribute( 'data-fileid' ) ) )
{
if ( \IPS\Settings::i()->ipb_url_filter_option == 'none' )
{
@@ -111,9 +111,9 @@ class _Field extends \IPS\CustomField
* @param \IPS\Member|NULL $member Member who completed the profile field
* @return string
*/
public function displayValue( $value=NULL, $showSensitiveInformation=FALSE, $location=0, \IPS\Member $member = null )
public function displayValue( $value=NULL, $showSensitiveInformation=FALSE, $location=0, \IPS\Member $member = null, $bypassCustomFormatting=FALSE, $separator=NULL )
{
$formattedValue = parent::displayValue( $value, $showSensitiveInformation );
$formattedValue = parent::displayValue( $value, $showSensitiveInformation, $separator );
$member = $member ?: new \IPS\Member;
switch( $location )
@@ -133,7 +133,7 @@ class _Field extends \IPS\CustomField
case ( static::PROFILE ):
case ( static::PROFILE_COMPLETION ):
if( $this->profile_format )
if( $this->profile_format and !$bypassCustomFormatting )
{
return $this->parseHtmlLogic( $this->profile_format, $value, $formattedValue, $member );
}
@@ -495,7 +495,12 @@ class _Field extends \IPS\CustomField
* @note Defined cache keys will be cleared automatically as needed
*/
protected $caches = array( 'profileFields' );
/**
* @brief [CustomField] Database table
*/
protected static $contentDatabaseTable;
/**
* [ActiveRecord] Delete Record
*
@@ -503,8 +508,9 @@ class _Field extends \IPS\CustomField
*/
public function delete()
{
static::$contentDatabaseTable = 'core_pfields_content';
parent::delete();
\IPS\Db::i()->dropColumn( 'core_pfields_content', "field_{$this->id}" );
/* Do we need to do stuff with profile steps? */
\IPS\Member\ProfileStep::resync();
@@ -873,6 +873,11 @@ class _Promote extends \IPS\Patterns\ActiveRecord
return parent::delete();
}
/**
* @brief Cache internal stream data
*/
protected static $internalStream = array();
/**
* Promote stream of internally promoted items
*
@@ -883,6 +888,13 @@ class _Promote extends \IPS\Patterns\ActiveRecord
*/
public static function internalStream( $limit=10, $sortField='promote_sent', $sortDirection='desc')
{
$_key = md5( $limit . $sortField . $sortDirection );
if( array_key_exists( $_key, static::$internalStream ) )
{
return static::$internalStream[ $_key ];
}
$items = array();
foreach( \IPS\Db::i()->select( '*', 'core_social_promote', array( 'promote_sent > 0 and promote_internal=1 and promote_hide=0' ), $sortField . ' ' . $sortDirection, $limit ) as $row )
@@ -890,6 +902,7 @@ class _Promote extends \IPS\Patterns\ActiveRecord
$items[ $row['promote_id'] ] = static::constructFromData( $row );
}
static::$internalStream[ $_key ] = $items;
return $items;
}
+223 -64
View File
@@ -263,6 +263,11 @@ class _Import extends \IPS\Node\Model
$form->add( new \IPS\Helpers\Form\Node( 'rss_import_node_id', $this->node_id, TRUE, $this->_extension->nodeSelectorOptions( $this ) ) );
$form->add( new \IPS\Helpers\Form\Member( 'rss_import_member', \IPS\Member::load( $this->member ), TRUE ) );
$form->add( new \IPS\Helpers\Form\Text( 'rss_import_showlink', $this->showlink ) );
$form->add( new \IPS\Helpers\Form\Radio( 'rss_import_enclosures', $this->enclosures, FALSE, array( 'options' => array(
'import' => "rss_import_enclosures_import",
'hotlink' => "rss_import_enclosures_hotlink",
'ignore' => "rss_import_enclosures_ignore",
) ) ) );
$form->add( new \IPS\Helpers\Form\Text( 'rss_import_topic_pre', $this->topic_pre, FALSE, array( 'trim' => FALSE ) ) );
$form->add( new \IPS\Helpers\Form\YesNo( 'rss_import_auto_follow', $this->auto_follow, FALSE, array(), NULL, NULL, NULL, 'rss_import_auto_follow' ) );
$this->_extension->form( $form, $this );
@@ -315,7 +320,17 @@ class _Import extends \IPS\Node\Model
throw new \DomainException( \IPS\Member::loggedIn()->language()->addToStack( 'rss_import_invalid' ) );
}
$values['title'] = (string) $request->get()->decodeXml()->channel->title;
$values['title'] = (string) $response->channel->title;
/* Reset the has_enclosures flag */
foreach( $response->articles() as $article )
{
if ( isset( $article['enclosure'] ) and isset( $article['enclosure']['url'] ) )
{
$this->has_enclosures = true;
break;
}
}
}
if( isset( $values['rss_import_node_id'] ) )
@@ -336,6 +351,15 @@ class _Import extends \IPS\Node\Model
unset( $values['rss_import_auto_follow'] );
}
$this->enclosures = $values['rss_import_enclosures'];
unset( $values['rss_import_enclosures'] );
/* If we are ignoring enclosures, reset the has_enclosures flag */
if( $this->enclosures == 'ignore' )
{
$this->has_enclosures = false;
}
if ( $settings = $this->_extension->saveForm( $values, $this ) )
{
$values['settings'] = $settings;
@@ -433,78 +457,98 @@ class _Import extends \IPS\Node\Model
$readMoreLink = "<p><a href='{$article['link']}' {$linkRelPart}>{$this->showlink}</a></p>";
}
/* Parse the article body now, in case we need to add attachments to it later */
$articleContent = \IPS\Text\Parser::parseStatic( $article['content'] . $readMoreLink, TRUE, NULL, $member, $this->_extension->fileStorage, TRUE, !(bool) $member->group['g_dohtml'] );
$imageHtml = '';
if ( isset( $article['enclosure'] ) and isset( $article['enclosure']['url'] ) and isset( $article['enclosure']['length'] ) and isset( $article['enclosure']['type'] ) )
if ( $this->enclosures != 'ignore' and isset( $article['enclosure'] ) and isset( $article['enclosure']['url'] ) and isset( $article['enclosure']['length'] ) and isset( $article['enclosure']['type'] ) )
{
/* Limit imports to around 2mb otherwise timeouts and memory issues can occur when processing with GD */
if ( mb_substr( $article['enclosure']['type'], 0, 6 ) == 'image/' and ( $article['enclosure']['length'] <= 1572864 or \IPS\Settings::i()->image_suite == 'imagemagick' ) )
if ( mb_substr( $article['enclosure']['type'], 0, 6 ) == 'image/' and ( $this->enclosures == 'hotlink' or $article['enclosure']['length'] <= 1572864 or \IPS\Settings::i()->image_suite == 'imagemagick' ) )
{
try
/* Are we remotely linking to the image? */
if( $this->enclosures == 'hotlink' and !$this->_enclosureEmbedded( $article['enclosure']['url'], $articleContent ) )
{
$response = \IPS\Http\Url::external( $article['enclosure']['url'] )->request()->get();
$match = FALSE;
$contentType = ( isset( $response->httpHeaders['Content-Type'] ) ) ? $response->httpHeaders['Content-Type'] : ( ( isset( $response->httpHeaders['content-type'] ) ) ? $response->httpHeaders['content-type'] : NULL );
if ( $contentType )
{
foreach ( \IPS\Image::$imageMimes as $mime )
{
if ( preg_match( '/^' . str_replace( '~~', '.+', preg_quote( str_replace( '*', '~~', $mime ), '/' ) ) . '$/i', $contentType ) )
{
$match = TRUE;
break;
}
}
}
/* Does it match? */
if ( $match )
{
$processAttachment = TRUE;
\IPS\Image::$exifEnabled = FALSE;
if ( method_exists( $this->_extension, 'processEnclosure' ) )
{
if ( $this->_extension->processEnclosure( $this, $response, $article ) !== FALSE )
{
$processAttachment = FALSE;
}
}
if ( $processAttachment )
{
try
{
$image = \IPS\Image::create( $response );
$maxImageSizes = NULL;
if ( \IPS\Settings::i()->attachment_resample_size )
{
$maxImageSizes = explode( 'x', \IPS\Settings::i()->attachment_resample_size );
}
if ( $maxImageSizes !== NULL )
{
$image->resizeToMax( $maxImageSizes[0], $maxImageSizes[1] );
}
$newFile = \IPS\File::create( 'core_Attachment', 'rssImage-' . $guid . '.' . $image->type, (string)$image );
$attachment = $newFile->makeAttachment( md5( $guid . ':' . session_id() ), $member );
$article['attachment'] = $attachment;
$imageHtml = \IPS\Theme::i()->getTemplate( 'editor', 'core', 'global' )->attachedImage( $attachment['attach_location'], $attachment['attach_thumb_location'] ? $attachment['attach_thumb_location'] : $attachment['attach_location'], $attachment['attach_file'], $attachment['attach_id'], $attachment['attach_thumb_location'] ? $attachment['attach_img_width'] : $attachment['attach_location'] );
}
catch ( \Exception $e )
{
}
}
}
$imageName = basename( parse_url( $article['enclosure']['url'], PHP_URL_PATH ) );
$imageHtml = \IPS\Theme::i()->getTemplate( 'editor', 'core', 'global' )->linkedImage( $article['enclosure']['url'], $imageName ?: 'image' );
}
catch ( \IPS\Http\Request\Exception $e )
elseif( $this->enclosures == 'import' )
{
try
{
$response = \IPS\Http\Url::external( $article['enclosure']['url'] )->request()->get();
$match = FALSE;
$contentType = ( isset( $response->httpHeaders['Content-Type'] ) ) ? $response->httpHeaders['Content-Type'] : ( ( isset( $response->httpHeaders['content-type'] ) ) ? $response->httpHeaders['content-type'] : NULL );
if ( $contentType )
{
foreach ( \IPS\Image::$imageMimes as $mime )
{
if ( preg_match( '/^' . str_replace( '~~', '.+', preg_quote( str_replace( '*', '~~', $mime ), '/' ) ) . '$/i', $contentType ) )
{
$match = TRUE;
break;
}
}
}
/* Does it match? */
if ( $match )
{
$processAttachment = TRUE;
\IPS\Image::$exifEnabled = FALSE;
if ( method_exists( $this->_extension, 'processEnclosure' ) )
{
if ( $this->_extension->processEnclosure( $this, $response, $article ) !== FALSE )
{
$processAttachment = FALSE;
}
}
if ( $processAttachment )
{
try
{
$image = \IPS\Image::create( $response );
$maxImageSizes = NULL;
if ( \IPS\Settings::i()->attachment_resample_size )
{
$maxImageSizes = explode( 'x', \IPS\Settings::i()->attachment_resample_size );
/* If the dimensions were 0x0 then correct... */
if ( !$maxImageSizes[0] or !$maxImageSizes[1] )
{
$maxImageSizes = NULL;
}
}
if ( $maxImageSizes !== NULL )
{
$image->resizeToMax( $maxImageSizes[0], $maxImageSizes[1] );
}
$newFile = \IPS\File::create( 'core_Attachment', 'rssImage-' . $guid . '.' . $image->type, (string)$image );
$attachment = $newFile->makeAttachment( md5( $guid . ':' . session_id() ), $member );
$article['attachment'] = $attachment;
/* If the image is already in the body of the article, replace it with our embed instead */
if( !$this->_enclosureReplace( $article['enclosure']['url'], $attachment, $articleContent ) )
{
$imageHtml = \IPS\Theme::i()->getTemplate( 'editor', 'core', 'global' )->attachedImage( $attachment['attach_location'], $attachment['attach_thumb_location'] ? $attachment['attach_thumb_location'] : $attachment['attach_location'], $attachment['attach_file'], $attachment['attach_id'], $attachment['attach_thumb_location'] ? $attachment['attach_img_width'] : $attachment['attach_location'] );
}
}
catch ( \Exception $e ){}
}
}
}
catch ( \IPS\Http\Request\Exception $e )
{
}
}
}
}
$content = $imageHtml . \IPS\Text\Parser::parseStatic( $article['content'] . $readMoreLink, TRUE, NULL, $member, $this->_extension->fileStorage, TRUE, !(bool) $member->group['g_dohtml'] );
$content = $imageHtml . $articleContent;
$item = $this->_extension->create( $this, $article, $container, $content );
$idColumn = $class::$databaseColumnId;
$followArea = mb_strtolower( mb_substr( \get_class( $class ), mb_strrpos( \get_class( $class ), '\\' ) + 1 ) );
@@ -515,7 +559,7 @@ class _Import extends \IPS\Node\Model
'rss_imported_guid' => $guid,
'rss_imported_content_id' => $item->$idColumn,
'rss_imported_import_id' => $this->id
) );
), TRUE );
if ( $this->auto_follow )
{
@@ -540,7 +584,7 @@ class _Import extends \IPS\Node\Model
'rss_imported_guid' => $guid,
'rss_imported_content_id' => 0,
'rss_imported_import_id' => $this->id
) );
), TRUE );
}
$i++;
@@ -558,6 +602,121 @@ class _Import extends \IPS\Node\Model
$this->last_import = time();
$this->save();
}
/**
* Check if the enclosure URL is already embedded in the content we are parsing and if so, replace it
*
* @param string $url Enclosure URL
* @param array $attachment Attachment details
* @param string $content Body of article
* @return bool
*/
protected function _enclosureReplace( $url, $attachment, &$content )
{
/* Load source */
$source = new \IPS\Xml\DOMDocument( '1.0', 'UTF-8' );
$source->loadHTML( \IPS\Xml\DOMDocument::wrapHtml( $content ) );
/* Look for the image URL and replace it with the attachment if found */
$replaced = FALSE;
$contentImages = $source->getElementsByTagName( 'img' );
foreach( $contentImages as $element )
{
$srcAttribute = $element->hasAttribute('data-src') ? 'data-src' : 'src';
if ( $element->hasAttribute( $srcAttribute ) AND $element->getAttribute( $srcAttribute ) == $url )
{
$replaced = true;
$element->setAttribute( 'data-fileid', $attachment['attach_id'] );
$element->setAttribute( $srcAttribute, '{fileStore.core_Attachment}/' . ( $attachment['attach_thumb_location'] ? $attachment['attach_thumb_location'] : $attachment['attach_location'] ) );
}
}
if( $replaced )
{
$content = \IPS\Text\DOMParser::getDocumentBodyContents( $source );
$content = \IPS\Text\Parser::replaceFileStoreTags( $content );
/* Set lazy loading and wrapping link on the content */
if( $rebuilt = \IPS\Text\Parser::rebuildAttachmentUrls( $content ) )
{
$content = $rebuilt;
}
$content = \IPS\Text\Parser::parseLazyLoad( $content, \IPS\Settings::i()->lazy_load_enabled );
/* And then finally, we need to reparse to make sure our replacement tags are in place */
$source = new \IPS\Xml\DOMDocument( '1.0', 'UTF-8' );
$source->loadHTML( \IPS\Xml\DOMDocument::wrapHtml( $content ) );
$tags = array( 'a', 'img' );
foreach( $tags as $tag )
{
$elements = $source->getElementsByTagName( $tag );
foreach( $elements as $element )
{
/* Anything which has a URL may need swapping out */
foreach ( array( 'href', 'src', 'data-src', 'data-video-src', 'data-embed-src', 'srcset', 'data-ipshover-target', 'data-fileid', 'cite', 'action', 'longdesc', 'usemap', 'poster' ) as $attribute )
{
if ( $element->hasAttribute( $attribute ) )
{
if ( preg_match( '#^(https?:)?//(' . preg_quote( rtrim( str_replace( array( 'http://', 'https://' ), '', \IPS\Settings::i()->base_url ), '/' ), '#' ) . ')/(.+?)$#', $element->getAttribute( $attribute ), $matches ) )
{
$element->setAttribute( $attribute, '%7B___base_url___%7D/' . $matches[3] );
}
}
}
foreach ( array( 'srcset', 'style' ) as $attribute )
{
if ( $element->hasAttribute( $attribute ) )
{
if ( mb_strpos( $element->getAttribute( $attribute ), \IPS\Settings::i()->base_url ) )
{
$element->setAttribute( $attribute, str_replace( \IPS\Settings::i()->base_url, '%7B___base_url___%7D/', $element->getAttribute( $attribute ) ) );
}
}
}
}
}
$content = \IPS\Text\DOMParser::getDocumentBodyContents( $source );
/* Replace file storage tags */
$content = preg_replace( '/&lt;fileStore\.([\d\w\_]+?)&gt;/i', '<fileStore.$1>', $content );
$content = str_replace( array( '&lt;___base_url___&gt;', '%7B___base_url___%7D' ), '<___base_url___>', $content );
}
return $replaced;
}
/**
* Check if the enclosure URL is already embedded in the content we are parsing
*
* @param string $url Enclosure URL
* @param string $content Body of article
* @return bool
*/
protected function _enclosureEmbedded( $url, $content )
{
/* Load source */
$source = new \IPS\Xml\DOMDocument( '1.0', 'UTF-8' );
$source->loadHTML( \IPS\Xml\DOMDocument::wrapHtml( $content ) );
/* Look for the image URL */
$contentImages = $source->getElementsByTagName( 'img' );
foreach( $contentImages as $element )
{
if ( $element->hasAttribute('src') AND $element->getAttribute('src') == $url )
{
return true;
}
}
return false;
}
/**
* [ActiveRecord] Delete Record
+1 -12
View File
@@ -124,7 +124,7 @@ class _Rss extends \IPS\Node\Model
{
$groups[ $group_id ] = $group->name;
}
$form->add( new \IPS\Helpers\Form\Select( 'rss_groups', ( $this->_id ) ? $this->groups : '*', FALSE, array( 'options' => $groups, 'multiple' => TRUE, 'unlimited' => '*' ) ) );
$form->add( new \IPS\Helpers\Form\CheckboxSet( 'rss_groups', ( $this->_id ) ? $this->groups : '*', FALSE, array( 'options' => $groups, 'multiple' => TRUE, 'unlimited' => '*', 'impliedUnlimited' => TRUE ) ) );
/* Content Form */
$form->addHeader( 'rss_content' );
@@ -422,17 +422,6 @@ class _Rss extends \IPS\Node\Model
return $document->asXML();
}
/**
* Get all saved RSS feeds (enabled status must be checked in userland code)
*
* @return array
* @deprecated
*/
public static function getAllFeeds()
{
return static::getStore();
}
/**
* Get all saved RSS feeds (enabled status must be checked in userland code)
+16 -8
View File
@@ -57,7 +57,7 @@ class _Install
if ( $return['requirements']['PHP']['version']['success'] and version_compare( $phpVersion, $requirements['php']['recommended'] ) == -1 )
{
$return['requirements']['PHP']['version']['message'] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_php_version_success', FALSE, array( 'sprintf' => array( $phpVersion ) ) );
$return['advice']['php'] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_php_version_advice', FALSE, array( 'sprintf' => array( $phpVersion, $requirements['php']['recommended'] ) ) );
$return['advice']['PHP']['php'] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_php_version_advice', FALSE, array( 'sprintf' => array( $phpVersion, $requirements['php']['recommended'] ) ) );
}
/* We require file_uploads otherwise lots of stuff won't work */
@@ -66,6 +66,7 @@ class _Install
$return['requirements']['PHP'][] = array(
'success' => FALSE,
'message' => \IPS\Member::loggedIn()->language()->addToStack( 'requirements_file_uploads' ),
'short' => \IPS\Member::loggedIn()->language()->addToStack( 'health__php_fileuploads' ),
);
}
@@ -84,13 +85,14 @@ class _Install
'message' => \IPS\Member::loggedIn()->language()->addToStack( 'requirements_curl_fopen' ),
);
$return['advice'][] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_curl_advice' );
$return['advice']['PHP']['curl'] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_curl_advice' );
}
else
{
$return['requirements']['PHP'][] = array(
'success' => FALSE,
'message' => \IPS\Member::loggedIn()->language()->addToStack( 'requirements_curl_fail' ),
'short' => \IPS\Member::loggedIn()->language()->addToStack( 'health__php_curl' ),
);
}
@@ -109,6 +111,7 @@ class _Install
$return['requirements']['PHP'][] = array(
'success' => FALSE,
'message' => \IPS\Member::loggedIn()->language()->addToStack( 'requirements_mb_regex' ),
'short' => \IPS\Member::loggedIn()->language()->addToStack( 'health__php_mbregex' ),
);
}
@@ -117,6 +120,7 @@ class _Install
$return['requirements']['PHP'][] = array(
'success' => FALSE,
'message' => \IPS\Member::loggedIn()->language()->addToStack( 'requirements_mb_overload' ),
'short' => \IPS\Member::loggedIn()->language()->addToStack( 'health__php_mboverload' ),
);
}
}
@@ -125,6 +129,7 @@ class _Install
$return['requirements']['PHP'][] = array(
'success' => FALSE,
'message' => \IPS\Member::loggedIn()->language()->addToStack( 'requirements_mb_fail' ),
'short' => \IPS\Member::loggedIn()->language()->addToStack( 'health__php_mb' ),
);
}
@@ -148,17 +153,18 @@ class _Install
$return['requirements']['PHP'][] = array(
'success' => FALSE,
'message' => \IPS\Member::loggedIn()->language()->addToStack( 'requirements_extension_fail', FALSE, array( 'sprintf' => array( \IPS\Member::loggedIn()->language()->addToStack( "requirements_extension_{$extension}" ) ) ) ),
'short' => \IPS\Member::loggedIn()->language()->addToStack( 'health__php_extension', FALSE, array( 'sprintf' => array( $extension ) ) ),
);
}
elseif ( $type === 'advised' )
{
if( \IPS\Member::loggedIn()->language()->checkKeyExists( 'requirements_extension_advice_' . $extension ) )
{
$return['advice'][] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_extension_advice_' . $extension );
$return['advice']['PHP'][ $extension ] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_extension_advice_' . $extension );
}
else
{
$return['advice'][] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_extension_advice', FALSE, array( 'sprintf' => array( \IPS\Member::loggedIn()->language()->addToStack( "requirements_extension_{$extension}" ) ) ) );
$return['advice']['PHP'][ $extension ] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_extension_advice', FALSE, array( 'sprintf' => array( \IPS\Member::loggedIn()->language()->addToStack( "requirements_extension_{$extension}" ) ) ) );
}
}
}
@@ -198,10 +204,13 @@ class _Install
{
$return['requirements']['PHP'][] = array(
'success' => FALSE,
'message' => \IPS\Member::loggedIn()->language()->addToStack( 'requirements_memory_limit_fail', FALSE, array( 'sprintf' => array( \IPS\Output\Plugin\Filesize::humanReadableFilesize( $memoryLimit ) ) ) )
'message' => \IPS\Member::loggedIn()->language()->addToStack( 'requirements_memory_limit_fail', FALSE, array( 'sprintf' => array( \IPS\Output\Plugin\Filesize::humanReadableFilesize( $memoryLimit ) ) ) ),
'short' => \IPS\Member::loggedIn()->language()->addToStack( 'health__php_memory' ),
);
}
$writeablesKey = \IPS\Member::loggedIn()->language()->addToStack('requirements_file_system');
/* Suhosin */
if ( \extension_loaded( 'suhosin' ) )
{
@@ -217,19 +226,18 @@ class _Install
$value = ini_get( $setting );
if ( $value and $value < $minimum )
{
$return['advice'][] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_suhosin_limit', FALSE, array( 'sprintf' => array( $setting, $value, $minimum ) ) );
$return['advice'][ $writeablesKey ]['suhosin'] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_suhosin_limit', FALSE, array( 'sprintf' => array( $setting, $value, $minimum ) ) );
}
}
$value = ini_get('suhosin.cookie.encrypt');
if ( $value and $value == 1 )
{
$return['advice'][] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_suhosin_cookie_encrypt' );
$return['advice'][ $writeablesKey ]['suhosin'] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_suhosin_cookie_encrypt' );
}
}
/* Writeables */
$writeablesKey = \IPS\Member::loggedIn()->language()->addToStack('requirements_file_system');
foreach ( array( 'applications', 'datastore', 'plugins', 'uploads' ) as $dir )
{
$success = is_writable( \IPS\ROOT_PATH . '/' . $dir );
+25 -10
View File
@@ -92,7 +92,7 @@ class _Upgrade
}
$maxChunkSizeValues = \IPS\Member::loggedIn()->language()->formatList( $maxChunkSizeValues );
$return['advice']["filesystem{$class->configurationId}"] = \IPS\Member::loggedIn()->language()->addToStack( 'file_storage_test_chunk_mismatch', FALSE, array( 'sprintf' => array( $class->displayName( $class->configuration ), \IPS\Output\Plugin\Filesize::humanReadableFilesize( $maxChunkSize * 1048576 ), \IPS\Output\Plugin\Filesize::humanReadableFilesize( $class::$minChunkSize * 1048576 ), $maxChunkSizeValues ) ) );
$return['advice'][ $writeablesKey ]["filesystem{$class->configurationId}"] = \IPS\Member::loggedIn()->language()->addToStack( 'file_storage_test_chunk_mismatch', FALSE, array( 'sprintf' => array( $class->displayName( $class->configuration ), \IPS\Output\Plugin\Filesize::humanReadableFilesize( $maxChunkSize * 1048576 ), \IPS\Output\Plugin\Filesize::humanReadableFilesize( $class::$minChunkSize * 1048576 ), $maxChunkSizeValues ) ) );
}
$successfulStorage = TRUE;
@@ -134,6 +134,21 @@ class _Upgrade
{
unset( $return['requirements'][ $writeablesKey ]['datastore'] );
}
/* If InnoDB is in use check that COMPACT isn't used */
if ( !\IPS\CIC AND iterator_to_array( \IPS\Db::i()->query( "SHOW TABLE STATUS WHERE Engine='InnoDB' AND Row_format='Compact'" ) ) )
{
$ifpt = '';
foreach ( \IPS\Db::i()->query("SHOW VARIABLES LIKE 'innodb_file_per_table'") as $row )
{
if( \strtolower( $row['Value'] ) !== \strtolower( 'ON' ) )
{
$ifpt = \IPS\Member::loggedIn()->language()->get( 'requirements_mysql_ifpt_advice' );
}
}
$return['advice']['MySQL']['compact'] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_mysql_format_advice', FALSE, array( 'htmlsprintf' => array( $ifpt ) ) );
}
return $return;
}
@@ -166,7 +181,7 @@ class _Upgrade
if ( version_compare( $mysqlVersion, $requirements['mysql']['recommended'] ) == -1 AND !mb_strpos( $mysqlVersion, "MariaDB" ) )
{
$return['advice'][] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_mysql_version_advice', FALSE, array( 'sprintf' => array( $mysqlVersion, $requirements['mysql']['recommended'] ) ) );
$return['advice']['MySQL']['version'] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_mysql_version_advice', FALSE, array( 'sprintf' => array( $mysqlVersion, $requirements['mysql']['recommended'] ) ) );
}
}
else
@@ -188,13 +203,13 @@ class _Upgrade
{
if ( $row['Variable_name'] == 'wait_timeout' AND $row['Value'] < 20 )
{
$return['advice'][] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_mysql_timeout', FALSE, array( 'sprintf' => array( $row['Variable_name'], $row['Value'] ) ) );
$return['advice']['MySQL']['timeout'] = \IPS\Member::loggedIn()->language()->addToStack( 'requirements_mysql_timeout', FALSE, array( 'sprintf' => array( $row['Variable_name'], $row['Value'] ) ) );
}
}
}
catch( \IPS\Db\Exception $e )
{
$return['advice'][] = $e->getMessage();
$return['advice']['MySQL'][] = $e->getMessage();
}
return $return;
@@ -480,9 +495,9 @@ class _Upgrade
try
{
if( file_exists( \IPS\ROOT_PATH . "/applications/{$app}/setup/upg_{$extra['_current']}/lang.json" ) )
if( file_exists( \IPS\Application::load( $app )->getApplicationPath() . "/setup/upg_{$extra['_current']}/lang.json" ) )
{
$langChanges = json_decode( \file_get_contents( \IPS\ROOT_PATH . "/applications/{$app}/setup/upg_{$extra['_current']}/lang.json" ), TRUE );
$langChanges = json_decode( \file_get_contents( \IPS\Application::load( $app )->getApplicationPath() . "/setup/upg_{$extra['_current']}/lang.json" ), TRUE );
if ( isset( $langChanges['normal']['removed'] ) and $langChanges['normal']['removed'] )
{
\IPS\Db::i()->delete( 'core_sys_lang_words', array( array( 'word_app=?', $app ), array( 'word_js=0' ), array( \IPS\Db::i()->in( 'word_key', $langChanges['normal']['removed'] ) ) ) );
@@ -794,7 +809,7 @@ class _Upgrade
if( !\IPS\CIC2 AND !is_writable( \IPS\SITE_FILES_PATH . '/plugins/hooks.php' ) )
{
throw new \RuntimeException( sprintf( \IPS\Member::loggedIn()->language()->get("hook_file_not_writable"), \IPS\ROOT_PATH . '/plugins/hooks.php' ) );
throw new \RuntimeException( sprintf( \IPS\Member::loggedIn()->language()->get("hook_file_not_writable"), \IPS\SITE_FILES_PATH . '/plugins/hooks.php' ) );
}
try
@@ -824,11 +839,11 @@ class _Upgrade
}
/* Update application data */
if( file_exists( \IPS\ROOT_PATH . '/applications/' . $app . '/data/application.json' ) )
if( file_exists( \IPS\Application::load( $app )->getApplicationPath() . '/data/application.json' ) )
{
\IPS\Log::debug( "Installing application data for " . $app, 'upgrade' );
$application = json_decode( file_get_contents( \IPS\ROOT_PATH . '/applications/' . $app . '/data/application.json' ), TRUE );
$application = json_decode( file_get_contents( \IPS\Application::load( $app )->getApplicationPath() . '/data/application.json' ), TRUE );
//\IPS\Lang::saveCustom( $app, "__app_{$app}", $application['application_title'] );
@@ -1141,7 +1156,7 @@ class _Upgrade
*/
public static function runLegacySql( $app, $upgradeId, $file='queries.php' )
{
$queryFile = \IPS\ROOT_PATH . '/applications/' . $app . '/setup/upg_' . $upgradeId . '/' . $file;
$queryFile = \IPS\Application::load( $app )->getApplicationPath() . '/setup/upg_' . $upgradeId . '/' . $file;
$lastIndex = ( isset( $_SESSION['lastJsonIndex'] ) ) ? $_SESSION['lastJsonIndex'] : 0;
if ( file_exists( $queryFile ) )
@@ -230,7 +230,7 @@ class _Service extends \IPS\Node\Model
public function form( &$form )
{
$form->add( new \IPS\Helpers\Form\Text( 'share_title', $this->title, TRUE ) );
$form->add( new \IPS\Helpers\Form\Select( 'share_groups', ( $this->groups != '*' ) ? explode( ",", $this->groups ) : $this->groups, FALSE, array( 'options' => \IPS\Member\Group::groups(), 'parse' => 'normal', 'multiple' => TRUE, 'unlimited' => '*', 'unlimitedLang' => 'everyone' ) ) );
$form->add( new \IPS\Helpers\Form\CheckboxSet( 'share_groups', ( $this->groups != '*' ) ? explode( ",", $this->groups ) : $this->groups, FALSE, array( 'options' => \IPS\Member\Group::groups(), 'parse' => 'normal', 'multiple' => TRUE, 'unlimited' => '*', 'unlimitedLang' => 'everyone', 'impliedUnlimited' => TRUE ) ) );
/* Find the service and see if it has any additional settings... */
$services = \IPS\Content\ShareServices::services();
@@ -254,13 +254,19 @@ class _Service extends \IPS\Node\Model
$values['share_autoshare'] = $values[ 'share_autoshare_' . ucwords( $this->key ) ];
unset( $values[ 'share_autoshare_' . ucwords( $this->key ) ] );
$loginHandlers = \IPS\Login::handlers(TRUE);
if ( isset( $loginHandlers[ ucwords( $this->key ) ] ) )
$loginHandlers = \IPS\Login::getStore();
foreach( $loginHandlers as $handler )
{
$settings = $loginHandlers[ ucwords( $this->key ) ]->settings;
$settings['autoshare'] = $values['share_autoshare'];
$loginHandlers[ ucwords( $this->key ) ]->settings = json_encode( $settings );
$loginHandlers[ ucwords( $this->key ) ]->save();
$_key = mb_substr( \get_class( $handler ), 10 );
if ( $_key == ucwords( $this->key ) )
{
$settings = $handler->settings;
$settings['autoshare'] = $values['share_autoshare'];
$handler->settings = json_encode( $settings );
$handler->save();
}
}
}
@@ -185,7 +185,13 @@ class _Group extends \IPS\Node\Model
}
else
{
foreach ( \IPS\Db::i()->select( '*', 'core_members', array( 'member_group_id=? OR FIND_IN_SET( ?, mgroup_others )', $child->type_id, $child->type_id ), 'name' ) as $m )
$memberIds = array();
foreach ( \IPS\Db::i()->select( 'member_id', 'core_members', array( 'member_group_id=? OR FIND_IN_SET( ?, mgroup_others )', $child->type_id, $child->type_id ), 'name' ) as $memberId )
{
$memberIds[] = $memberId;
}
foreach ( \IPS\Db::i()->select( '*', 'core_members', array( \IPS\Db::i()->in( 'member_id', $memberIds ) ) ) as $m )
{
if ( !isset( $members[ $m['member_id'] ] ) )
{
@@ -66,6 +66,11 @@ class _User extends \IPS\Node\Model
* @brief [Node] Order Database Column
*/
public static $databaseColumnOrder = 'position';
/**
* @brief [Node] Node Title
*/
public static $nodeTitle = 'staff_directory';
/**
* @brief [Node] ACP Restrictions
@@ -128,7 +133,6 @@ class _User extends \IPS\Node\Model
}, NULL, NULL, 'leader_id_member' ) );
$form->add( new \IPS\Helpers\Form\Radio( 'leader_use_custom_name', ( \IPS\Member::loggedIn()->language()->checkKeyExists("core_staff_directory_name_{$this->id}") ) ? 1 : 0, FALSE, array( 'options' => array( 0 => 'leader_custom_name_default', 1 => 'leader_custom_name_custom' ), 'toggles' => array( 1 => array( 'leader_custom_name' ) ) ), NULL, NULL, NULL, 'leader_name_toggle' ) );
$form->add( new \IPS\Helpers\Form\Translatable( 'leader_custom_name', NULL, FALSE, array( 'app' => 'core', 'key' => ( $this->id ? "core_staff_directory_name_{$this->id}" : NULL ) ), NULL, NULL, NULL, 'leader_custom_name' ) );
$form->add( new \IPS\Helpers\Form\Radio( 'leader_use_custom_title', ( \IPS\Member::loggedIn()->language()->checkKeyExists("core_staff_directory_title_{$this->id}") ) ? 1 : 0, FALSE, array( 'options' => array( 0 => 'leader_custom_title_default', 1 => 'leader_custom_title_custom' ), 'toggles' => array( 1 => array( 'leader_custom_title' ) ) ), NULL, NULL, NULL, 'leader_title_toggle' ) );
$form->add( new \IPS\Helpers\Form\Translatable( 'leader_custom_title', NULL, FALSE, array( 'app' => 'core', 'key' => ( $this->id ? "core_staff_directory_title_{$this->id}" : NULL ) ), NULL, NULL, NULL, 'leader_custom_title' ) );
$form->add( new \IPS\Helpers\Form\Translatable( 'leader_custom_bio', NULL, FALSE, array(
'app' => 'core',
@@ -201,17 +205,10 @@ class _User extends \IPS\Node\Model
\IPS\Lang::saveCustom( 'core', "core_staff_directory_name_{$this->id}", $values['leader_custom_name'] );
}
if ( isset( $values['leader_use_custom_title'] ) )
{
$toUnset[] = 'leader_use_custom_title';
$toUnset[] = 'leader_custom_title';
\IPS\Lang::deleteCustom( 'core', "core_staff_directory_title_{$this->id}" );
}
if( isset( $values['leader_custom_title'] ) AND isset( $values['leader_use_custom_title'] ) AND $values['leader_use_custom_title'] )
if( isset( $values['leader_custom_title'] ) )
{
\IPS\Lang::saveCustom( 'core', "core_staff_directory_title_{$this->id}", $values['leader_custom_title'] );
unset( $values['leader_custom_title'] );
}
if( array_key_exists( 'leader_custom_bio', $values ) )
+52 -19
View File
@@ -291,6 +291,11 @@ class _Status extends \IPS\Content\Item implements \IPS\Content\Lockable, \IPS\C
$return = TRUE;
/* Can we access the module? */
if( !( $member->canAccessModule( \IPS\Application\Module::get( 'core', 'status' ) ) and \IPS\Settings::i()->profile_comments ) )
{
return FALSE;
}
if ( !parent::canCreate( $member, $container, $showError ) )
{
$return = FALSE;
@@ -378,6 +383,21 @@ class _Status extends \IPS\Content\Item implements \IPS\Content\Lockable, \IPS\C
return $formElements;
}
/**
* Return the comment form object
*
* @return \IPS\Helpers\Form
*/
protected function _commentForm()
{
$idColumn = static::$databaseColumnId;
$form = new \IPS\Helpers\Form( 'commentform' . '_' . $this->$idColumn, static::$formLangPrefix . 'submit_comment', $this->url() );
$form->class = 'ipsForm_vertical';
$form->hiddenValues['_contentReply'] = TRUE;
return $form;
}
/**
* Add the comment form elements
*
@@ -419,7 +439,7 @@ class _Status extends \IPS\Content\Item implements \IPS\Content\Lockable, \IPS\C
{
/* Create */
$status = parent::createFromForm( $values, $container, $sendNotification );
\IPS\File::claimAttachments( 'status', $status->id, NULL, $status->member_id );
\IPS\File::claimAttachments( 'status' . $status->member_id, $status->id, NULL, $status->member_id );
/* Return */
return $status;
@@ -528,23 +548,37 @@ class _Status extends \IPS\Content\Item implements \IPS\Content\Lockable, \IPS\C
$notification->send();
}
/* Notify when a follower posts a status update */
if ( $this->author()->member_id == $this->member_id )
}
/**
* Users to receive immediate notifications
*
* @param int|array $limit LIMIT clause
* @param string|NULL $extra Additional data
* @param boolean $countOnly Just return the count
* @return \IPS\Db\Select
*/
public function notificationRecipients( $limit=array( 0, 25 ), $extra=NULL, $countOnly=FALSE )
{
if( $countOnly )
{
$notification = new \IPS\Notification( \IPS\Application::load( 'core' ), 'new_status', $this, array( $this ) );
$followers = \IPS\Member::load( $this->member_id )->followers( 3, array( 'immediate' ), $this->mapped('date'), NULL );
if( $followers !== NULL and \count( $followers ) )
{
foreach( $followers AS $follower )
{
$notification->recipients->attach( \IPS\Member::load( $follower['follow_member_id'] ) );
}
}
$notification->send( $sentTo );
return $this->author()->followersCount( 3, array( 'immediate' ), $this->mapped('date') );
}
else
{
return $this->author()->followers( 3, array( 'immediate' ), $this->mapped('date'), $limit );
}
}
/**
* Create Notification
*
* @param string|NULL $extra Additional data
* @return \IPS\Notification
*/
protected function createNotification( $extra=NULL )
{
return new \IPS\Notification( \IPS\Application::load( 'core' ), 'new_status', $this, array( $this ) );
}
/**
@@ -692,8 +726,7 @@ class _Status extends \IPS\Content\Item implements \IPS\Content\Lockable, \IPS\C
if ( $numberOfComments >= $limit )
{
/* Work out what page we're looking at, but only if we are actually paginating through comments */
/* @future we should probably remove the dependancy on \IPS\Request::i()->page here, as the status may be display on a page that isn't necessarily the profile (ex: My Activity) */
$page = ( isset( \IPS\Request::i()->page ) AND isset( \IPS\Request::i()->status ) ) ? \intval( \IPS\Request::i()->page ) : 1;
$page = ( isset( \IPS\Request::i()->commentPage ) AND isset( \IPS\Request::i()->status ) ) ? \intval( \IPS\Request::i()->commentPage ) : 1;
if( $page < 1 )
{
$page = 1;
@@ -757,7 +790,7 @@ class _Status extends \IPS\Content\Item implements \IPS\Content\Lockable, \IPS\C
* @param array $reactions Reaction Data
* @return string
*/
public static function searchResult( array $indexData, array $authorData, array $itemData, array $containerData = NULL, array $reputationData, $reviewRating, $iPostedIn, $view, $asItem, $canIgnoreComments=FALSE, $template=NULL, $reactions=array() )
public static function searchResult( array $indexData, array $authorData, array $itemData, ?array $containerData, array $reputationData, $reviewRating, $iPostedIn, $view, $asItem, $canIgnoreComments=FALSE, $template=NULL, $reactions=array() )
{
if ( $template !== NULL )
{
+20 -10
View File
@@ -348,7 +348,7 @@ class _Stream extends \IPS\Node\Model
if ( $titleType )
{
$titleClass = '\IPS\Helpers\Form\\' . $titleType;
$form->add( new $titleClass( 'stream_title', ( $this->id and $titleType === 'Text' ) ? $this->_title : NULL, $titleRequired, array( 'app' => 'core', 'key' => ( $this->id ? "stream_title_{$this->id}" : NULL ) ) ) );
$form->add( new $titleClass( 'stream_title', ( $this->id and $titleType === 'Text' ) ? $this->_title : NULL, $titleRequired, array( 'app' => 'core', 'key' => ( $this->id ? "stream_title_{$this->id}" : NULL ),'maxLength' => 255 ) ) );
}
/* All content or specific content? */
@@ -494,19 +494,22 @@ class _Stream extends \IPS\Node\Model
) ), NULL, NULL, NULL, 'stream_followed_types' ) );
/* Date */
$form->add( new \IPS\Helpers\Form\Radio( 'stream_date_type', $this->date_type, TRUE, array(
'options' => array(
'all' => 'stream_date_type_all',
'last_visit' => 'stream_date_type_last_visit',
'relative' => 'stream_date_type_relative',
'custom' => 'stream_date_type_custom',
),
$streamDateOptions = [];
if ( \IPS\Settings::i()->search_method === 'elastic' )
{
$streamDateOptions['all'] = 'stream_date_type_all';
}
$streamDateOptions['last_visit'] = 'stream_date_type_last_visit';
$streamDateOptions['relative'] = 'stream_date_type_relative';
$streamDateOptions['custom'] = 'stream_date_type_custom';
$form->add( new \IPS\Helpers\Form\Radio( 'stream_date_type', $this->id ? $this->date_type : ( \IPS\Settings::i()->search_method === 'elastic' ? 'all' : 'relative' ), TRUE, array(
'options' => $streamDateOptions,
'toggles' => array(
'relative' => array( 'stream_date_relative_days' ),
'custom' => array( 'stream_date_range' )
)
) ) );
$form->add( new \IPS\Helpers\Form\Interval( 'stream_date_relative_days', $this->date_relative_days ?: 7, NULL, array( 'valueAs' => \IPS\Helpers\Form\Interval::DAYS ), function( $val )
$form->add( new \IPS\Helpers\Form\Interval( 'stream_date_relative_days', $this->date_relative_days ?: 365, NULL, array( 'valueAs' => \IPS\Helpers\Form\Interval::DAYS ), function( $val )
{
if ( \IPS\Request::i()->stream_date_type == 'relative' and !$val )
{
@@ -1232,7 +1235,14 @@ class _Stream extends \IPS\Node\Model
$query->$filterDateMethod( \IPS\DateTime::ts( \IPS\Member::loggedIn()->last_visit ) );
break;
case 'relative':
$query->$filterDateMethod( \IPS\DateTime::create()->sub( new \DateInterval( 'P' . \intval( $this->date_relative_days ) . 'D' ) ) );
if ( \is_array( $this->date_relative_days ) )
{
$query->$filterDateMethod( \IPS\DateTime::create()->sub( new \DateInterval( 'P' . \intval( $this->date_relative_days['val'] ) . mb_strtoupper( $this->date_relative_days['unit'] ) ) ) );
}
else
{
$query->$filterDateMethod( \IPS\DateTime::create()->sub( new \DateInterval( 'P' . \intval( $this->date_relative_days ) . 'D' ) ) );
}
case 'custom':
$query->$filterDateMethod( $this->date_start ? \IPS\DateTime::ts( $this->date_start ) : NULL, $this->date_end ? \IPS\DateTime::ts( $this->date_end ) : NULL );
break;
@@ -90,6 +90,8 @@ class _Reason extends \IPS\Node\Model
, 'unlimited' => -1, 'unlimitedLang' => 'never'
) ) );
$form->add( new \IPS\Helpers\Form\YesNo( 'wr_remove_override', $this->id ? $this->remove_override : TRUE ) );
$form->add( new \IPS\Helpers\Form\Number( 'wr_cheev_point_reduction', $this->cheev_point_reduction ? $this->cheev_point_reduction : 0 ) );
$form->add( new \IPS\Helpers\Form\YesNo( 'wr_cheev_override', $this->id ? $this->remove_override : TRUE ) );
$form->add( new \IPS\Helpers\Form\Editor( 'wr_notes', $this->id ? $this->notes : NULL, FALSE, array( 'app' => 'core', 'key' => 'Modcp', 'autoSaveKey' => "warn-member-default", 'attachIds' => ( $this->id ? array( $this->id, NULL, 'warndefault' ) : NULL ), 'minimize' => 'warn_member_note_placeholder' ) ) );
}
+43 -6
View File
@@ -106,6 +106,12 @@ class _Warning extends \IPS\Content\Item
}
}
}
if ( $this->cheev_point_reduction )
{
$member->achievements_points += $this->cheev_point_reduction;
$consequences['cheev_point_reduction'] = $this->cheev_point_reduction;
}
/* Save */
$member->save();
@@ -283,6 +289,7 @@ class _Warning extends \IPS\Content\Item
$elements[] = new \IPS\Helpers\Form\Select( 'warn_reason', NULL, TRUE, array( 'options' => $reasons ) );
$elements[] = new \IPS\Helpers\Form\Number( 'warn_points', 0, FALSE, array( 'valueToggles' => array( 'warn_remove' ), 'disabled' => ( !$first->points_override ) ) );
$elements[] = new \IPS\Helpers\Form\Date( 'warn_remove', -1, FALSE, array( 'time' => TRUE, 'unlimited' => -1, 'unlimitedLang' => 'never' ), NULL, NULL, NULL, 'warn_remove' );
$elements[] = new \IPS\Helpers\Form\Number( 'warn_cheeve_point_reduction', $first->cheev_point_reduction, FALSE, array( 'disabled' => ( !$first->cheev_override ) ) );
$elements[] = new \IPS\Helpers\Form\Editor( 'warn_member_note', NULL, FALSE, array( 'app' => 'core', 'key' => 'Modcp', 'autoSaveKey' => "warn-member-" . \IPS\Request::i()->id, 'attachIds' => ( $item === NULL ? NULL : array( $item->id, NULL, 'member' ) ), 'minimize' => 'warn_member_note_placeholder' ) );
$elements[] = new \IPS\Helpers\Form\Editor( 'warn_mod_note', NULL, FALSE, array( 'app' => 'core', 'key' => 'Modcp', 'autoSaveKey' => "warn-mod-" . \IPS\Request::i()->id, 'attachIds' => ( $item === NULL ? NULL : array( $item->id, NULL, 'mod' ) ), 'minimize' => 'warn_mod_note_placeholder' ) );
$elements[] = new \IPS\Helpers\Form\CheckboxSet( 'warn_punishment', array(), FALSE, array(
@@ -331,12 +338,14 @@ class _Warning extends \IPS\Content\Item
}, \IPS\Member::loggedIn()->language()->addToStack('until'), NULL, NULL, 'warn_suspend' );
$member = \IPS\Member::load( \IPS\Request::i()->id );
$member = \IPS\Member::load( \IPS\Request::i()->id );
if( $member->temp_ban OR $member->mod_posts OR $member->restrict_post )
{
$elements[] = \IPS\Member::loggedIn()->language()->addToStack('member_existing_penalties', TRUE, array( 'sprintf' => $member->name ) );
}
if( $member->temp_ban OR $member->mod_posts OR $member->restrict_post )
{
$elements[] = \IPS\Member::loggedIn()->language()->addToStack('member_existing_penalties', TRUE, array( 'sprintf' => $member->name ) );
}
\IPS\Member::loggedIn()->language()->words['warn_cheeve_point_reduction_desc'] = \IPS\Member::loggedIn()->language()->addToStack('warn_cheeve_point_reduction__desc', NULL, [ 'sprintf' => [ $member->name, $member->achievements_points, $member->name ] ] );
/* Return */
return $elements;
@@ -357,7 +366,7 @@ class _Warning extends \IPS\Content\Item
{
\IPS\Output::i()->error( 'no_module_permission', '2C150/3', 403, '' );
}
$values = $this->processWarning( $values, \IPS\Member::loggedIn() );
parent::processBeforeCreate( $values );
@@ -396,6 +405,25 @@ class _Warning extends \IPS\Content\Item
}
}
}
if ( $this->cheev_point_reduction )
{
$member->achievements_points -= $this->cheev_point_reduction;
if ( $member->achievements_points >= $this->cheev_point_reduction )
{
/* Eg points to deduct is 50, user has 100 */
$member->achievements_points -= $this->cheev_point_reduction;
}
else
{
/* Eg points to deduct is 50, user has 10, so set points deducted to 10 so undo doesn't add 50 back */
$this->cheev_point_reduction = $member->achievements_points;
}
$consequences['cheev_point_reduction'] = $this->cheev_point_reduction;
}
$member->members_bitoptions['unacknowledged_warnings'] = (bool) \IPS\Settings::i()->warnings_acknowledge;
$member->save();
$member->logHistory( 'core', 'warning', array( 'wid' => $this->id, 'points' => $this->points, 'reason' => $this->reason, 'consequences' => $consequences ) );
@@ -461,6 +489,15 @@ class _Warning extends \IPS\Content\Item
$this->expire_date = $values['warn_remove'];
}
}
if ( ! $reason->cheev_override )
{
$this->cheev_point_reduction = $reason->cheev_point_reduction;
}
else
{
$this->cheev_point_reduction = $values['warn_cheeve_point_reduction'];
}
$this->reason = $values['warn_reason'];
}