Перейти к содержанию

OutOfRangeException: (0) при доступе к профилю пользователя


Рекомендуемые сообщения

Здравствуй,

Я получаю эту ошибку при доступе к профилю пользователя, который выиграл несколько розыгрышей:

OutOfRangeException:  (0)
#0 mydomain.com/public_html/home/applications/raffles/extensions/core/StreamItems/Raffles.php(51): IPS\Patterns\_ActiveRecord::load(4)
#1 mydomain.com/public_html/home/system/Content/Search/Results.php(669): IPS\raffles\extensions\core\StreamItems\_Raffles->extraItems(Object(IPS\Member), 1621474369, NULL)
#2 mydomain.com/public_html/home/applications/core/modules/front/members/profile.php(259): IPS\Content\Search\_Results->addExtraItems(Array, Object(IPS\Member))
#3 mydomain.com/public_html/home/system/Dispatcher/Controller.php(101): IPS\core\modules\front\members\_profile->manage()
#4 mydomain.com/public_html/home/applications/core/modules/front/members/profile.php(73): IPS\Dispatcher\_Controller->execute()
#5 mydomain.com/public_html/home/system/Dispatcher/Dispatcher.php(153): IPS\core\modules\front\members\_profile->execute()
#6 mydomain.com/public_html/home/index.php(13): IPS\_Dispatcher->run()
#7 {main}

Это приложение немного устарело, но в большинстве случаев оно работает нормально. 

Я читал документацию и обнаружил, что:

OutOfRangeException is given if a record with the given ID is not found or if the user does not have permission to view the record.
OutOfRangeException выдается, если запись с данным идентификатором не найдена или если у пользователя нет разрешения на просмотр записи.

Я не вижу ничего плохого в параметрах. Вот файл:

Spoiler

<?php
/**
 * @brief        Activity stream items extension: Raffles
 * @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
 * @subpackage    Raffles
 * @since        23 Jun 2017
 */

namespace IPS\raffles\extensions\core\StreamItems;

/* 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;
}

/**
 * @brief    Activity stream items extension: Raffles
 */
class _Raffles
{    
    /**
     * Is there content to display?
     *
     * @param    \IPS\Member|NULL    $author        The author to limit extra items to
     * @param    Timestamp|NULL    $lastTime    If provided, only items since this date are included. If NULL, it works out which to include based on what results are being shown
     * @param    Timestamp|NULL    $firstTime    If provided, only items before this date are included. If NULL, it works out which to include based on what results are being shown
     * @return    array Array of \IPS\Content\Search\Result\Custom objects
     */
    public function extraItems( $author=NULL, $lastTime=NULL, $firstTime=NULL )
    {
        $entries     = array();
        $where         = array( array( 'rw_date>?', $lastTime ) );

        if ( $firstTime )
        {
            $where[] = array( 'rw_date<?', $firstTime );
        }

        if ( $author )
        {
            $where[] = array( 'raffles_winners.rw_member_id=?', $author->member_id );
        }

        foreach ( \IPS\Db::i()->select( '*', 'raffles_winners', $where, 'rw_date DESC', 10 ) as $row )
        {
            $raffle        = \IPS\raffles\Raffle::load( $row[ 'rw_raffle_id' ] );
            $position     = \IPS\Member::loggedIn()->language()->addToStack( 'rafffle_winner_' . $row['rw_prize_position'] );

             switch( $raffle->type )
             {
                case 'raffle':
                    $type = \IPS\Member::loggedIn()->language()->addToStack( 'new_raffle' );
                break;
                case 'giveaway':
                    $type = \IPS\Member::loggedIn()->language()->addToStack( 'new_giveaway' );
                break;
            }

            $member     = \IPS\Member::load( $row['rw_member_id'] );
            $entries[]     = new \IPS\Content\Search\Result\Custom( \IPS\DateTime::ts( $row['rw_date'] ), \IPS\Member::loggedIn()->language()->addToStack( 'activity_raffle_completed', FALSE, array( 'htmlsprintf' => array( \IPS\Theme::i()->getTemplate( 'global', 'core', 'front' )->userLink( $member ), $position, $type, $raffle->url(), $raffle->title ) ) ) );
        }

        /* Return */
        if ( !empty( $entries ) )
        {
            return $entries;
        }

        return array();
    }
}

Вот база данных:

image.png.fe678244d0d91f746655b0d3c2b288b1.png

В этом случае это происходит с memberid 1. Розыгрыши, которые отображаются в базе данных, уже удалены.

Кто-нибудь знает, что вызывает это?

Спасибо!

Изменено пользователем BlackShot
Ссылка на комментарий
Поделиться на другие сайты

6 минут назад, BlackShot сказал:

Вот база данных:

Ты смотришь на таблицу raffles_winners, а нужно открыть raffles_raffles (может быть иначе), где хранятся сами raffles. Там окажется, что записи с id4 не будет.

Ссылка на комментарий
Поделиться на другие сайты

17 minutes ago, Respected said:

Ты смотришь на таблицу raffles_winners, а нужно открыть raffles_raffles (может быть иначе), где хранятся сами raffles. Там окажется, что записи с id4 не будет.

Думаю, вы разобрались! А название стола - в точности raffles_raffles. Не могли бы вы рассказать мне, как добавить этот фрагмент кода? 

Вот данные raffles_raffles:

image.thumb.png.74b6d432b4a123eb34800d6c1f9b7e2f.png

Ссылка на комментарий
Поделиться на другие сайты

Не надо ничего добавлять..

$raffle = \IPS\raffles\Raffle::load( $row[ 'rw_raffle_id' ] ); - ошибка, если значение не найдено в таблице, поэтому самый простой способ - удалить записи с неверными ID.

Увидели ошибку, выполнили SQL
DELETE FROM raffles_winners where rw_raffle_id=4;

номер взять из сообщения об ошибке (...IPS\Patterns\_ActiveRecord::load(4))

Изменено пользователем Desti
Ссылка на комментарий
Поделиться на другие сайты

4 minutes ago, Desti said:

Не надо ничего добавлять..

$raffle = \IPS\raffles\Raffle::load( $row[ 'rw_raffle_id' ] ); - ошибка, если значение не найдено в таблице, поэтому самый простой способ - удалить записи с неверными ID.

Увидели ошибку, выполнили SQL
DELETE FROM raffles_winners where rw_raffle_id=4;

номер взять из сообщения об ошибке (...IPS\Patterns\_ActiveRecord::load(4))

Думаю, автор забыл добавить команду удаления победителей при удалении розыгрыша/raffle.

Удаление вручную работает, но мне нужно добавить фрагмент кода, чтобы либо удалить записи raffles_winners, либо игнорировать недопустимые строки. Правильно?

Spoiler

<?php

namespace IPS\raffles;

