/**
     * Update profile data
     *
     * @param array $parameters
     * @return array
     */
    public function write( $parameters = null )
    {
        $result = array();

        //TODO find another placement ?
        //if Token (CSRF)
        if(!isset($_POST['Token']) || !SecurityTool::isUserTokenValid($_POST['Token']))
        {
            $result = array(
                'Data' => array(
                    'Status' => 'Error',
                    'ErrorCode' => 10,
                    'Msg' => "Invalid Token"
                )
            );
        }
        else
        {
            $result = $this->callEsbWrite($parameters);
        }

        // ESB update
        $uuid         = MMUsers::getCurrentUserId();
        $ticketParams = array( $this->getBusinessNameMapping('userName') => $uuid );

        foreach ( $this->getBusinessNamesForWrite() as $name )
        {
            $ticketParams[$name] = isset( $_POST[$name] ) ? $_POST[$name] : '';
        }

        // Front user update
        $userUpdateParams = array(
            'uuid'           => $uuid,
            'customerType'   => $_POST[$this->getBusinessNameMapping( 'customerType' )],
            'userSpeciality' => $_POST[$this->getBusinessNameMapping( 'userSpecialty' )],
            'state'          => isset( $_POST['state'] ) ? $_POST['state'] : null,
            'country'        => $this->getCountryOfRegistration(),
            'language'       => ""
        );

        // quick fix for retrieve the real main spe
        $userSpe = $this->getUserSpecialty($uuid);
        if ( $userSpe != $ticketParams['User_speciality'] )
        {
            $userUpdateParams['userSpeciality'] = $userSpe;
        }

        $user = MMUserLogin::createOrUpdateMMUser( $userUpdateParams );
        $user->setCookie();
        
        $businessNames = $this->getBusinessNamesForTicket();
        $ticketBackendParams  = array();
        foreach ( $businessNames as $ticketParam => $businessName )
        {
            if ( isset( $userUpdateParams[$businessName] ) )
            {
                $ticketBackendParams[$ticketParam] = $userUpdateParams[$businessName];
            }
            elseif ( isset( $ticketParams[$businessName] ) )
            {
                $ticketBackendParams[$ticketParam] = $ticketParams[$businessName];
            }
            elseif ( $businessName == $this->getBusinessNameMapping( 'countryOfRegistration' ) )
            {
                $ticketBackendParams[$ticketParam] = $this->getCountryOfRegistration();
            }
            else
            {
                eZDebug::writeError( 'Could not get registration param: ' . $businessName );
            }
        }
        $ticketBackendParams[MMUsers::COOKIE_KEY] = $user->getMMSettings();

        $result['User']   = $user;
        $result['Ticket'] = MMUserLogin::encryptText( json_encode( $ticketBackendParams ) );

        return $result;
    }
    /**
     * Create token and send password reset request email
     *
     * @return array
     */
    public function t()
    {
        $http = BlockDefault::http();
        $isConsult = (bool) $http->postVariable('consult');

        $token = $http->postVariable('token');
        if(!SecurityTool::isUserTokenValid($token))
        {
            return array(
                'errorCode' =>  ResponseError::ERROR_REQUEST_EXECUTION,
                'msg'       =>  'Invalid token',
            );
        }

        $username = $http->postVariable('Username');
        if (empty($username))
        {
            return array(
                'errorCode' => ResponseError::ERROR_USERNAME_MISSING,
                'msg' => 'Username missing'
            );
        }
        eZLog::write(var_export('We have username.', true) , 'resetpass.log');
        $countryOfRegistration = eZINI::instance('site.ini')->variable('RegionalSettings', 'CountryOfRegistration');
        if (empty($countryOfRegistration))
        {
            return array(
                'errorCode' => ResponseError::ERROR_COUNTRY_NOT_SPECIFIED,
                'msg' => 'Country of registration not set'
            );
        }
        eZLog::write(var_export('We have countrycode.', true) , 'resetpass.log');

        try
        {
            eZLog::write(var_export('Sending request for token.', true) , 'resetpass.log');
            $esbClient = self::getEsbClient();
            $response = $esbClient->createToken($username, $countryOfRegistration);

            eZLog::write(var_export('We got response:.', true) , 'resetpass.log');
            eZLog::write(var_export($response, true) , 'resetpass.log');
        }
        catch(\Exception $e)
        {
            return array(
                'errorCode' => ResponseError::ERROR_REQUEST_EXECUTION,
                'msg' => $e->getMessage()
            );
        }
        eZLog::write(var_export('We have token.', true) , 'resetpass.log');

        $token = self::encryptToken($response);

        eZLog::write("TOKEN: {$token}", 'esb_uump.log');
        eZLog::write("TOKEN: {$token}", 'resetpass.log');
        eZLog::write(var_export('Consult status: ' . $isConsult, true) , 'resetpass.log');
        eZLog::write(var_export('Sending an email with pass reset.', true) , 'resetpass.log');

        self::sendResetPasswordMail($token, $response['userId'], $response['email'], $isConsult);

        if($isConsult)
        {
            $confirmationUrl = $this->getCustomParameter('ConsultEmailSentUrl');
        }
        else
        {
            $confirmationUrl = $this->getCustomParameter('EmailSentUrl');
        }
        if( !preg_match('#^https?://[^/]+#', $confirmationUrl) )
        {
            $confirmationUrl = contextTool::instance()->domain().$confirmationUrl;
        }

        eZLog::write(var_export('After email.', true) , 'resetpass.log');
        eZLog::write(var_export(array(
            'errorCode' => ResponseError::SUCCESS,
            'redirectUrl' => $confirmationUrl
        ), true) , 'resetpass.log');

        return array(
            'errorCode' => ResponseError::SUCCESS,
            'redirectUrl' => $confirmationUrl
        );
    }
    /**
     * @return array
     */
    public function stc()
    {
        if( !self::user() ) {
            return false;
        }
        $http = BlockDefault::http();

        //get current user infos
        $serviceUser = ServiceUser::getInstance();
        $parameters = $serviceUser->getFormParameters();
        $userInfos = $serviceUser->callWSHandler( $serviceUser->getEsbInterface( 'read' ), $parameters );

        $appname = $http->hasPostVariable( 'appname' ) ? stripslashes( $http->postVariable( 'appname' ) ) : '';

        $sender = $userInfos['Data']['Params']['Firstname'] . $userInfos['Data']['Params']['Lastname'];
        $senderName = $userInfos['Data']['Params']['Firstname'] . $userInfos['Data']['Params']['Lastname'];
        $senderEmail = $userInfos['Data']['Params']['Email_address'];

        //get comment

        if(!$http->hasPostVariable( 'token' ) || !SecurityTool::isUserTokenValid($http->postVariable( 'token' )))
        {
            return array(
                'Error' =>  'Invalid token',
            );
        }

        $message = $http->hasPostVariable( 'comment' ) ? stripslashes( $http->postVariable( 'comment' ) ) : '';

        //get recipient email
        $recipient = $http->hasPostVariable( 'Recipient_email' ) ? stripslashes( preg_replace( '/\s/', '', $http->postVariable( 'Recipient_email' ) ) ) : '';
        $recipients = array_unique( explode( ';', $recipient ) );

        //get Article nodeID
        $extract = $title = '';
        $articleRemoteID = $http->hasPostVariable( 'remote_id' ) ? $http->postVariable( 'remote_id' ) : null;
        if(!is_null($articleRemoteID))
        {
            $fieldsQuery = array (
                '(meta_remote_id_ms:' . $articleRemoteID . ')',
                '(meta_class_identifier_ms:article)'
            );

            $fields = array (
                'attr_promo_description_t',
                'attr_headline_t',
            );

            //fetch solr
            $params = array(
                'indent'        => 'on',
                'q'             => '*:*',
                'start'         => 0,
                'rows'          => 1,
                'fq'            => implode(' AND ', $fieldsQuery),
                'fl'            => implode(',', $fields),
                'qt'            => '',
                'explainOther'  => '',
                'hl.fl'         => '',
            );

            $raw = SolrTool::rawSearch($params);
            $article = $raw['response']['docs'][0];

            if(strlen($article['attr_promo_description_t']) > 150)
            {
                $extract = mb_substr($article['attr_promo_description_t'], 0, 150, 'utf-8') . '...';
            }
            else
            {
                $extract = $article['attr_promo_description_t'];
            }

            $title = $article['attr_headline_t'];
        }

        $destUrl = $http->hasPostVariable( 'destURL' ) ? stripslashes( filter_var($http->postVariable( 'destURL' ), FILTER_VALIDATE_URL) ) : '';

        $preparedMessage = $this->prepareMessage( $sender, htmlentities( $message ), $extract, $destUrl );

        if( SolrSafeOperatorHelper::featureIsActive( 'ExactTarget' ) && SolrSafeOperatorHelper::featureIsActive( 'UUMP' ) )
        {
            $message = nl2br($message);
            
            foreach( $recipients as $recipient )
            {
                ExactTarget::sendToAColleague(
                    self::user()->attribute( 'uuid' ),
                    $recipient,
                    $message,
                    $appname,
                    $destUrl,
                    $extract,
                    $title
                );
            }
        }
        else
        {
            // Below code is no longer used, since all clusters are using ExactTarget feature.
            $email = new MailTool( $title, $senderName, array(), $preparedMessage, 'sendtocolleague_email.log');
            foreach ( $recipients as $recipient )
            {
                $to = filter_var( $recipient, FILTER_VALIDATE_EMAIL );
                if ( $to === false ) {
                    continue;
                }
                $email->setRecipients( $to );
                $email->sendMail();
            }
        }

        return array(
            'redirect_url' => $this->redirectUrl
        );
    }