/**
     * @return string
     */
    static public function getCookieDomain ()
    {
        $cookieDomain = false;
        if( self::iniMerck()->hasVariable( 'CookieSettings', 'CookieDomain') )
        {
            $cookieDomainSetting = self::iniMerck()->variable( 'CookieSettings', 'CookieDomain' );

            if ( $cookieDomainSetting  == 'disabled' )
                return false;

            if( $cookieDomainSetting == 'dynamic' )
            {
                $splitDepth = self::iniMerck()->hasVariable( 'CookieSettings', 'CookieDomainSplitDepth' )
                    ? self::iniMerck()->variable( 'CookieSettings', 'CookieDomainSplitDepth' )
                    : 1;
                if ( $splitDepth == 0 )
                {
                    $cookieDomain = preg_replace('#^(https?://)?([^.]+.){0}#', '', ContextTool::instance()->domain() );
                }
                else
                {
                    $cookieDomain = preg_replace('#^(https?://)?([^.]+.){'.$splitDepth.'}#', '.', ContextTool::instance()->domain() );
                }
                return $cookieDomain;
            }

            $cookieDomain = $cookieDomainSetting;
        }

        return $cookieDomain;
    }
function callUpdate($appList)
{
    $url = ContextTool::instance()->domain() . '/esibuild/ajax/apps_bar/a/ual';
    $data = array(
        'al' => implode('-', $appList),
    );

    $cookieData = implode("; ", array_map(
            function($k, $v) { return "$k=$v"; },
            array_keys($_COOKIE),
            array_values($_COOKIE)
        )
    );

    $ch = curl_init($url);

    curl_setopt_array($ch, array(
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => http_build_query($data),
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_COOKIE => $cookieData,
    ));

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}
    /**
     * Fetches the zones and blocks for each zone
     *
     * The cache will be checked before hitting the database.
     *
     * @param string $currentEnvId
     * @return array Array of zones and blocks
     */
    public function fetchZones( $currentEnvId )
    {
        $env = eZINI::instance()->variable("Environment", "Type");
        if ( $env != "stg" )
        {
            if ( ContextTool::instance()->isMobile() )
                $zones = $this->getCachedValue( self::MOBILE_ZONES_CACHE_KEY );
            else
                $zones = $this->getCachedValue( self::DESKTOP_ZONES_CACHE_KEY );
        }
        else
        {
            $zones = false;
        }
        if ( !$zones )
        {
            $clusterIdentifier = ClusterTool::clusterIdentifier();
            $leftZone = MMHomePageZone::fetch( MMHomePageZone::LEFT_ZONE );
            $rightZone = MMHomePageZone::fetch( MMHomePageZone::RIGHT_ZONE );
            $zones = array(
                'left' => $leftZone->fetchBlocks( $currentEnvId, $clusterIdentifier ),
                'right' => $rightZone->fetchBlocks( $currentEnvId, $clusterIdentifier ),
            );
            if ( $env != "stg" )
            {
                if ( ContextTool::instance()->isMobile() )
                    $this->storeCacheValue( self::MOBILE_ZONES_CACHE_KEY, $zones );
                else
                    $this->storeCacheValue( self::DESKTOP_ZONES_CACHE_KEY, $zones );
            }
        }

        return $zones;
    }
 /**
  * @return string
  */
 protected static function refuseToU()
 {
     MMUserLogin::logoutUser();
     CookieTool::destroyCookie( 'remember_me' );
     $redirectURL = ContextTool::instance()->domain().'/logoutActions.php';
     return $redirectURL;
 }
    /**
     * @return ContextTool
     */
    public static function instance()
    {
        if( is_null(self::$_instance) )
        {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
    function __construct( $row )
    {
        parent::__construct( $row );
        $this->configurations = ChannelBlockConfiguration::getConfigurationsByBlock( $this->attribute("id") );

        $templateObject = ChannelTemplate::getTemplateById( $this->attribute("template_id") );
        if( $templateObject )
        {
            $this->template = $templateObject->attribute("template_web");
            if( ContextTool::instance()->isMobile() && $templateObject->attribute("template_mobile") )
            {
                $this->template = $templateObject->attribute("template_mobile");
            }
        }
    }
    /**
     * @param eZScript $script
     * @param eZCli $cli
     */
    public function __construct( $script, $cli )
    {
        $this->script = $script;
        $this->cli = $cli;
        $this->newRelicApi = new klpNrApi();

        $envArray    = array(
            ContextTool::ENVIRONMENT_STAGING => 'stg',
            ContextTool::ENVIRONMENT_PROD    => 'prod'
          );
        if( !isset($envArray[ContextTool::instance()->environment()]) )
            $this->script->shutdown( 0, 'This script cannot be executed on the current environment' );
        $this->env = $envArray[ContextTool::instance()->environment()];

        $this->newsletterFeed = $this->populateNewsletterFeed();
    }
    /**
     * @return bool
     */
    public function htmlBuildResult()
    {
        $ela = array();

        foreach( CacheApplicationTool::clusterApplications() as $app )
        {
            if
            (
                $app->applicationObject->applicationType->attribute('type_identifier') == 'e-learning'
                && $app->getCustomParameter('HasLearningTracker')
                && ApplicationFactory::fetchByUri($app->attribute('url_alias'))->canRead()
            )
            {
                $ela[] = array(
                    'headline' => $app->headline,
                    'url'      => $app->applicationUrl(),
                );
            }
        }
        $this->pushResult( 'ela', $ela );
        $this->pushResult( 'content_service_configuration', $this->applicationObject->configurationContentService );
        $this->pushResult( 'is_mobile', ContextTool::instance()->isMobile() );
		$this->pushResult( 'isApplicationAllowedToUser', MMLimitedApplicationsAllowedUsers::hasCurrentUserAccessToApp(CacheApplicationTool::buildLocalizedApplicationByIdentifier('learning-needs-assessment')->application_id) );

        $uuid = $this->user()->attribute('uuid');
        $this->pushResult( 'userId', $uuid );

        //LNA Dashboard url
        $lmtBaseUrl = SolrSafeOperatorHelper::feature('LearningNeedsAssessment', 'LMTBaseUrl');
        $lmtPrefix = SolrSafeOperatorHelper::feature('LearningNeedsAssessment', 'LMTPrefix');
        $this->pushResult( 'dashboardUrl', $lmtBaseUrl . $lmtPrefix );

        $environment = new MMEnvironment();
        $this->pushResult( 'environment', $environment->env );
        
        $userData = CertificatesWebservice::readUserData();
        $this->pushResult( 'companyCode', $userData['CID'] );

        $countryPrefix = preg_replace( "~cluster|_~", "", ClusterTool::clusterIdentifier() );
        $this->pushResult( 'dashBoardCountryPrefix', strtolower( $countryPrefix ) . '_' );

        parent::htmlBuildResult();

        return true;
    }
    /**
     * @return bool
     */
    public function htmlBuildResult()
    {
        $this->pushResult( 'rightColumnContext', 'about' );

        if ( $this->fullContext == 'chapter' )
        {
            $params = array(
                'DepthOperator' => 'eq',
                'Limit'         => 1,
                'Offset'        => 0,
                'Depth'         => 1,
                'SortBy'        => array(
                    array(
                        'priority',
                        'asc'
                    )
                ),
            );
            $children = eZContentObjectTreeNode::subTreeByNodeID( $params, $this->rootNodeId() );

            if ( isset( $children[0] ) && $children[0] instanceof eZContentObjectTreeNode )
            {
                $this->node        = $children[0];
                $this->fullContext = 'topic';
            }
        }

        $this->pushResult( 'node', $this->node );

        if ( ContextTool::instance()->isMobile() )
        {
            $this->pushResult( 'hideMenuButton', true );
            $this->pushResult( 'hideTreeButton', true );
        }

        return true;
    }
            '%GLOBAL_RANK' => $playerScoring->attribute('global_ranking'),
            '%NB_POINTS' => $playerScoring->attribute('score')
        ));

        $description = strip_tags($description);
        $data = array(
            'title' => ezpI18n::tr("merck/quiz", "QUIZ ANNOUNCEMENT"),
            'description' => $description,
            'specialty_rank' => $playerScoring->attribute('specialty_ranking'),
            'global_rank' => $playerScoring->attribute('global_ranking'),
            'application_identifier' => $applicationIdentifier,
            'type' => $cardType,
        );
        $userId = $playerScoring->attribute('uuid');
        $clusterIdentifier = $playerScoring->attribute('cluster_identifier');

        $hash = md5($cluster_identifier . $userId . $description);

        $socialCard = MMSocialCard::fetchByHash($hash);
        if (!$socialCard)
        {
            $socialCard = MMSocialCard::create($data);
            $socialCard->hash = $hash;
            $socialCard->store();
        }

        echo ContextTool::instance()->domain() . "/esibuild/social_card/$hash";
    }
}

    public function contentBuildResult()
    {
        $oldSkipPage = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, 'SkipExitPage', 'application');
        $skipPage = $oldSkipPage || !$this->exitStrategy();

        $this->pushResult('user' , self::user());
        $this->pushResult('country', LocaleTool::countryISO3166Code());

        if ( $skipPage )
        {
            $_REQUEST['proceed'] = 'proceed';
            $_COOKIE[$this->cookieKey()] = '1';
            if ( ContextTool::instance()->isMobile() )
                $_REQUEST['r'] = 1;
        }

        if( isset($_REQUEST['proceed']) && isset($_COOKIE[$this->cookieKey()]) && filter_var($_COOKIE[$this->cookieKey()], FILTER_VALIDATE_INT))
        {
            // proceed to iframe view
            $this->iframeBuildResult( );
        }
        elseif( isset($_REQUEST['proceed']) )
        {
            // proceed requested but no cookie, we ask again and force redirect to make sure we the proper layout
            header('Location: '.ContextTool::instance()->domain().$this->applicationLocalized()->applicationUrl());
            eZExecution::cleanExit();
        }
        else
        {
            // normal exit page vie
            $isMobile   = ContextTool::instance()->isMobile();
            $urlToRedirect = isset($_REQUEST['r']) ? trim($_REQUEST['r']) : null;
            if ($this->isExitApplication() && $this->displayIframe())
            {
                $serverUrl  = ContextTool::instance()->domain();
                $params = array(
                    'r' => urlencode($urlToRedirect),
                    'exit_strategy' => 0,
                    'display_iframe' => $this->displayIframe(),
                    'new_window' => $this->newWindow()
                );

                $urlToRedirect = $serverUrl . '/external/exit/?' . http_build_query($params);
                $this->pushResult('decode_url', false);
                $this->pushResult('server_url', $serverUrl);
            }
            if($isMobile){
                if($this->applicationObject()->externalLinkHandler())
                {
                    $externalUrl = $this->applicationObject()->externalLinkHandler()->getNodeUrl( $this->node );
                    $urlToRedirect = isset($externalUrl) ? $externalUrl : $urlToRedirect ;

                    if(SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, 'usePostMethod', 'application' )){

                        $url = $this->applicationObject()->externalLinkHandler()->getNodeUrl( $this->node );
                        $url = $this->getDeeplink( $url );

                        if ($url == null && isset($_REQUEST['r']))
                        {
                            $url = urldecode($_REQUEST['r']);
                        }

                        $url = in_array('arg', array_keys($this->_params['UserParameters'])) ? $url . $this->_params['UserParameters']['arg'] : $url;

                        $this->pushResult('postParams', $url);
                    }
                }
                else
                {
                    $urlToRedirect = '/bad_config';
                }
            }
            $this->pushResult('back_url', ContextTool::instance()->backUrl());
            $this->pushResult('url', $urlToRedirect);
            $this->pushResult('deeplink', urlencode( $this->getDeeplink() ));
            // Because we are passing boolean parameters to final URL, we need to make isset check.
            if ( $this->isDeeplinkApplication() || $this->isExitApplication() )
            {
                if ( isset( $_GET['display_iframe'] ) )
                {
                    $this->pushResult('display_iframe', $this->displayIframe());
                }
                if ( isset( $_GET['new_window'] ) )
                {
                    $this->pushResult('new_window', $this->newWindow());
                }
                if ( isset( $_GET['exit_strategy'] ) )
                {
                    $this->pushResult('exit_strategy', $this->exitStrategy());
                }
            }
        }

        if($this->node && $this->node->attribute('url_alias') != "")
        {
            $this->pushResult('article_url', end(explode("/", $this->node->attribute('url_alias'))));
            /* @type $pfDM eZContentObjectAttribute[] */
            $pf   = NodeTool::getPublisherNodeFromNode( $this->node );
            $pfDM = $pf->DataMap();
            $pfID = PublisherFolderTool::getPathToIDMapping( $pfDM['path']->content() );
            $this->pushResult( 'pfid', $pfID['pfid'] . '/' );
        }

        $oldOpenInNewWindow = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject()->identifier, 'openInNewWindow', 'application');
        $openInNewWindow = $this->newWindow() || $oldOpenInNewWindow;
        $this->pushResult('application', $this->applicationObject);
        $this->pushResult('open_in_new_window', $openInNewWindow);
        $this->pushResult('cookie_key', $this->cookieKey());
        $this->pushResult('node', $this->node);
        
        if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
        {
            $this->pushResult( 'gtm_variables', $this->getGTMTags( $this->node ) );
            if( $this->node )
            {
                $publisherNodeId = PublisherFolderTool::getPublisherNodeIdFromArticleNode($this->node);

                if ($publisherNodeId)
                {
                    $publisherInfos  = PublisherFolderTool::getNodeIdToPathMapping( $publisherNodeId );
                    $publisherPath   = $publisherInfos['path'];

                    $this->pushResult( 'publisher', $this->applicationLocalized()->getPublisherFolderFromPath( $publisherPath ) );
                }
            }
        }
    }
        )
        {
            $serviceLogin = ESBFactory::getLoginService( ServiceLoginBase::ESB_METHOD_AUTOLOGIN, $_REQUEST );
            if ( $serviceLogin->checkTouPPPopin( ESBFactory::getUserService()->form() ) )
            {
                CookieTool::destroyCookie( 'displayToUPPPopin' );
                CookieTool::destroyCookie( 'displayToUPPPopin', '/', null );
                $serviceLogin->login();
                eZExecution::cleanExit();
            }
        }
    }

    // User is already logged-in, we redirect him
    $context = isset( $_REQUEST['context'] ) ? $_REQUEST['context'] : false;
    header('Location: '.ContextTool::instance()->contextUrl($context));
    eZExecution::cleanExit();
}
elseif (   isset($_REQUEST['dsp'])
        && $_REQUEST['dsp'] == 1
){
    $tpl = eZTemplate::factory();

    $tpl->setVariable( 'cluster_identifier', ClusterTool::clusterIdentifier() );

    header_remove('Pragma');
    header_remove('Cache-control');
    header_remove('Expires');
    header('Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 7200 ) . ' GMT');
    header('esi-enabled: 1');
    if( isset($_GET['context']))
    {
        $context = trim($_GET['context']);

        if( preg_match( '#^(?:https?://|/)#', $context) )
        {
            if( strpos( $context, '/' ) === 0 )
            {
                $context = ContextTool::instance()->domain().$context;
            }
            if( ContextTool::instance()->checkRedirectUrl( $context ) )
            {
                $destUrl = $context;
            }
            else
            {
                $destUrl = ContextTool::instance()->backUrl();
            }
        }
    }
    
     header('Location: '.$destUrl );
     eZExecution::cleanExit();
}
else
{
    header( 'HTTP/1.1 500 Login Failed' );
    header( 'Status: 500 Login Failed' );
    $Result['content'] = $tpl->fetch ('design:login/fail.tpl');
}
    /**
     * @return bool
     */
    public function htmlBuildResult()
    {
        if( !$this->isFull )
        {
            $solrResult     = $this->resultHandler->contentResultMain( true );
            $articleNodeId  = $solrResult['response']['docs'][0]['meta_node_id_si'];
            $this->pushResult( 'features', $this->resultHandler->features );
            $this->pushResult( 'articles', $articleNodeId );

            // quiz of the day
            $solrReturn = $this->getResultHandler()->articleResult($solrResult, array());
            if($solrReturn["article_informations"] && $solrReturn["article_informations"]["articles_solrdata"])
            {
                $this->pushResult('articles_solrdata', $solrReturn["article_informations"]["articles_solrdata"]);
            }
        }
        else
        {
            /* @type $dm eZContentObjectAttribute[] */
            $dm = $this->node->dataMap();
            if( $dm['media_content']->hasContent() )
            {
                $mediaContent = $dm['media_content']->content();
                /* @type $quizDM eZContentObjectAttribute[] */
                $quizDM       = eZContentObjectTreeNode::fetch( $mediaContent['relation_list'][0]['node_id'] )->dataMap();
                $quizReplies  = $quizDM['replies'];

                if( $quizReplies instanceof eZContentObjectAttribute )
                {
                    /* @type $quizRepliesContent eZMatrix */
                    $quizRepliesContent = $quizReplies->content();
                    $replies            = $quizRepliesContent->Matrix['rows']['sequential'];
                    $repliesList        = array();
                    $finalReplies       = array();

                    foreach( $replies as $reply )
                        $repliesList[] = $reply['columns-by-id'];

                    foreach($repliesList as $reply)
                    {
                        $i = 0;
                        $replyAttr = array();
                        foreach($reply as $attr)
                        {
                            if($i == 0)
                                $replyAttr['index'] = $attr;
                            else
                                $replyAttr['label'] = $attr;
                            $i++;
                        }
                        $finalReplies[] = $replyAttr;
                    }
                    $this->pushResult( 'replies', $finalReplies );
                }
            }
            $this->pushResult( 'quiz_id', $this->node->object()->attribute('id') );
        }

        $this->pushResult( 'is_mobile', ContextTool::instance()->isMobile() );

        parent::htmlBuildResult();

        return true;
    }
    /**
     * @return string
     */
    protected function startCourseOverWsdl()
    {
        $courseId    = ( isset( $_POST['courseid'] ) && filter_var($_POST['courseid'], FILTER_VALIDATE_REGEXP, SecurityTool::$ELEARNING_COURSEID_REGEXP) ) ? $_POST['courseid'] : null;
        
        $soapUrl            = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'WsdlUrl');
        $credentialLogin    = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'WsdlLogin');
        $credentialPassword = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'WsdlPassword');
        $useLocale          = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'UseLocale');
        $locale             = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'Locale');
        
        $credentials = array(
            'login'    => $credentialLogin,
            'password' => $credentialPassword,
        );
        
        $params = array(
            array(
                'username' => MMUsers::getCurrentUserId(),
                'courseID' => $courseId,
            )
        );
        
        if ( $useLocale )
        {
            $params[0]['locale'] = $locale;
        }
        
        try
        {
            $soap   = new SoapClientAuth( $soapUrl, $credentials );
            $result = $soap->__soapCall( 'UnivadisEncrypt', $params );
            
            if ( isset($result) && isset($result->return) )
            {
                $url = $result->return;
                if ( strpos($url, 'http') !== 0 || strpos($url, 'https') !== 0)
                {
                    $url = 'http://' . $url;
                }
                
                if ( !ContextTool::instance()->isMobile() )
                {
                    $url = urlencode( urlencode( $url ) );
                    $url = '/external/deeplink?deeplink=' . $url . '&exit_strategy=0';
                }
                
                return $url;
            }
        }
        catch ( SoapFault $f )
        {
        }

        return false;
    }
    /**
     * @param bool $forAnonmyous
     * @param null $processedUserCustomerType
     * @return int[]
     */
    public static function fetchAuthorizedApplicationIds( $forAnonmyous = false, $processedUserCustomerType = null )
    {
        if( !$forAnonmyous && !is_null(self::$_authorizedApplications) )
            return self::$_authorizedApplications;
        $db = MMDB::instance();

        $customerType   = null;
        $mainSpeciality = null;

        $whereString = sprintf(
            "     cluster_identifier='%s' 
              AND environment & %d",
            $db->escapeString(ClusterTool::clusterIdentifier()),
            ContextTool::instance()->environment()
        );
        
        $user = $forAnonmyous ? false : MMUsers::getCurrentUserObject();

        if( $user )
        {
            /* @var $user MMUsers */
            $user = MMUsers::getCurrentUserObject();

            $customerType   = $user->attribute('customer_type');
            $mainSpeciality = $user->attribute('main_speciality');

            if( $user->hasAttribute('prefered_language'))
            {
                $language = $user->attribute('prefered_language');

                $whereString.= sprintf(
                    " AND ( language = '%s' OR language IS NULL OR language = '0' )",
                    $db->escapeString($language)
                );
            }

            if( $user->hasAttribute('country'))
            {
                $country = $user->attribute('country');

                $whereString.= sprintf(
                    " AND ( country = '%s' OR country IS NULL OR country = '0' )",
                    $db->escapeString($country)
                );
            }
        }

        if (!$customerType && $processedUserCustomerType) {
            $customerType = $processedUserCustomerType;
        }
        $whereString .= is_null($customerType)
            ? ' AND customer_type IS NULL '
            : sprintf( " AND ( customer_type IS NULL OR customer_type = '0' OR customer_type='%s') ", $db->escapeString($customerType) );
        $whereString .= is_null($mainSpeciality)
            ? ' AND main_speciality IS NULL '
            : sprintf( " AND ( main_speciality IS NULL OR main_speciality = '0' OR main_speciality='%s') ", $db->escapeString($mainSpeciality) );

        $sql = "SELECT *
            FROM mm_country_application_library
            WHERE
            ".$whereString."
            ORDER BY country DESC, language DESC, customer_type DESC, main_speciality DESC";

        $lastProfile    = null;
        $excludedApps   = array();
        $applicationIds = array();

        foreach( $db->arrayQuery($sql) as $row )
        {
            $profile = serialize( array($row['customer_type'], $row['main_speciality']) );
            if( !is_null($lastProfile) && $profile != $lastProfile )
                break;

            $lastProfile = $profile;

            if( $user && $user->hasAttribute('state') && !is_null($user->attribute('state')) && $row['state'] === $user->attribute('state') )
            {
                $excludedApps[] = (int)$row['application_id'];
                continue;
            }

            $applicationIds[] = (int) $row['application_id'];
        }

        if( !empty($excludedApps) )
        {
            foreach ( $applicationIds as $k => $appId )
            {
                if( in_array($appId, $excludedApps ) )
                    unset( $applicationIds[$k] );
            }
            $applicationIds = array_values($applicationIds);
        }
        
        if(SolrSafeOperatorHelper::featureIsActive('LearningNeedsAssessment'))
        {
            $applicationIds[] = ApplicationObject::fetchByIdentifier('learning-needs-assessment')->attribute('id');
        }

        $applicationIds = array_unique( $applicationIds );

        if( !$forAnonmyous )
            self::$_authorizedApplications = $applicationIds;

        return $applicationIds;
    }