/* 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;
}

class _Raffle extends \IPS\Content\Item implements
\IPS\Content\Permissions,
\IPS\Content\Tags,
\IPS\Content\Followable,
\IPS\Content\ReadMarkers,
\IPS\Content\Views,
\IPS\Content\Hideable,
\IPS\Content\Featurable,
\IPS\Content\Pinnable,
\IPS\Content\Lockable,
\IPS\Content\Shareable,
\IPS\Content\Ratings,
\IPS\Content\Searchable,
\IPS\Content\Embeddable,
\IPS\Content\FuturePublishing,
\IPS\Content\MetaData
{
     use \IPS\Content\Reactable, \IPS\Content\Reportable, \IPS\Content\ItemTopic;

    public static $application = 'raffles';
    public static $module = 'raffles';
    public static $databaseTable = 'raffles_raffles';
    public static $databasePrefix = 'raffle_';
    protected static $multitons;
    public static $containerNodeClass = 'IPS\raffles\Category';
    public static $commentClass = 'IPS\raffles\Raffle\Comment';
    public static $reviewClass = 'IPS\raffles\Raffle\Review';
    public static $coverPhotoDefault = true;

    public static $databaseColumnMap = array(
        'container'                => 'cat',
        'author'                => 'mid',
        'views'                    => 'views',
        'title'                    => 'title',
        'content'                => 'description',
        'num_comments'            => 'comments',
        'unapproved_comments'    => 'unapproved_comments',
        'hidden_comments'        => 'hidden_comments',
        'last_comment'            => 'last_comment',
        'num_reviews'            => 'reviews',
        'unapproved_reviews'    => 'unapproved_reviews',
        'hidden_reviews'        => 'hidden_reviews',
        'last_review'            => 'last_review',
        'date'                    => 'submitted',
        'updated'                => 'updated',
        'rating'                => 'rating',
        'approved'                => 'open',
        'approved_date'            => 'approvedon',
        'pinned'                => 'pinned',
        'featured'                => 'featured',
        'locked'                => 'locked',
        'ip_address'            => 'ipaddress',
        'is_future_entry'        => 'is_future_entry',
        'future_date'           => 'publish_date',
        'status'                => 'status',
        'meta_data'                => 'meta_data',
    );

    public static $title = 'raffles_raffle';
    public static $icon = 'ticket';
    public $tableHoverUrl = TRUE;
    public static $formLangPrefix = 'raffle_';
    public static $reputationType = 'raffle_id';
    public static $hideLogKey = 'raffles-raffle';
    public static $ownerTypes = array( 'member' => 'raffle_mid' );

    public static function basicDataColumns()
    {
        $return = parent::basicDataColumns();
        $return[] = 'raffle_image';
        $return[] = 'raffle_thumb';
        $return[] = 'raffle_type';
        $return[] = 'raffle_tickets';
        $return[] = 'raffle_participants';
        $return[] = 'raffle_datelimit';
        return $return;
    }

    public function set_title( $title )
    {
        $this->_data['title'] = $title;
        $this->_data['title_seo'] = \IPS\Http\Url\Friendly::seoTitle( $title );
    }

    public function get_title_seo()
    {
        if( !$this->_data['title_seo'] )
        {
            $this->title_seo    = \IPS\Http\Url\Friendly::seoTitle( $this->title );
            $this->save();
        }

        return $this->_data['title_seo'] ?: \IPS\Http\Url\Friendly::seoTitle( $this->title );
    }

    protected $_url    = array();
    public static $urlBase = 'app=raffles&module=raffles&controller=view&id=';
    public static $urlTemplate = 'raffles_raffle';
    public static $seoTitleColumn = 'title_seo';

    public function lastCommentPageUrl()
    {
        return parent::lastCommentPageUrl()->setQueryString( 'tab', 'comments' );
    }

    public static function getCommentsPerPage()
    {
        return \IPS\Settings::i()->raffles_display_comments;
    }

    public function lastReviewPageUrl()
    {
        return parent::lastCommentPageUrl()->setQueryString( 'tab', 'reviews' );
    }

    public static function contentTableTemplate()
    {
        return array( \IPS\Theme::i()->getTemplate( 'browse', 'raffles' ), 'rows' );
    }

    public static function manageFollowRows()
    {        
        return array( \IPS\Theme::i()->getTemplate( 'global', 'raffles', 'front' ), 'manageFollowRow' );
    }

    public function customFields( $topic = FALSE )
    {
        $return = array();
        $fields = $this->container()->cfields;

        if( $topic === TRUE )
        {
            $fieldData    = iterator_to_array( \IPS\Db::i()->select( 'cf_id, cf_format', 'raffles_cfields', array( 'cf_topic=?', 1 ) )->setKeyField( 'cf_id' )->setValueField( 'cf_format' ) );
        }

        try
        {
            $data = \IPS\Db::i()->select( '*', 'raffles_ccontent', array( 'raffle_id=?', $this->id ) )->first();
            
            foreach ( $data as $k => $v )
            {
                if( $topic === TRUE and !isset( $fieldData[ str_replace( 'field_', '', $k ) ] ) )
                {
                    continue;
                }

                if ( array_key_exists( str_replace( 'field_', '', $k ), $fields ) )
                {
                    if( $topic === TRUE )
                    {
                        if( isset( $fieldData[ str_replace( 'field_', '', $k ) ] ) )
                        {
                            $v    = str_replace( '{content}', htmlspecialchars( $v, \IPS\HTMLENTITIES, 'UTF-8', FALSE ), $fieldData[ str_replace( 'field_', '', $k ) ] );
                            $v    = str_replace( '{member_id}', \IPS\Member::loggedIn()->member_id, $v );
                            $v    = str_replace( '{title}', \IPS\Member::loggedIn()->language()->addToStack( 'raffles_field_' . str_replace( 'field_', '', $k ) ), $v );
                        }
                        else
                        {
                            $v    = htmlspecialchars( $v, \IPS\HTMLENTITIES, 'UTF-8', FALSE );
                        }
                    }

                    $return[ $k ] = $v;
                }
            }
        }
        catch( \UnderflowException $e ){}
        
        return $return;
    }

    public function rafflesViewTabs()
    {
        $tabs = array();
        if ( $this->container()->allowcomments )
        {
            $tabs['comments'] = \IPS\Member::loggedIn()->language()->pluralize( \IPS\Member::loggedIn()->language()->get( 'raffle_comment_count' ), array( $this->mapped('num_comments') ) );
        }
        if ( $this->container()->allowreviews )
        {
            $tabs['reviews'] = \IPS\Member::loggedIn()->language()->pluralize( \IPS\Member::loggedIn()->language()->get( 'raffle_review_count' ), array( $this->mapped('num_reviews') ) );
        }
                
        return $tabs;
    }

    public function rafflesTabs( $tab )
    {
        if ( $tab === 'reviews' )
        {
            return \IPS\Theme::i()->getTemplate('view')->reviews( $this );
        }
        elseif( $tab === 'comments' )
        {
            return \IPS\Theme::i()->getTemplate('view')->comments( $this );
        }
        
        return '';
    }
    
    public static function moderateNewItems( \IPS\Member $member, \IPS\Node\Model $container = NULL, $considerPostBeforeRegistering = false )
    {
        if ( $container and $container->newmoderated and !$member->group['g_avoid_q'] )
        {
            return TRUE;
        }
        
        return parent::moderateNewItems( $member, $container );
    }
    
    public function moderateNewComments( \IPS\Member $member, $considerPostBeforeRegistering = false )
    {
        $commentClass = static::$commentClass;
        return ( $this->container()->comments_moderated and !$member->group['g_avoid_q'] ) or parent::moderateNewComments( $member );
    }

    public function moderateNewReviews( \IPS\Member $member, $considerPostBeforeRegistering = false )
    {
        return ( $this->container()->reviews_moderated and !$member->group['g_avoid_q'] ) or parent::moderateNewReviews( $member );
    }
    
    public function canView( $member=NULL )
    {
        $member = $member ?: \IPS\Member::loggedIn();
        $return = parent::canView( $member );

        if ( $this->status == 'draft' AND !static::canViewHiddenItems( $member, $this->container() ) AND $member->member_id != $this->author()->member_id )
        {
            $return = FALSE;
        }
        
        if ( $this->status == 'draft' AND $this->is_future_entry == 1 AND $member->member_id == $this->author()->member_id )
        {
            $return = TRUE;
        }

        return $return;
    }
    
    public function canEdit( $member=NULL )
    {
        $member = $member ?: \IPS\Member::loggedIn();

        if ( !$member->member_id )
        {
            return FALSE;
        }

        return ( $member->member_id == $this->author()->member_id ) or parent::canEdit( $member );
    }

    public static function getItemsWithPermission( $where=array(), $order=NULL, $limit=10, $permissionKey='read', $includeHiddenItems=\IPS\Content\Hideable::FILTER_AUTOMATIC, $queryFlags=0, \IPS\Member $member=NULL, $joinContainer=FALSE, $joinComments=FALSE, $joinReviews=FALSE, $countOnly=FALSE, $joins=NULL, $skipPermission=FALSE, $joinTags=TRUE, $joinAuthor=TRUE, $joinLastCommenter=TRUE, $showMovedLinks=FALSE )
    {
        $member = $member ?: \IPS\Member::loggedIn();

        if ( !$member->isAdmin() )
        {
            $where[] = array( 'raffles_categories.rc_open=1' );
        }

        $joinContainer = TRUE;

        return parent::getItemsWithPermission( $where, $order, $limit, $permissionKey, $includeHiddenItems, $queryFlags, $member, $joinContainer, $joinComments, $joinReviews, $countOnly, $joins, $skipPermission, $joinTags, $joinAuthor, $joinLastCommenter, $showMovedLinks );
    }

    public static function canCreate( \IPS\Member $member, \IPS\Node\Model $container=NULL, $showError=FALSE )
    {
        $data = \IPS\raffles\Members::getMemberData( $member->member_id );
        if( $member->member_id AND !$data['raffles_submit'] )
        {
            if ( $showError )
            {
                \IPS\Output::i()->error( 'raffle_error_submissions_blocked', 'RAFFLE-CREATE RAFFLE/1', 403, '' );
            }

            return FALSE;
        }

        if( $member->group['g_raffle_rafflespertime'] > 0 )
        {
            switch ( $member->group['g_raffle_rafflespertime_period'] )
            {
                case 'D':
                    $unit = time() - 86400;
                    $name = \IPS\Member::loggedIn()->language()->addToStack('raffle_day');
                break;
                case 'W':
                    $unit = time() - 604800;
                    $name = \IPS\Member::loggedIn()->language()->addToStack('raffle_week');
                break;
                case 'M':
                    $unit = time() - 2592000;
                    $name = \IPS\Member::loggedIn()->language()->addToStack('raffle_month');
                break;
                case 'Y':
                    $unit = time() - 217728000;
                    $name = \IPS\Member::loggedIn()->language()->addToStack('raffle_year');
                break;
            }

            $raffles = \IPS\Db::i()->select( 'count(*)', 'raffles_raffles', array( "raffle_mid=? AND raffle_submitted>?", \IPS\Member::loggedIn()->member_id, $unit ) )->first();

            if ( $raffles >= $member->group['g_raffle_rafflespertime'] )
            {
                $msg = \IPS\Member::loggedIn()->language()->addToStack('raffle_err_submissions_restriction_period', FALSE, array( 'sprintf' => array( $member->group['g_raffle_rafflespertime'], $name ) ) );

                if ( $showError )
                {
                    \IPS\Output::i()->error( $msg, 'RAFFLE-CREATE RAFFLE/2', 403, '' );
                }
                
                return FALSE;
            }
        }

        return parent::canCreate( $member, $container, $showError );
    }

    public function canReview( $member = NULL, $considerPostBeforeRegistering = true )
    {
        return parent::canReview( $member );
    }

    public function changeAuthor( \IPS\Member $newAuthor, $log=true )
    {
        if ( \IPS\Application::appIsEnabled( 'forums' ) )
        {
            if ( $topic = $this->topic() )
            {
                $topic->changeAuthor( $newAuthor );
            }
        }

        parent::changeAuthor( $newAuthor );
    }

    public static function formElements( $item=NULL, \IPS\Node\Model $container=NULL )
    {
        $return = parent::formElements( $item, $container );

        $return['title'] = new \IPS\Helpers\Form\Text( "raffle_title", $item ? $item->title : NULL, TRUE, array( 'minLength' => \IPS\Settings::i()->raffle_min_title_length, 'maxLength' =>  \IPS\Settings::i()->raffle_max_title_length ) );

        if( \IPS\Request::i()->do == 'submit' )
        {
            $options = array();
            $types = json_decode( $container->raffles_type, TRUE );
            if( $types['raffle'] )
            {
                $options[ 'raffle' ] = 'rc_raffles_type_raffles';
            }
            if( $types['giveaway'] )
            {
                $options[ 'giveaway' ] = 'rc_raffles_type_giveaways';
            }

            if( \count( $options ) > 1 )
            {
                $return['type'] = new \IPS\Helpers\Form\Radio( 'raffle_type', $item ? $this->type : NULL, TRUE, array( 'options' => $options, 'toggles' => array( 'raffle' => array( 'raffle_price', 'raffle_payment_type', 'raffle_points_required', 'raffle_restriction_tickets' ) ) ) );
            }
            else
            {
                foreach( $options as $id => $lang )
                {
                    $type = $id;
                }
            }

            $paymentOptions = array();
            $paymentTypes   = json_decode( $container->payment_type, TRUE );
            if( \IPS\Application::appIsEnabled( 'nexus' ) AND $paymentTypes['money'] )
            {
                $paymentOptions[ 'money' ] = 'raffle_payment_type_money';
            }
            if( \IPS\Application::appIsEnabled( 'membersshop' ) AND $paymentTypes['points'] AND \IPS\Application::load( 'membersshop' )->long_version >= 11003 AND \IPS\Settings::i()->raffle_membersshop_onoff )
            {
                $paymentOptions[ 'points' ] = 'raffle_payment_type_points';
            }

            if( \count( $paymentOptions ) > 1 )
            {
                $toggles = array( 'money' => array( 'raffle_price' ), 'points' => array( 'raffle_points_required' ) );
                $return['payment_type'] = new \IPS\Helpers\Form\Radio( 'raffle_payment_type', NULL, FALSE, array( 'options' => $paymentOptions, 'toggles' => $toggles ), NULL, NULL, NULL, 'raffle_payment_type' );            
            }

            if( isset( $paymentOptions[ 'money' ] ) AND $paymentOptions[ 'money' ] AND \count( $options ) > 1 OR $type == 'raffle' )
            {
                $return['price'] = new \IPS\nexus\Form\Money( 'raffle_price', $item ? json_decode( $item->price, TRUE ) : 0, NULL, array(), function( $val )
                {
                    if( \IPS\Request::i()->raffle_type == 'raffle' AND ( isset( \IPS\Request::i()->raffle_payment_type ) AND \IPS\Request::i()->raffle_payment_type === 'money' AND !$val ) OR ( !isset( \IPS\Request::i()->raffle_payment_type ) AND !$val ) )
                    {
                        throw new \DomainException('form_required');
                    }

                    if( \IPS\Request::i()->raffle_payment_type === 'money' AND \IPS\Settings::i()->raffle_force_fill_price_currencies )
                    {
                        echo time();exit;
                        foreach( \IPS\nexus\Money::currencies() as $currency )
                        {
                            if( !isset( $val[ $currency ]->currency, $currency ) )
                            {
                                throw new \DomainException('raffle_invalid_price2');
                            }

                            if( $val[ $currency ]->amount->isZero() OR !$val[ $currency ]->amount->isPositive() )
                            {
                                throw new \DomainException('raffle_invalid_price1');
                            }
                        }
                    }
                }, NULL, NULL, 'raffle_price' );

                $priceCaption = NULL;
                $fees = NULL;
                if ( $_fees = json_decode( \IPS\Settings::i()->raffle_transfee, TRUE ) )
                {
                    $fees = array();
                    foreach ( $_fees as $fee )
                    {
                        $fees[] = (string) ( new \IPS\nexus\Money( $fee['amount'], $fee['currency'] ) );
                    }
                    $fees = \IPS\Member::loggedIn()->language()->formatList( $fees, \IPS\Member::loggedIn()->language()->get('or_list_format') );
                }

                if ( \IPS\Settings::i()->raffle_percent and $fees )
                {
                    $priceCaption = \IPS\Member::loggedIn()->language()->addToStack( 'raffle_price_desc_both', FALSE, array( 'sprintf' => array( \IPS\Settings::i()->raffle_percent, $fees ) ) );
                }
                elseif ( \IPS\Settings::i()->raffle_percent )
                {
                    $priceCaption = \IPS\Member::loggedIn()->language()->addToStack('raffle_price_desc_percent', FALSE, array( 'sprintf' => \IPS\Settings::i()->raffle_percent ) );
                }
                elseif ( $fees )
                {
                    $priceCaption = \IPS\Member::loggedIn()->language()->addToStack('raffle_price_desc_fee', FALSE, array( 'sprintf' => $fees ) );
                }
        
                \IPS\Member::loggedIn()->language()->words['raffle_price_desc'] = $priceCaption;
            }

            if( isset( $paymentOptions[ 'points' ] ) AND $paymentOptions[ 'points' ] )
            {
                $return['points'] = new \IPS\Helpers\Form\Number( 'raffle_points_required', $item ? $item->points_required : 1, NULL, array( 'min' => 1 ), NULL, NULL, NULL, 'raffle_points_required' );
            }
        }

        $return['datelimit'] = new \IPS\Helpers\Form\Date( 'raffle_datelimit', ( $item ) ? ( $item->datelimit ? \IPS\DateTime::ts( $item->datelimit ) : 0 ) : 0, TRUE, array( 'time' => TRUE ) );

        $return['description']     = new \IPS\Helpers\Form\Editor( 'raffle_description', ( $item ) ? $item->description : NULL, TRUE, 
            array(
                'app' => 'raffles', 
                'key' => 'Raffles', 
                'autoSaveKey' => 'raffles-new-raffle', 
                'attachIds' => ( $item === NULL ? NULL : array( $item->id ) ) 
        ), function ( $val )
           {
                if( mb_strlen( trim( strip_tags( $val ) ) ) < \IPS\Settings::i()->raffle_min_description_length )
                {
                    $msg = \IPS\Member::loggedIn()->language()->addToStack('raffle_err_content_length', FALSE, array( 'sprintf' => \IPS\Settings::i()->raffle_min_description_length ) );
                    throw new \InvalidArgumentException( $msg );
                }
            }
        );

        $customFieldValues     = $item ? $item->customFields() : array();
        foreach ( $container->cfields as $k => $field )
        {
            $return[] = $field->buildHelper( isset( $customFieldValues[ "field_{$k}" ] ) ? $customFieldValues[ "field_{$k}" ] : NULL );
        }

        $return['image'] = new \IPS\Helpers\Form\Upload( 'raffle_image', $item ? \IPS\File::get( 'raffles_Image', $item->image ) : NULL, TRUE, array( 'multiple' => FALSE, 'image' => TRUE, 'storageExtension' => 'raffles_Image' ) );

        if( \IPS\Request::i()->do == 'submit' )
        {
            $modOptions = array();
            $toggles = array();

            if ( static::modPermission( 'lock', NULL, $container ) )
            {
                $modOptions['lock'] = 'create_raffle_locked';
                $toggles['lock'] = array( 'create_raffle_locked' );
            }

            if ( static::modPermission( 'pin', NULL, $container ) )
            {
                $modOptions['pin'] = 'create_raffle_pinned';
                $toggles['pin'] = array( 'create_raffle_pinned' );
            }

            if ( static::modPermission( 'hide', NULL, $container ) )
            {
                $modOptions['hide'] = 'create_raffle_hidden';
                $toggles['hide'] = array( 'create_raffle_hidden' );
            }

            if ( static::modPermission( 'feature', NULL, $container ) )
            {
                $modOptions['feature'] = 'create_raffle_featured';
                $toggles['feature'] = array( 'create_raffle_featured' );
            }

            if ( \count( $modOptions ) or \count ( $toggles ) )
            {
                $return['raffle_state'] = new \IPS\Helpers\Form\CheckboxSet( 'raffle_create_state', array(), FALSE, array(
                    'options'     => $modOptions,
                    'toggles'    => $toggles,
                    'multiple'    => TRUE
                ) );    
            }
        }

        if( \IPS\Request::i()->do == "submit" AND ( isset( $type ) AND $type == 'raffle' OR \count( $options ) > 1 ) OR ( \IPS\Request::i()->do == "edit" AND $item->type == 'raffle' ) )
        {
            $return['tickets']     = new \IPS\Helpers\Form\Number( 'raffle_restriction_tickets', $item ? $item->restriction_tickets : 1, FALSE, array( 'min' => 1, 'unlimited' => -1, 'unlimitedLang' => 'no_restriction' ), NULL, NULL, NULL, 'raffle_restriction_tickets' );
        }

        $return['users']     = new \IPS\Helpers\Form\Number( 'raffle_restriction_users', $item ? $item->restriction_users : 0, FALSE, array( 'unlimited' => 0, 'unlimitedLang' => 'no_restriction', 'min' => $item ? $item->totalParticipants() : 0 ), NULL, NULL, NULL );

        if( \IPS\Request::i()->do == "submit" OR ( \IPS\Request::i()->do == "edit" AND $item->getParticipantsCount() ) )
        {
            $return['posts']     = new \IPS\Helpers\Form\Number( 'raffle_restriction_posts', $item ? $item->restriction_posts : 0, FALSE, array( 'unlimited' => 0, 'unlimitedLang' => 'no_restriction' ), NULL, NULL, NULL );
            $return['rep']         = new \IPS\Helpers\Form\Number( 'raffle_restriction_reppoints', $item ? $item->restriction_reppoints : 0, FALSE, array( 'unlimited' => 0, 'unlimitedLang' => 'no_restriction' ), NULL, NULL, NULL );
            $return['joined']    = new \IPS\Helpers\Form\Number( 'raffle_restriction_daysjoined', $item ? $item->restriction_daysjoined : 0, FALSE, array( 'unlimited' => 0, 'unlimitedLang' => 'no_restriction' ), NULL, NULL, NULL );
            $return['age']        = new \IPS\Helpers\Form\Number( 'raffle_restriction_age', $item ? $item->restriction_age : 0, FALSE, array( 'min' => 16, 'unlimited' => 0, 'unlimitedLang' => 'no_restriction' ), NULL, NULL, NULL );

            if ( $item )
            {
                if ( $item->restriction_groups === '*' )
                {
                    $group = '*';
                }
                else
                {
                    $group = explode( ',', $item->restriction_groups );
                }
            }
            else
            {
                $group = '*';
            }
    
            $return['groups']    = new \IPS\Helpers\Form\Select( 'raffle_restriction_groups', $group, FALSE, array( 'options' => \IPS\Member\Group::groups( TRUE, FALSE ), 'parse' => 'normal', 'multiple' => TRUE, 'unlimited' => '*', 'unlimitedLang' => 'all_groups' ) );
        }

        $return['publish'] = new \IPS\Helpers\Form\YesNo( 'raffle_publish', $item ? $item->status : TRUE, FALSE, array( 'togglesOn' => array( 'raffle_date' ) ) );

        $date = NULL;
        if ( isset( $return['date'] ) )
        {
            $date = $return['date'];
            unset( $return['date'] );

            $return['date'] = $date;
        }

        if ( isset( $return['auto_follow'] ) )
        {
            $autofollow = $return['auto_follow'];
            unset( $return['auto_follow'] );
            $return['auto_follow'] = $autofollow;
        }

        return $return;
    }

    public function processForm( $values )
    {
        parent::processForm( $values );

        $this->description             = $values['raffle_description'];
        $this->image                 = (string) $values['raffle_image'];
        $this->datelimit             = $values['raffle_datelimit']->getTimestamp();

        if( \IPS\Request::i()->do == 'submit' )
        {
            $types = json_decode( $this->container()->raffles_type, TRUE );
            if( $types['raffle'] )
            {
                $options[ 'raffle' ] = 'rc_raffles_type_raffles';
            }
            if( $types['giveaway'] )
            {
                $options[ 'giveaway' ] = 'rc_raffles_type_giveaways';
            }

            if( \count( $options ) > 1 )
            {
                $type = $values['raffle_type'];
            }
            else
            {
                foreach( $options as $id => $lang )
                {
                    $type = $id;
                }
            }

            $this->type    = $type;

            if( $type === 'raffle' )
            {
                $paymentOptions = array();
                $paymentTypes   = json_decode( $this->container()->payment_type, TRUE );
                if( isset( $paymentTypes['money'] ) AND $paymentTypes['money'] )
                {
                    $paymentOptions[ 'money' ] = 'raffle_payment_type_money';
                }
                if( isset( $paymentTypes['points'] ) AND $paymentTypes['points'] AND \IPS\Application::appIsEnabled( 'membersshop' ) AND \IPS\Application::load( 'membersshop' )->long_version >= 11003 AND \IPS\Settings::i()->raffle_membersshop_onoff )
                {
                    $paymentOptions[ 'points' ] = 'raffle_payment_type_points';
                }

                if( \count( $paymentOptions ) > 1 )
                {
                    $this->payment_type = $values['raffle_payment_type'];
                    if( $values['raffle_payment_type'] == 'money' )
                    {
                        $this->payment_type     = 'money';
                        $this->price             = json_encode( $values['raffle_price'] );
                        $this->points_required     = 0;
                    }
                    else
                    {
                        $this->payment_type     = 'points';
                        $this->price             = '[]';
                        $this->points_required     = $values['raffle_points_required'];
                    }
                }
                else
                {
                    if( $paymentOptions[ 'money' ] )
                    {
                        $this->payment_type     = 'money';
                        $this->price             = json_encode( $values['raffle_price'] );
                        $this->points_required     = 0;
                    }
                    else
                    {
                        $this->payment_type     = 'points';
                        $this->price             = '[]';
                        $this->points_required     = $values['raffle_points_required'];
                    }
                }
            }
            else
            {
                $this->price             = '[]';
                $this->payment_type     = NULL;
                $this->points_required     = 0;
            }
        }

        if( isset( $values['raffle_price'] ) AND $values['raffle_price'] )
        {
            foreach( $values['raffle_price'] as $currency => $currencyDetails )
            {
                if( \IPS\Db::i()->checkForColumn( 'raffles_raffles', "raffle_{$currency}" ) )
                {
                    $this->$currency = $currencyDetails->amount;
                }
            }
        }

        if( isset( $values['raffle_restriction_tickets'] ) )
        {
            $this->restriction_tickets = $values['raffle_restriction_tickets'];
        }
        else
        {
            $this->restriction_tickets = 1;
        }

        $this->restriction_users = $values['raffle_restriction_users'];

        if( isset( $values['raffle_restriction_posts'] ) )
        {
            $this->restriction_posts = $values['raffle_restriction_posts'];
        }

        if( isset( $values['raffle_restriction_reppoints'] ) )
        {
            $this->restriction_reppoints = $values['raffle_restriction_reppoints'];
        }

        if( isset( $values['raffle_restriction_daysjoined'] ) )
        {
            $this->restriction_daysjoined = $values['raffle_restriction_daysjoined'];
        }

        if( isset( $values['raffle_restriction_age'] ) )
        {
            $this->restriction_age = $values['raffle_restriction_age'];    
        }

        if( isset( $values['raffle_restriction_groups'] ) )
        {
            $this->restriction_groups = $values['raffle_restriction_groups'] !== '*' ? implode( ',', $values['raffle_restriction_groups'] ) : '*';
        }

        $this->status = $values['raffle_publish'] ? 'published' : 'draft';

        if( isset( $values['raffle_date'] ) )
        {
            $this->submitted = ( $values['raffle_date'] AND $values['raffle_publish'] ) ? $values['raffle_date']->getTimestamp() : time();
        }

        if ( $this->submitted > time() )
        {
            $this->status = 'draft';
        }

        if ( isset( $values['raffle_create_state'] ) )
        {
            if ( \in_array( 'lock', $values['raffle_create_state'] ) )
            {
                $this->locked = 1;    
            }

            if ( \in_array( 'hide', $values['raffle_create_state'] ) )
            {
                $this->open = 0;
            }

            if ( \in_array( 'pin', $values['raffle_create_state'] ) )
            {
                $this->pinned = 1;
            }

            if ( \in_array( 'feature', $values['raffle_create_state'] ) )
            {
                $this->featured = 1;
            }
        }

        $this->save();

        $cfields = array();
        foreach ( $this->container()->cfields as $field )
        {
            $helper    = $field->buildHelper();
            if ( $helper instanceof \IPS\Helpers\Form\Upload )
            {
                $cfields[ "field_{$field->id}" ] = (string) $values[ "raffles_field_{$field->id}" ];
            }
            else
            {
                $cfields[ "field_{$field->id}" ] = $helper::stringValue( $values[ "raffles_field_{$field->id}" ] );
            }

            if ( $helper instanceof \IPS\Helpers\Form\Editor )
            {
                $field->claimAttachments( $this->id );
            }
        }

        if ( !empty( $cfields ) )
        {
            \IPS\Db::i()->insert( 'raffles_ccontent', array_merge( array( 'raffle_id' => $this->id, 'updated' => time() ), $cfields ), TRUE );
        }

        $this->container()->setLastRaffle();
        $this->container()->save();

        \IPS\File::claimAttachments( 'raffles-new-raffle', $this->id );
    }
    
    protected function processAfterCreate( $comment, $values )
    {
        try
        {
            $original = \IPS\File::get( 'raffles_Image', $this->image );
            \IPS\Db::i()->update( 'raffles_raffles', array( 'raffle_thumb' => (string) $original->thumbnail( 'raffles_Image' ) ), array( 'raffle_id=?', $this->id ) );
            $this->save();
        }
        catch( \Exception $e ){}

        parent::processAfterCreate( $comment, $values );

        if ( $this->status == 'published' )
        {
            $category                    = $this->container();
            $category->last_raffle_id     = $this->id;
            $category->last_raffle_date    = time();
            $category->save();
        }
    }

    public function processAfterEdit( $values )
    {
        if ( \IPS\Application::appIsEnabled('forums') and $this->topic() )
        {
            $this->syncTopic();
        }

        parent::processAfterEdit( $values );

        $this->updated = time();
        $this->save();
        
        try
        {
            $original = \IPS\File::get( 'raffles_Image', $this->image );
            \IPS\Db::i()->update( 'raffles_raffles', array( 'raffle_thumb' => (string) $original->thumbnail( 'raffles_Image' ) ), array( 'raffle_id=?', $this->id ) );
            $this->save();
        }
        catch( \Exception $e ){}
    }

    public function logDelete( $member = NULL )
    {
        parent::logDelete( $member );

        if ( $topic = $this->topic() and $this->container()->delete_topic )
        {
            $topic->logDelete( $member );
        }
    }

    public function delete()
    {
        if ( $topic = $this->topic() and $this->container()->delete_topic )
        {
            $topic->delete();
        }

        parent::delete();

        foreach ( new \IPS\File\Iterator( \IPS\Db::i()->select( 'raffle_image', 'raffles_raffles', array( 'raffle_id=?', $this->id ) ), 'raffles_Image' ) as $file )
        {
            try
            {
                $file->delete();
            }
            catch ( \Exception $e ) { }
        }

        foreach ( new \IPS\File\Iterator( \IPS\Db::i()->select( 'raffle_thumb', 'raffles_raffles', array( 'raffle_id=? AND raffle_thumb IS NOT NULL', $this->id ) ), 'raffles_Image' ) as $file )
        {
            try
            {
                $file->delete();
            }
            catch ( \Exception $e ) { }
        }

        foreach ( new \IPS\File\Iterator( \IPS\Db::i()->select( 'prize_image', 'raffles_prizes', array( 'prize_raffle_id=?', $this->id ) ), 'raffles_Prize' ) as $file )
        {
            try
            {
                $file->delete();
            }
            catch ( \Exception $e ) { }
        }

        foreach ( new \IPS\File\Iterator( \IPS\Db::i()->select( 'prize_thumbnail', 'raffles_prizes', array( 'prize_raffle_id=?', $this->id ) ), 'raffles_Prize' ) as $file )
        {
            try
            {
                $file->delete();
            }
            catch ( \Exception $e ) { }
        }

        \IPS\Db::i()->delete( 'raffles_ccontent', array( 'raffle_id=?', $this->id ) );
        \IPS\Db::i()->delete( 'raffles_participants', array( 'rp_raffle_id=?', $this->id ) );
        \IPS\Db::i()->delete( 'raffles_prizes', array( 'prize_raffle_id=?', $this->id ) );

        $this->container()->setLastRaffle();
        $this->container()->save();
    }

    public static function canTag( \IPS\Member $member = NULL, \IPS\Node\Model $container = NULL )
    {
        return parent::canTag( $member, $container ) and ( $container === NULL or !$container->tags_disabled );
    }
    
    public static function canPrefix( \IPS\Member $member = NULL, \IPS\Node\Model $container = NULL )
    {
        return parent::canPrefix( $member, $container ) and ( $container === NULL or !$container->tags_noprefixes );
    }
    
    public static function definedTags( \IPS\Node\Model $container = NULL )
    {
        if ( $container and $container->tags_predefined )
        {
            return explode( ',', $container->tags_predefined );
        }
        
        return parent::definedTags( $container );
    }

    public static function supportsComments( \IPS\Member $member = NULL, \IPS\Node\Model $container = NULL )
    {        
        if( $container !== NULL )
        {
            return parent::supportsComments() and $container->allowcomments AND ( !$member or $container->can( 'read', $member ) );
        }
        else
        {
            return parent::supportsComments() and ( !$member or \IPS\raffles\Category::countWhere( 'read', $member, array( 'rc_allowcomments=1' ) ) );
        }
    }

    public function setDefaultValues()
    {
        static::$reviewsPerPage = \IPS\Settings::i()->raffles_display_reviews;
    }

    public static function supportsReviews( \IPS\Member $member = NULL, \IPS\Node\Model $container = NULL )
    {
        if( $container !== NULL )
        {
            return parent::supportsReviews() and $container->allowreviews AND ( !$member or $container->can( 'read', $member ) );
        }
        else
        {
            return parent::supportsReviews() and ( !$member or \IPS\raffles\Category::countWhere( 'read', $member, array( 'rc_allowcomments=1' ) ) );
        }
    }

    public function onPublish( $member )
    {
        $this->status = 'published';
        $this->save();

        parent::onPublish( $member );
        
        $this->container()->resetCommentCounts();
        $this->container()->save();
    }

    public function onUnpublish( $member )
    {
        $this->status = 'draft';
        $this->save();
        
        parent::onUnpublish( $member );
        
        $this->container()->resetCommentCounts();
        $this->container()->save();
    }

    /**
     * Update Topic: workaround for the PROTECTED function
     *
     * @return    void
     */
    public function updateTopic()
    {
        if ( \IPS\Application::appIsEnabled('forums') and $this->topic() )
        {
            $this->syncTopic();
        }
    }
    
    public function updateTopicWithResult()
    {
        try
        {
            $topic         = \IPS\forums\Topic::load( $this->topicid );
            $type        = $this->type == 'raffle' ? 'new_raffle' : 'new_giveaway';
            $content     = \IPS\Theme::i()->getTemplate( 'submit', 'raffles', 'front' )->updateTopicWithWinners( $this->id, $this->type, $winners );
            \IPS\Member::loggedIn()->language()->parseOutputForDisplay( $content );
            $post        = \IPS\forums\Topic\Post::create( $topic, $content, FALSE, NULL, NULL, $this->author() );
            $post->post = $content;
            $post->save();
        }
        catch ( \OutOfRangeException $e )
        {
            return;
        }
    }

    public function displayShareLinks()
    {
        return $this->container()->sharing;
    }

    public function canUsePoints()
    {
        if( \IPS\Application::appIsEnabled( 'membersshop' ) AND \IPS\Application::load( 'membersshop' )->long_version >= 11003 AND \IPS\Settings::i()->raffle_membersshop_onoff AND ( $this->payment_type == 'both' OR $this->payment_type == 'points' ) )
        {
            return TRUE;
        }

        return FALSE;
    }

    public function canChangeAuthor( \IPS\Member $member = NULL )
    {
        return static::modPermission( 'edit', $member, $this->container() );
    }

    public function canManagePrizes( $member=NULL )
    {
        if( $this->isExpired() OR $this->isCompleted() )
        {
            return FALSE;
        }
        
        $member = $member ?: \IPS\Member::loggedIn();

        if ( !$member->member_id OR $this->locked() )
        {
            return FALSE;
        }

        return ( $member->member_id == $this->author()->member_id ) or \IPS\Member::loggedIn()->modPermission( 'can_manage_prizes' );
    }

    public function getPrizes()
    {
        try
        {
            $prizes = iterator_to_array( \IPS\Db::i()->select( '*', 'raffles_prizes', array( 'prize_raffle_id=?', $this->id ), 'prize_place ASC' )->setKeyField( 'prize_id' ) );

            return $prizes;
        }
        catch( \UnderflowException $e )
        {
            return array();
        }
    }

    public function getPrizeById( $id )
    {
        try
        {
            $prize = \IPS\Db::i()->select( '*', 'raffles_prizes', array( 'prize_raffle_id=? AND prize_id=?', $this->id, $id ) )->first();
            return $prize;
        }
        catch( \UnderflowException $e )
        {
            return array();
        }
    }

    public function getPrizeByIdWinner( $id )
    {
        try
        {
            $prize = iterator_to_array( \IPS\Db::i()->select( '*', 'raffles_prizes', array( 'prize_raffle_id=? AND prize_place=?', $this->id, $id ) )->setKeyField( 'prize_id' ) );

            return $prize;
        }
        catch( \UnderflowException $e )
        {
            return array();
        }
    }

    public function getFirstPrize()
    {
        try
        {
            $firstPrize = iterator_to_array( \IPS\Db::i()->select( '*', 'raffles_prizes', array( 'prize_raffle_id=? AND prize_place=?', $this->id, 1 ) )->setKeyField( 'prize_id' ) );

            return $firstPrize;
        }
        catch( \UnderflowException $e )
        {
            return array();
        }
    }

    public function getSecondPrize()
    {
        try
        {
            $secondPrize = iterator_to_array( \IPS\Db::i()->select( '*', 'raffles_prizes', array( 'prize_raffle_id=? AND prize_place=?', $this->id, 2 ) )->setKeyField( 'prize_id' ) );

            return $secondPrize;
        }
        catch( \UnderflowException $e )
        {
            return array();
        }
    }

    public function getThirdPrize()
    {
        try
        {
            $thirdPrize = iterator_to_array( \IPS\Db::i()->select( '*', 'raffles_prizes', array( 'prize_raffle_id=? AND prize_place=?', $this->id, 3 ) )->setKeyField( 'prize_id' ) );

            return $thirdPrize;
        }
        catch( \UnderflowException $e )
        {
            return array();
        }
    }

    public function canParticipate( $member=NULL )
    {
        $return = TRUE;
        $member = $member ?: \IPS\Member::loggedIn();

        if( !$this->getNumberOfPrizes() )
        {
            $return = FALSE;
        }

        if( $this->type == 'raffle' AND $this->payment_type == 'money' AND !$this->price() )
        {
            $return = FALSE;
        }

        if( !$this->container->can( 'buy' ) )
        {
            $return = FALSE;
        }

        if( $this->expired )
        {
            $return = FALSE;
        }

        if( $this->completed )
        {
            $return = FALSE;
        }

        if ( $member->member_id == $this->author()->member_id )
        {
            $return = FALSE;
        }

        if ( !$member->member_id )
        {
            $return = FALSE;
        }

        if ( $member->raffle_ban_participation )
        {
            $return = FALSE;
        }

        if( $this->restriction_users > 0 AND $this->totalParticipants() >= $this->restriction_users )
        {
            $return = FALSE;
        }

        if( $this->restriction_posts > 0 AND $member->member_posts < $this->restriction_posts )
        {
            $return = FALSE;
        }

        if( $this->restriction_reppoints > 0 AND $member->pp_reputation_points < $this->restriction_reppoints )
        {
            $return = FALSE;
        }

        if( $this->restriction_daysjoined > 0 )
        {
            $now         = \IPS\DateTime::ts( time() );
            $joined        = $member->joined;
            $timeLeft     = $now->diff( $joined );

            if( $timeLeft->days < $this->restriction_daysjoined )
            {
                $return = FALSE;
            }
        }

        if( $this->restriction_age > 0 AND \IPS\Member::loggedIn()->age() < $this->restriction_age )
        {
            $return = FALSE;
        }

        if( $this->restriction_groups != '*' AND !\IPS\Member::loggedIn()->inGroup( explode( ',', $this->restriction_groups ) ) )
        {
            $return = FALSE;
        }

        if( $this->locked() )
        {
            $return = FALSE;
        }

        if( $this->type == 'raffle' AND $this->payment_type == 'money' )
        {
            if( !$this->price() )
            {
                $reason[] = \IPS\Member::loggedIn()->language()->addToStack( 'raffle_cant_participate_no_price', FALSE, array( 'sprintf' => $this->type ) );
            }
        }

        if( $this->type == 'raffle' AND $this->restriction_tickets > 0 )
        {
            $count = 0;
            foreach( \IPS\Db::i()->select( '*', 'raffles_participants', array( "rp_raffle_id=? AND rp_member_id=?", $this->id, $member->member_id ) ) as $row )
            {
                $count += $row['rp_tickets'];
            }

            if ( $count >= $this->restriction_tickets )
            {
                $return = FALSE;
            }
        }

        if( $this->type == 'raffle' AND \IPS\Application::appIsEnabled('membersshop') AND \IPS\Application::load( 'membersshop' )->long_version >= 11003 AND $this->payment_type == 'points' )
        {
            if( $member->shopPoints() < $this->points_required )
            {
                $return = FALSE;
            }
        }

        return $return;
    }

    public function getNumberOfPrizes()
    {
        return \IPS\Db::i()->select( 'COUNT(*) as count', 'raffles_prizes', array( 'prize_raffle_id=?', $this->id ) )->first();
    }

    public function updateRafflePrizes()
    {
        $this->prizes += 1;
        $this->save();
    }

    public function timeUntil( $timestamp )
    {
        $now             = \IPS\DateTime::ts( time() );
        $expiredate        = \IPS\DateTime::ts( $timestamp );
        $timeLeft        = \IPS\DateTime::formatInterval( $now->diff( $expiredate ) );
        return $timeLeft;
    }

    public function isExpired()
    {
        if( $this->expired )
        {
            return TRUE;
        }

        if( time() >= $this->datelimit )
        {
            return TRUE;
        }

        return FALSE;
    }

    public function isCompleted()
    {
        if( $this->completed )
        {
            return TRUE;
        }

        return FALSE;
    }

    public function price()
    {
        return static::_price( $this->price );
    }

    public static function _price( $cost )
    {
        if ( $cost )
        {
            $currency = ( isset( $_SESSION['currency'] ) and \in_array( $_SESSION['currency'], \IPS\nexus\Money::currencies() ) ) ? $_SESSION['currency'] : \IPS\nexus\Customer::loggedIn()->defaultCurrency();
            
            $costs = json_decode( $cost, TRUE );
            if ( \is_array( $costs ) )
            {
                if ( isset( $costs[ $currency ]['amount'] ) and $costs[ $currency ]['amount'] )
                {
                    return new \IPS\nexus\Money( $costs[ $currency ]['amount'], $currency );
                }
            }
            else
            {
                return new \IPS\nexus\Money( $cost, $currency );
            }
        }
        
        return NULL;
    }

    public function getParticipants()
    {
        try
        {
            $participants = iterator_to_array( \IPS\Db::i()->select( '*', 'raffles_participants', array( 'rp_raffle_id=?', $this->id ), "RAND()" )->setKeyField( 'rp_id' ) );

            return $participants;
        }
        catch( \UnderflowException $e )
        {
            return array();
        }
    }

    public function getWinners()
    {
        try
        {
            $winners = iterator_to_array( \IPS\Db::i()->select( '*', 'raffles_winners', array( 'rw_raffle_id=?', $this->id ), "rw_prize_position ASC" )->setKeyField( 'rw_id' ) );

            return $winners;
        }
        catch( \UnderflowException $e )
        {
            return array();
        }
    }

    public function amIParticipating()
    {
        $count = (int) \IPS\Db::i()->select( 'count(*)', 'raffles_participants', array( 'rp_raffle_id=? AND rp_member_id=?', $this->id, \IPS\Member::loggedIn()->member_id ) )->first();

        if( $count > 0  )
        {
            return TRUE;
        }
        
        return FALSE;
    }

    public function getParticipantsCount()
    {
        $count = (int) \IPS\Db::i()->select( 'count(*)', 'raffles_participants', array( 'rp_raffle_id=?', $this->id ) )->first();

        if( $count > 0  )
        {
            return FALSE;
        }
        
        return TRUE;
    }

    public function totalParticipants()
    {
        $count = (int) \IPS\Db::i()->select( 'count(*)', 'raffles_participants', array( 'rp_raffle_id=?', $this->id ) )->first();
        return $count;
    }

    public function canMemberBeManuallyAdded( $member )
    {
        $member = $member ?: \IPS\Member::loggedIn();

        if( $this->type == 'raffle' )
        {
            if( $this->restriction_tickets == 1 )
            {
                $count = \IPS\Db::i()->select( 'count(*)', 'raffles_participants', array( 'rp_raffle_id=? AND rp_member_id=?', $this->id, $member->member_id ) )->first();

                if ( $count >= 1 )
                {
                    return FALSE;
                }
            }

            if( $this->restriction_tickets > 1 )
            {
                $count = 0;
                foreach( \IPS\Db::i()->select( '*', 'raffles_participants', array( "rp_raffle_id=? AND rp_member_id=?", $this->id, $member->member_id ) ) as $row )
                {
                    $count += $row['rp_tickets'];
                }

                if ( $count >= $this->restriction_tickets )
                {
                    return FALSE;
                }
            }
        }
        else
        {
            $count = \IPS\Db::i()->select( 'count(*)', 'raffles_participants', array( 'rp_raffle_id=? AND rp_member_id=?', $this->id, $member->member_id ) )->first();

            if( $count > 0 )
            {
                return FALSE;
            }
        }
        
        return TRUE;
    }

    public function canChangeTicketPrice()
    {
        if( \IPS\Application::appIsEnabled('nexus') AND ( \IPS\Member::loggedIn()->modPermission('can_change_raffles_price') OR $this->author()->member_id == \IPS\Member::loggedIn()->member_id ) AND $this->type=='raffle' AND ( !$this->isExpired() AND !$this->isCompleted() ) AND ( $this->payment_type == 'money' OR $this->payment_type == 'both' ) )
        {
            return TRUE;
        }

        return FALSE;
    }

    public function canChangeTicketPoints()
    {
        if( \IPS\Application::appIsEnabled('membersshop') AND \IPS\Application::load( 'membersshop' )->long_version >= 11003 AND ( \IPS\Member::loggedIn()->modPermission('can_change_raffles_price') OR $this->author()->member_id == \IPS\Member::loggedIn()->member_id ) AND $this->type=='raffle' AND ( !$this->isExpired() AND !$this->isCompleted() ) AND ( $this->payment_type == 'points' OR $this->payment_type == 'both' ) )
        {
            return TRUE;
        }

        return FALSE;
    }

    public function canReactivate( $member )
    {
        if( $this->type == 'raffle' AND \IPS\Member::loggedIn()->modPermission( 'can_reactivate_raffles' ) )
        {
            return TRUE;
        }

        if( $this->type == 'giveaway' AND \IPS\Member::loggedIn()->modPermission( 'can_reactivate_giveaways' ) )
        {
            return TRUE;
        }

        return FALSE;
    }

    public function getMyNumberOfTickets( \IPS\Member $member )
    {
        $member = $member ?: \IPS\Member::loggedIn();

        try
        {
            $count = \IPS\Db::i()->select( '*', 'raffles_participants', array( 'rp_raffle_id=? AND rp_member_id=?', $this->id, $member->member_id ) )->first();
            return $count['rp_tickets'];
        }
        catch( \UnderflowException $e )
        {
            return 0;
        }
    }

    public function getMyRaffleJoinedDate( $member )
    {
        $member = $member ?: \IPS\Member::loggedIn();

        try
        {
            $date = \IPS\Db::i()->select( '*', 'raffles_participants', array( 'rp_raffle_id=? AND rp_member_id=?', $this->id, $member->member_id ) )->first();
            return $date['rp_date'];
        }
        catch( \UnderflowException $e )
        {
            return 0;
        }
    }

    public function getMemberOdds( $member )
    {
        $member         = $member ?: \IPS\Member::loggedIn();
        $prTicketOdds     = 100 / $this->tickets;

        $count = \IPS\Db::i()->select( '*', 'raffles_participants', array( 'rp_raffle_id=? AND rp_member_id=?', $this->id, $member->member_id ) )->first();
        $myTickets = $count['rp_tickets'];

        return round( $myTickets * $prTicketOdds, 2);
    }

    public function updateRaffleParticipants()
    {
        $this->participants += 1;
        $this->save();
    }

    public function decreaseRaffleParticipants()
    {
        $this->participants -= 1;
        $this->save();
    }

    public function decreaseRaffleTickets( \IPS\Member $member )
    {
        $tickets = $this->getMyNumberOfTickets( $member );
        $this->tickets -= $tickets;
        $this->save();
    }

    public function searchIndexPermissions()
    {
        if ( $this->status == 'draft' )
        {
            return '0';
        }

        return parent::searchIndexPermissions();
    }

    public static function sitemapWhere()
    {
        return array( array( 'raffles_raffles.raffle_is_future_entry=0 AND raffles_raffles.raffle_status!=?', 'draft' ) );
    }

    public static function searchResultSnippet( array $indexData, array $authorData, array $itemData, array $containerData = NULL, array $reputationData, $reviewRating, $view )
    {
        $mainImage = isset( $itemData['raffle_thumb'] ) ? $itemData['raffle_thumb'] : $itemData['raffle_image'];

        $url = \IPS\Http\Url::internal( static::$urlBase . $indexData['index_item_id'], 'front', static::$urlTemplate, \IPS\Http\Url::seoTitle( $indexData['index_title'] ?: $itemData[ static::$databasePrefix . static::$databaseColumnMap['title'] ] ) );

        $type            = $itemData['raffle_type'];
        $time             = $itemData['raffle_datelimit'];
        $participants    = $itemData['raffle_participants'];
        $tickets         = $itemData['raffle_tickets'];

        return \IPS\Theme::i()->getTemplate( 'global', 'raffles', 'front' )->searchResultRafflesSnippet( $indexData, $itemData, $mainImage, $url, $type, $time, $participants, $tickets, $view == 'condensed' );
    }

    public static function reactionType()
    {
        return 'raffle_id';
    }

    public static function supportedMetaDataTypes()
    {
        return array( 'core_FeaturedComments', 'core_ContentMessages' );
    }

    public function contentImages( $limit = NULL )
    {
        $attachments = parent::contentImages( $limit ) ?: array();
        $attachments[] = array( 'raffles_Image' => $this->thumb );

        if( $this->prizes > 0 )
        {
            $count = 0;
            foreach( \IPS\Db::i()->select( 'prize_image', 'raffles_prizes', array( 'prize_image IS NOT NULL AND prize_raffle_id=?', $this->id ) ) as $image )
            {
                if ( $count == $limit )
                {
                    break;
                }

                $attachments[] = array( 'raffles_Prize' => (string) $image );
                $count++;
            }
        }

        return \count( $attachments ) ? $attachments : NULL;
    }

    public function embedImage()
    {
        return $this->thumb ? \IPS\File::get( 'raffles_Image', $this->thumb ) : NULL;
    }

    public function embedContent( $params )
    {
        \IPS\Output::i()->cssFiles = array_merge( \IPS\Output::i()->cssFiles, \IPS\Theme::i()->css( 'raffles.css', 'raffles', 'front' ) );
        return \IPS\Theme::i()->getTemplate( 'global', 'raffles', 'front' )->embedRaffle( $this, $this->url()->setQueryString( $params ), $this->embedImage() );
    }

    public function coverPhoto( $getOverlay=TRUE, $position='full' )
    {
        $photo = new \IPS\Helpers\CoverPhoto;
        if ( $this->cover_photo )
        {
            $photo->file = \IPS\File::get( 'raffles_CoverPhoto', $this->cover_photo );
            $photo->offset = $this->cover_offset;
        }

        if ( $getOverlay )
        {
            $photo->overlay = \IPS\Theme::i()->getTemplate( 'view', 'raffles', 'front' )->coverPhotoOverlay( $this, $position );
        }

        $photo->editable = $this->canEdit();
        $photo->object = $this;

        return $photo;
    }

    public function coverPhotoBackgroundColor()
    {
        return $this->staticCoverPhotoBackgroundColor( $this->mapped('title') );
    }

    public static function containerForumIdColumn()
    {
        return 'forum';
    }

    function getTopicTitle()
    {
        return $this->container()->prefix . $this->title . $this->container()->suffix;
    }

    function getTopicContent()
    {
        return \IPS\Theme::i()->getTemplate( 'submit', 'raffles', 'front' )->topic( $this );
    }

    /**
     * Can convert review to comment?
     *
     * @param    \IPS\Member    $member    The member (null for currently logged in member)
     * @return    bool
     */
    public function canConvertReview( \IPS\Member $member = NULL )
    {
        $member = $member ?: \IPS\Member::loggedIn();

        if
        (
            $member->modPermission( 'raffle_can_convert_rev_com' )
            and
            (
                ( $member->modPermission( \IPS\raffles\Category::$modPerm ) === TRUE or $member->modPermission( \IPS\raffles\Category::$modPerm ) === -1 )
                or
                (
                    \is_array( $member->modPermission( \IPS\raffles\Category::$modPerm ) )
                    and
                    \in_array( $this->container()->_id, $member->modPermission( \IPS\raffles\Category::$modPerm ) )
                )
            )
            and $this->container()->allowcomments
        )
        {
            return TRUE;
        }

        return FALSE;
    }

    public static function getWidgetSortOptions()
    {
        $sortOptions = parent::getWidgetSortOptions();

        $sortOptions['_rand'] = 'sort_rand';

        return $sortOptions;
    }

    public function apiOutput()
    {
        return array(
            'id'                => $this->id,
            'title'                => $this->title,
            'category'            => $this->container()->apiOutput(),
            'author'            => $this->author()->apiOutput(),
            'date'                => \IPS\DateTime::ts( $this->submitted )->rfc3339(),
            'datelimit'            => \IPS\DateTime::ts( $this->datelimit )->rfc3339(),
            'draft'                => $this->status == 'draft',
            'description'        => $this->content(),
            'type'                => $this->type,
            'items'                => $this->items,
            'prizes'            => $this->prizes,
            'participants'        => $this->participants,
            'tickets'            => $this->tickets,
            'expired'            => $this->expired,
            'completed'            => $this->completed,
            'comments'            => $this->comments,
            'reviews'            => $this->reviews,
            'views'                => $this->views,
            'prefix'            => $this->prefix(),
            'tags'                => $this->tags(),
            'locked'            => (bool) $this->locked(),
            'hidden'            => (bool) $this->hidden(),
            'pinned'            => (bool) $this->mapped('pinned'),
            'featured'            => (bool) $this->mapped('featured'),
            'rating'            => $this->averageRating(),
            'url'                => (string) $this->url(),
        );
    }
}

В: public function delete()

Попробую сам отредактировать, не уверен, что получится, так как не очень опытен.

Буду признателен, если вы хотите помочь.

ОБНОВИТЬ:

Починил это!!!!

Я добавил:

Quote

\IPS\Db::i()->delete( 'raffles_winners', array( 'rw_raffle_id=?', $this->id ) );

После:

Quote

\IPS\Db::i()->delete( 'raffles_prizes', array( 'prize_raffle_id=?', $this->id ) );

Спасибо всем!!

Ссылка на комментарий
Поделиться на другие сайты

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.
Примечание: Ваш пост будет проверен модератором, прежде чем станет видимым.

Гость
Ответить в этой теме...

×   Вставлено с форматированием.   Вставить как обычный текст

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отображать как обычную ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.

  • Последние посетители   0 пользователей онлайн

    • Ни одного зарегистрированного пользователя не просматривает данную страницу
×
×
  • Создать...