$previousEntriesFile = eZSys::cacheDirectory().'/solrpendingmonitor.json';
$previousEntries =    file_exists( $previousEntriesFile )
                    ? json_decode( file_get_contents($previousEntriesFile), true )
                    : array();

foreach ( $previousEntries as $date => $row )
{
    if ( ( time() - strtotime($date) ) <= $alertPeriod )
    {
        if ( ( $retriesCount - $row['retriesCount'] ) >= $alertThreshold )
        {
            // Alert!!!
            $to = '*****@*****.**';
            $from = eZINI::instance()->variable('MailSettings', 'EmailSender');
            $subject = '[' . ContextTool::instance()->environment() . '] Solr Pending list Alert!! Threshold reached for index errors';
            $message = ( $retriesCount - $row['retriesCount'] ) . " objects failed to index within the last " . $alertPeriod . " seconds";

            $email = new MailTool( $subject, $from, $to, $message, 'solrpendingmonitor_email.log');
            return $email->sendMail();
        }
    }
    else
    {
        unset( $previousEntries[$date] );
    }
}


$previousEntries[date('Y-m-d H:i:s')] = array(
    'retriesCount'  => $retriesCount,
    /**
     * Fetches a page using params
     *
     * @param array $params Fetch parameters for the page
     * @return null or instance of MMStaticPage
     **/
    public static function fetchBy( $params )
    {
        $environmentOriginal = $params['environment'];
        if( ContextTool::instance()->isMobile() )
        {
            $params['target_platform'] = 'MOBILE';
        }

        $page = self::fetchObject( self::definition(), null, $params, true );

        if ( !$page && self::shouldFallbackToProdEnv() )
        {
            $params['environment'] = self::ENV_PROD;
            $page = self::fetchObject( self::definition(), null, $params, true );
        }
        
        if( !$page && ContextTool::instance()->isMobile() )
        {
            $params['environment'] = $environmentOriginal;
            $params['target_platform'] = 'WEB';
            $page = self::fetchObject( self::definition(), null, $params, true );
        }

        if ( !$page && self::shouldFallbackToProdEnv() )
        {
            $params['environment'] = self::ENV_PROD;
            $page = self::fetchObject( self::definition(), null, $params, true );
        }

        if( !$page )
        {
            return null;
        }

        $page->setAttribute( 'core_content', str_replace( '/bundles/static-data/', '/esibuild/static/', $page->attribute( 'core_content' ) ) );

        return $page;
    }
    /**
     * @param string $token
     * @param string $uumpId
     * @param string $email
     * @param bool $isConsult
     */
    protected function sendResetPasswordMail($token, $uumpId, $email, $isConsult = false)
    {
        if ( $isConsult ) {
            $baseUrl = 'consult/';
        }
        $baseUrl .= SolrSafeOperatorHelper::getApplicationUrl('reset-password');
        eZLog::write(var_export("Base url is {$baseUrl}", true) , 'resetpass.log');
        $url =  ContextTool::instance()->domain() . "/{$baseUrl}/(token)/{$token}";
        eZLog::write("URL: {$url}", 'esb_uump.log');
        eZLog::write("URL: {$url}", 'resetpass.log');

        $this->sendMailWrapper("MailServiceResetPasswordTemplateId", $uumpId, $email, $url, $isConsult);
    }
    /**
     * @param null $customerType
     * @param null $speciality
     * @param null $limit
     * @return array
     */
    public static function fetchBanners($customerType = null, $speciality = null, $limit = null)
    {
        $user = MMUsers::getCurrentUserObject();
        if($user)
        {
            $speciality = $user->attribute("user_speciality");
            $customerType = $user->customerTypeId();
        }

        $channels = self::fetchFeaturedByProfile($customerType, $speciality, $limit);
        $banners = array();

        $environment = ContextTool::instance()->environment();
        /** @var FeaturedChannel $channel */
        foreach($channels as $channel)
        {
            $application = $channel->application();
            if ($application == null) {
                continue;
            }
            $applicationLocalized = $application->applicationLocalized();
            if (!$applicationLocalized || !($applicationLocalized->attribute('environment') & $environment))
            {
                continue;
            }

            $channelConfiguration = ChannelConfiguration::getChannelConfigurationByApplicationLocalizedId($applicationLocalized->attribute("id"));

            $title = $channel->attribute("title");
            $subtitle = $channel->attribute("subtitle");

            if(!$title)
            {
                $title = $applicationLocalized->attribute("headline");
            }
            
            if(!$subtitle)
            {
                $subtitle = $channelConfiguration->attribute("subtitle");
            }

            $banners[] = array(
                "title" => $title,
                "subtitle" => $subtitle,
                "url"   => "/".$applicationLocalized->attribute("url"),
                "cover" => $channel->getCoverPath($channelConfiguration),
                "icon_small" => $channel->getIconSmallPath($channelConfiguration),
                "new" => $channel->getNewImage($channelConfiguration),
                "color" => $channel->getColor($channelConfiguration),
            );
        }

        return $banners;
    }
 public function htmlBuildResult()
 {
     $this->pushResult( 'is_mobile', ContextTool::instance()->isMobile() );
     $this->pushResult( 'anonymousUrl', $this->anonymousUrl );
     $this->pushResult( 'parisSynchHour', SolrSafeOperatorHelper::feature( 'merckConnectWebServices', 'parisSynchHour' ) );
 }
    /**
     * @return eZTemplate
     */
    public function tpl()
    {
        if(is_null($this->_tpl))
        {
            eZTemplate::resetInstance();
            $this->_tpl = eZTemplate::factory();

            if (SolrSafeOperatorHelper::featureIsActive('showMedicalNewsDemo') && SolrSafeOperatorHelper::feature('ShowMedicalNewsDemo', 'showDemo')){
                $showMedicalNewsDemo = true;
                
            }else {
                $showMedicalNewsDemo = false;
            }
            
            $this->_tpl->setVariable('showMedicalNewsDemo',$showMedicalNewsDemo);
            
            $this->_tpl->setVariable('language'          , LocaleTool::languageISO639Code());
            $this->_tpl->setVariable('application_class' , get_class($this) );
            $this->_tpl->setVariable('view_parameters'   , $this->_params['UserParameters']);
            $this->_tpl->setVariable('cluster_identifier', ClusterTool::clusterIdentifier());
            $this->_tpl->setVariable('application_url'   , $this->applicationName());
            $this->_tpl->setVariable('consult'           , $this->isConsult);
            $this->_tpl->setVariable('httpcontext'       , array(
                'host'  => ContextTool::instance()->domain(),
            ));

            $environment = new MMEnvironment();
            $this->_tpl->setVariable('environment'       , $environment->env);

            $applicationLocalized = CacheApplicationTool::buildLocalizedApplication($this->applicationName());

            if (empty($applicationLocalized))
                $this->_tpl->setVariable('application_name'  , $this->applicationName());
            else
            {
                $applicationIdentifier = $applicationLocalized->applicationObject->attribute('identifier');

                $this->_tpl->setVariable('application_name' , $applicationIdentifier );
                $this->_tpl->setVariable('current_localized' , $applicationLocalized );
                $this->_tpl->setVariable('current_application' , $applicationLocalized->applicationObject );
            }
        }

        return $this->_tpl;
    }
    $isConsentOptOut = in_array( ClusterTool::clusterIdentifier(), array() );

    $displayToUPPAndOptInsBlockTitle = in_array( ClusterTool::clusterIdentifier(), array( 'cluster_france' ) );
    
    $visitorCountry = SolrSafeOperatorHelper::getLocaleBySystemCode( 'ga_visitor_country' );
    if( $visitorCountry == 'not provided' || !isset($visitorCountry) || is_null($visitorCountry) || empty($visitorCountry)){
        
        $dt = new DateTime("Europe/Warsaw");
        $msg = 'Missing ga_visitor_country for '.ClusterTool::clusterIdentifier().' at '.$dt->format('Y-m-d H:i:s');
        ezLog::write($msg, 'toupp_visitor_country.log');
    }

    echo json_encode( array(
        'userProfile'      => $userProfile,
        'displayConsents'  => $displayConsents,
        'useDedicatedPage' => (ContextTool::instance()->isMobile() ? SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'useDedicatedPageMobile' ) : SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'useDedicatedPage' )),
        'visitorCountry'   => SolrSafeOperatorHelper::getLocaleBySystemCode( 'ga_visitor_country' ),
        'staticPages'      => array(
            'ToU' => is_null( $touPage ) ? null : $touPage->attribute( 'core_content' ),
            'PP'  => is_null( $ppPage ) ? null : $ppPage->attribute( 'core_content' )
        ),
        'features'         => array(
            'currentToUConsentVersion'        => $currentToUConsentVersion,
            'currentPPConsentVersion'         => $currentPPConsentVersion,
            'hasCheckbox'                     => $hasCheckbox,
            'precheckedCheckbox'              => $precheckedCheckbox,
            'adaptConsentText'                => $adaptConsentText,
            'isConsentOptOut'                 => $isConsentOptOut,
            'displayToUPPAndOptInsBlockTitle' => $displayToUPPAndOptInsBlockTitle,
            'touPPCheckboxFeatures'           => $touPPCheckboxFeatures,
            'optInFeatures'                   => $optInFeatures,
<?php

require 'autoload.php';

$script = eZScript::instance( array(
    'description'    => ( "Get the newsletter feed consumed by Creator mail" ),
    'use-modules'    => true,
    'use-extensions' => true,
    'debug-output'   => false,
) );

$script->startup();
$script->initialize();

if ( ContextTool::instance()->environment() != ContextTool::ENVIRONMENT_PROD )
    $script->shutdown( 1, "This script can only be run on production" );

$options = $script->getOptions( "[cluster:][nlt:][frq:]", array(
    'cluster'   => 'Cluster identifier',
    'nlt'       => 'Newsletter type [news|education]',
    'frq'       => 'Frequency [daily|ẁeekly|monthly]'
) );

$cli = new QuestionInteractiveCli();

$clusterIdentifier  = isset ( $options['cluster'] ) ? $options['cluster'] : false;
$nlType             = isset( $options['nlt'] ) ? $options['nlt'] : null;
$nlFrequency        = isset( $options['frq'] ) ? $options['frq'] : null;

$clusterDomains = eZINI::instance( 'merck.ini' )->variable( 'DomainMappingSettings', 'ClusterDomains' );
if ( !$clusterIdentifier )
    /**
     * Sends an alert if necessary for quarentaines
     */
    protected function sendAlert()
    {
        if ( count($this->quarantaineFiles) > 0 )
        {
            $envArray    = array(
                ContextTool::ENVIRONMENT_DEV => "dev",
                ContextTool::ENVIRONMENT_STAGING => "stg",
                ContextTool::ENVIRONMENT_PROD => "prod",
            );
            $environment = ContextTool::instance()->environment();
            $subject     = "[MERCK-IMPORT][{$envArray[$environment]}] Article putted on quarantaine";
            $from        = eZINI::instance()->variable('MailSettings', 'EmailSender');
            $to          = array(XMLImportMonitor::EMAIL_LIST);
            $body        = "Hello,\n\nthe following article has reached the maximum of import attempts and has been putted on quarantaine :\n%s\n\nRegards,\nAdministrator";
            $body        = sprintf($body, $this->implodeQuarentaineText());

            if ( $envArray[$environment] == "prod" )
                $to[] = '*****@*****.**';

            $email = new MailTool( $subject, $from, $to, $body, 'import_monitoring_email.log');
            $email->sendMail();
        }
    }
    /**
     * Relog the user if rememberme is checked and not logged in
     * @param bool $try
     * @throws Exception
     * @return boolean
     */
    public static function relog($try = false)
    {
        $out = array('session_lifetime' => intval(eZINI::instance('merck.ini')->variable('WSMobile', 'SessionLifetime')));

        $backendUrl = eZINI::instance('merck.ini')->variable('WSMobile', 'BackEndUrl');
        $c = curl_init();
        curl_setopt($c, CURLOPT_URL, $backendUrl.'/mobile.php');
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($c, CURLOPT_NOBODY, true);
        curl_setopt($c, CURLOPT_HEADER, true);
                        
        if ( eZINI::instance('merck.ini')->hasVariable('WSMobile', 'BackEndHeader') )
        {
            /* @type $headers array */
            $headersList = array();
            $headers = eZINI::instance('merck.ini')->variable('WSMobile', 'BackEndHeader');
            foreach ( $headers as $header => $value )
            {
                $headersList[] = sprintf('%s: %s', $header, $value);
            }
            curl_setopt($c, CURLOPT_HTTPHEADER, $headersList);
        }
        $headers = getallheaders();
        if( isset($headers['Cookie']) )
            curl_setopt($c, CURLOPT_COOKIE, $headers['Cookie']);

        $result = curl_exec($c);
        $errno = curl_errno($c);
        $error = curl_error($c);
        curl_close($c);
        
        $loggedOnBackend = true;
        if(    preg_match( '#^HTTP/1.1 302 Found#', $result )
               || (
                   preg_match( '#Set-Cookie: .*BSESSIONID=(?P<baksess>.*?);#m', $result, $m )
                && isset( $_COOKIE['BESSIONID'] )
                && $_COOKIE['BESSIONID'] != $m['baksess']
               )
        ){
            $loggedOnBackend = false;
        }
        
        if ( self::isLogged() && $loggedOnBackend )
        {
            return $out;
        }
        
        if ( isset($_COOKIE['remember_me']) )
        {
            $db = MMDB::instance();
            $corQuery = "SELECT r.code
            FROM bo_reference r
            JOIN bo_cluster_has_reference chr ON chr.cluster_identifier = '%s'
            WHERE r.type = 'country' AND r.id = chr.reference_id";
            $cor = $db->arrayQuery( sprintf( $corQuery, ClusterTool::clusterIdentifier() ) );
            if( count( $cor ) > 0 )
                $countryOfRegistration = $cor[0]['code'];
            else
                $countryOfRegistration = eZINI::instance('site.ini')->variable('RegionalSettings', 'CountryOfRegistration');

            $uuid = MMUserLogin::uncryptTicket($_COOKIE['remember_me']);
            $context = isset( $_REQUEST['context'] ) ? $_REQUEST['context'] : ContextTool::instance()->domain() . '/';
            $readService = ESBFactory::getUserService();
            $parameters  = $readService->getFormParameters($uuid);
            $datas       = $readService->read( $parameters, $uuid );
            $esbResult   = new ESBResult();

            $isPopulated = ServiceLoginUUMP::populateESBResult( $esbResult, $datas );
            
            if ( !$isPopulated )
            {
                // error log caught on WS stack
                return null;
            }

            $loginResult = MMUserLogin::esbLogin( $uuid, $esbResult, true, $context );
            
            if( is_null( $loginResult ))
            {
                $out['status'] = 'failed';
                $out['errorCode'] = 9; 
                $out['msg'] = 'User not found.';
                return $out;
            }
            
            $user = MMUsers::fetchByIdAndCountry($loginResult['params']['Username'], $countryOfRegistration);

            $loginResult['params']['mmSettings']       = $user->getMMSettings();
            $loginResult['params']['unorderedAppList'] = $user->getApplicationList();
            $loginResult['params']['alterboxMsgReset'] = $user->hasPreference('alterboxMsgReset') ? $user->getPreferences('alterboxMsgReset') : true;

            $logged = self::backendLog($loginResult['params']);

            if ( $logged )
            {
                return $out;
            }
        }

        if ( $try !== true )
        {
            throw new Exception('Missing "remember_me" cookie', 30);
        }

        return false;
    }
    /**
     * @param string $applicationIdentifier
     * @return bool
     */
    public static function seoIsEnabled($applicationIdentifier)
    {
        $featureEnabled = self::featureIsActive('Seo');
        if ( !$featureEnabled )
            return false;

        /** @var ApplicationLocalized $applicationLocalized */
        $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier($applicationIdentifier);
        if(!$applicationLocalized)
            return false;

        $seoParams = $applicationLocalized->seoParams();
        if(!$seoParams)
            return false;

        $enabled = $seoParams->attribute("enabled");
        if(!$enabled)
            return false;

        return ContextTool::instance()->compareMask($enabled);
    }
    /**
     * @param int $applicationIdentifier
     * @param string $clusterIdentifier
     * @return ApplicationLocalized
     */
    public static function getLocalizedApplicationByIdentifier( $applicationIdentifier, $clusterIdentifier = null )
    {
        $conditions = array(
            'identifier' => $applicationIdentifier,
        );

        $applicationArray = ApplicationObject::fetchObject(
            ApplicationObject::definition(),
            null,
            $conditions,
            false
        );

        if ( is_array( $applicationArray ) && isset($applicationArray["id"]) )
        {
            $conditions = array(
                'application_id'     => $applicationArray["id"],
                'cluster_identifier' => $clusterIdentifier == null ? ClusterTool::clusterIdentifier() : $clusterIdentifier,
            );

            $result = self::fetchObject (
                self::definition(),
                null,
                $conditions
            );
    
            if ( !$result || !($result->attribute('environment') & ContextTool::instance()->environment() ) )
                return null;
    
            return $result;
        }
        else
        {
            return null;
        }
    }
// Suppression session EZP
MMUserLogin::logoutUser();

// Redirection vers logoutActions.php (Suppression session PHP-ESI)
$redirectURL = "/logoutActions.php";
if ( isset( $_GET['context'] ) )
{
    $context = urldecode( $_GET['context'] );

    if ( preg_match( '#^(?:https?://|/)#', $context ) )
    {
        if ( strpos( $context, '/' ) === 0 )
        {
            $context = ContextTool::instance()->domain() . $context;
        }
        if ( ContextTool::instance()->checkRedirectUrl( $context ) )
        {
            $redirectURL .= '?context='.urlencode( $context );
        }
    }

}

$isUserAction = ( isset( $Params['isUserAction'] ) && $Params['isUserAction'] );
if( $isUserAction )
{
    CookieTool::destroyCookie( 'remember_me' );
    CookieTool::destroyCookie( 'unorderedAppList' );
    CookieTool::destroyCookie( eZINI::instance( 'merck.ini' )->variable( 'TIBCOCookieSettings', 'TIBCOCookieName' ) );
    $cookiesToInvalidate = eZINI::instance( 'merck.ini' )->variable( 'LogoutSettings', 'InvalidateCookies' );
    if (is_array($cookiesToInvalidate))
    /**
     * @param ApplicationDefault $contentApp
     * @return array
     */
    private function oldPromoPage( $contentApp )
    {
        $promoLoginUri  = eZINI::instance()->variable('SiteSettings', 'PromoLoginPage');
        $promoLoginPath = preg_replace('#^https?://[^/]+/#', '/', $promoLoginUri);

        if(    (bool)self::user()
            && !self::user()->toUValidated()
            && $this->iniMerck()->hasVariable( 'LoginSettings', 'ToUCheck' )
            && $this->iniMerck()->variable( 'LoginSettings', 'ToUCheck') != 'disabled'
        ){
            $promoLoginUri = eZINI::instance()->variable('SiteSettings', 'ToUAgreementPage');
            $promoLoginPath = preg_replace('#^https?://[^/]+/#', '/', $promoLoginUri);
        }

        $patterns   = array(
            '#^(?:https?://[^/]+)?/esibuild/main_view/app_content#',
            '#\?key=[^&]+#'
        );
        $context    = ContextTool::instance()->domain().preg_replace($patterns, array( '', '' ), $_SERVER['REQUEST_URI'] );

        // for externals, we need to redirect to the promologin page
        if( !isset($_GET['key'] ) &&  $this->applicationObject()->hasExternalLinkHandler() )
        {
            $context = preg_replace( '#^(https?://[^/]+/)#', '\1external/', $context );
            header( 'Location: '.ContextTool::instance()->domain().$promoLoginUri.'?context='.urlencode($context) );
            eZExecution::cleanExit();
        }

        if(strpos($promoLoginPath, '/page') !== 0)
            $promoLoginPath = '/page'.$promoLoginPath;
        $app = ApplicationFactory::fetchByUri( $promoLoginPath );

        if( empty( $app->node ) )
        {
            if( in_array( ContextTool::instance()->environment(), array(ContextTool::ENVIRONMENT_PROD, ContextTool::ENVIRONMENT_STAGING) ) )
            {
                openlog( 'Missing Promo page', LOG_PID, LOG_LOCAL6 );
                syslog( LOG_CRIT, 'Error message' );
                closelog();
            }
            else
            {
                $out = 'Promo page can not be loaded for the cluster: '.ClusterTool::clusterIdentifier();
                eZDebug::writeError( $out, 'Missing Promo page' );
            }
        }

        $app->buildResult();

        $app->pushResult('context', urlencode( $context ));
        $this->tpl()->setVariable('staticnode', $contentApp->node);

        if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
        {
            $this->tpl()->setVariable( 'gtm_variables', $this->getGTMTags( $contentApp->node ) );
            if( $contentApp->node )
            {
                $publisherNode = NodeTool::getPublisherNodeFromNode($contentApp->node);
                if ($publisherNode)
                {
                    /* @type eZContentObjectAttribute[] $publisherDM */
                    $publisherDM   = $publisherNode->dataMap();
                    $publisherPath = $publisherDM['path']->content();
                    $this->tpl()->setVariable( 'publisher', $this->applicationLocalized()->getPublisherFolderFromPath( $publisherPath ) );
                }
            }
        }

        return $app->getHtmlResult();
    }