/**
     * @param string $clusterIdentifier
     * @return array
     */
    public static function getForbiddenWordsArray ( $clusterIdentifier )
    {
        if (!isset(self::$forbiddenWordsArray))
            self::$forbiddenWordsArray = array();
        
        if ( !isset(self::$forbiddenWordsArray[$clusterIdentifier]) )
        {
            $db         = MMDB::instance();
            $query      = sprintf( "SELECT forbidden_words FROM bo_cluster where identifier='%s'", $clusterIdentifier );
            $results    = $db->arrayQuery($query);
            
            if ( $results )
                $forbiddenWords = trim($results[0]["forbidden_words"]);

            if( !isset($forbiddenWords) || empty($forbiddenWords) )
            {
                self::$forbiddenWordsArray[$clusterIdentifier] = array();
                return array();
            }

            $forbiddenWordsSplit = preg_split( "/(\r\n|\n|\r)/", $forbiddenWords, -1, PREG_SPLIT_NO_EMPTY );
            $tmp = array();
            foreach( $forbiddenWordsSplit as $word )
            {
                if (trim($word) != '')
                    $tmp[] = '-"'.addcslashes(trim($word), '"').'"';
            }
            $forbiddenWordsArray = array_unique( $tmp, SORT_LOCALE_STRING );
            
            self::$forbiddenWordsArray[$clusterIdentifier] = $forbiddenWordsArray;
        }
        
        return self::$forbiddenWordsArray[$clusterIdentifier];
    }
    /**
     * @return bool
     */
    private static function loadConfiguration()
    {
        if( !empty( self::$fields ) )
        {
            return false;
        }

        $db = MMDB::instance();

        $clusterIdentifier = ClusterTool::clusterIdentifier();

        $query = 'SELECT f.business_name, f.attribute_type, l.default_value,
                  CASE WHEN l.control_type_identifier IS NULL THEN f.control_type_identifier ELSE l.control_type_identifier END AS control_type_identifier,
                  CASE WHEN l.control_type_value IS NULL THEN f.control_type_value ELSE l.control_type_value END AS control_type_value
                  FROM uump_field AS f INNER JOIN uump_localized_field AS l ON l.field_id = f.id AND l.cluster_identifier = "%s"
                  ORDER BY f.business_name';
        $results = $db->arrayQuery( sprintf( $query, $clusterIdentifier ) );

        foreach( $results as $result )
        {
            self::$fields[$result['business_name']] = array(
                'control_type_identifier' => $result['control_type_identifier'],
                'control_type_value'      => $result['control_type_value'],
                'attribute_type'          => $result['attribute_type'],
                'default_value'           => $result['default_value']
            );
        }

        return true;
    }
    /**
     * @param eZINI $importINI
     * @param string $ftpFolder
     * @param bool $modeUAT
     * @throws Exception
     */
    protected function __construct( $importINI, $ftpFolder, $modeUAT )
    {
        $this->importINI            = $importINI;
        $this->rootImportFolder     = $this->importINI->variable( 'XMLImportSettings', 'RootImport' . ucfirst( $ftpFolder ) );
        $this->dataSources          = array();
        $this->dataSourceIterator   = -1;
        $this->dataSourcesCount     = 0;
        $this->dataSourcesCompleted = 0;
        $this->ftpFolder            = $ftpFolder;
        self::$modeUAT              = $modeUAT;
        $this->publisherFolder      = array();
        $this->publisherFolderName  = array();
        $mmDB                       = MMDB::instance();
        $sql                        = "SELECT id,default_language,default_language_medias,path FROM mm_publisher_folder WHERE source='ftp'";
        $results                    = $mmDB->arrayQuery( $sql );

        if ( !$results )
            throw new Exception ( 'No publisher folder declared' );

        foreach ( $results as $result )
        {
            $this->publisherFolder[$result['path']] = $result;
            $this->publisherFolderName[$result['id']] = $result['path'];
        }
    }
    /**
     * @return array
     */
    public static function taxonomyAttribute()
    {
        if( is_null( self::$_taxonomyAttributes ) )
        {
            self::$_taxonomyAttributes = array();
            $db = MMDB::instance();
            foreach( $db->arrayQuery("SELECT identifier FROM mm_taxonomy_category GROUP BY identifier") as $row )
                self::$_taxonomyAttributes[] = $row['identifier'];
        }

        return self::$_taxonomyAttributes;
    }
    /**
     * @return string[]
     */
    public function city()
    {
        if ( !isset($_GET['city']) )
        {
            return false;
        }

        $db = MMDB::instance();
        $city = $db->escapeString(trim($_GET['city']));

        return ChinaLocation::fetchDistrictsAndHospitalsByCity($city);
    }
    public function organisation()
    {
        if ( !isset($_GET['organisation']) )
        {
            return false;
        }

        $db = MMDB::instance();
        $organisation = $db->escapeString(trim($_GET['organisation']));
        
        return ReferentialValue::fetchReferentialByIdentifierForAutoComplete('organisationName', $organisation, 'asc', 10);
    }
    /**
     * @param string clusterIdentifier
     * @param array $applicationIds
     * @return string
     */
    protected function bulidUpdateXml( $clusterIdentifier, $applicationIds = array() )
    {
        $xml = '<add>';

        $sql  = $this->getSql( $clusterIdentifier );
        if ( !empty( $applicationIds ) )
        {
            $sql .= sprintf( " AND a.id IN ('%s')", implode( "','" , $applicationIds ) );
        }

        $applications = MMDB::instance()->arrayQuery( $sql );
        foreach( $applications as $row )
        {
            $application = new ApplicationLocalized( $row );

            $cacheApp = CacheApplicationTool::buildLocalizedApplicationByLocalizedId($application->id);
            
            if( !($cacheApp instanceof ApplicationLocalized) )
            {
                continue;
            }     
            $xml .= '<doc>';
            $this->addField( $xml, self::META_INSTALLATION_ID_MS_KEY, self::META_INSTALLATION_ID_MS_VAL );
            $this->addField( $xml, 'meta_guid_ms', md5( $application->application_id ) . "-{$application->cluster_identifier}" );
            $this->addField( $xml, 'identifier_s', $row['application_identifier'] );
            $this->addField( $xml, 'name_s', htmlspecialchars( $application->name ) );
            $this->addField( $xml, 'cluster_identifier_s', $application->cluster_identifier );

            $headlineKeywords = $this->prepareHeadlineKeywords($application->headline);

            foreach ($headlineKeywords as $headlineKeyword) {
                $this->addField( $xml, self::HEADLINE_KEYWORD, self::prepareKeywordString( $headlineKeyword ) );
            }


            $keywords = $application->getKeywords();
            if ( is_array( $keywords ) )
            {
                foreach ( $keywords as $keyword )
                {
                    $this->addField( $xml, self::META_APPLICATION_KEYWORD, self::prepareKeywordString( $keyword ) );
                }
            }
            $xml .= '</doc>';
        }

        $xml .= '</add>';
        return $xml;
    }
    /**
     * @return array
     */
    public function getAllApplicationLocalizedIds()
    {
        $db = MMDB::instance();
        $query 	= "SELECT id
		  	   FROM mm_application_localized
		  	   WHERE application_id='".$this->application->application_id."'";
        $buffer = $db->arrayQuery( $query );

        $ids = array();
        foreach($buffer as $row)
        {
            $ids[] = $row['id'];
        }

        return $ids;
    }
 /**
  * Fetches block attached to this zone
  *
  * Only blocks that matches the current enviornment bitmask will be
  * returned.
  *
  * @param int $currentEnvId Int of current enviornment
  * @param string $clusterIdentifier
  * @return MMBlock[] Array
  */
 public function fetchBlocks( $currentEnvId, $clusterIdentifier )
 {
     $db = MMDB::instance();
     $query = "SELECT block.*
         FROM
             mm_block AS block
         JOIN
             mm_homepage_zone_has_block AS join_tbl ON join_tbl.block_id = block.id
         WHERE
             join_tbl.zone_id = {$this->ID}
             AND join_tbl.environment & {$currentEnvId}
             AND join_tbl.cluster_identifier = '{$clusterIdentifier}'
         ORDER BY
             join_tbl.position";
     $rows = $db->arrayQuery( $query );
     if ( $rows && count( $rows ) >= 1 )
         return eZPersistentObject::handleRows( $rows, "MMBlock", true );
 }
    /**
     * Convert all values in translation_value which begin by 'js' to a JS file
     */
    private function convertDB()
    {
        $db     = MMDB::instance();
        $tabJs  = array();

        $sql = "SELECT id, name
FROM ezx_translation_context
WHERE status = 2
AND name like 'js%'";
        $contexts = $db->arrayQuery($sql);

        foreach($contexts as $context)
        {
            $name       = $context["name"];
            $newArray   = array();

            $env = eZINI::instance( "site.ini.append.php" )->variable("Environment", "Type");
                    
            if($env){
                switch ($env){
                    case 'prod':
                        $messages = eZTranslationContext::fetchValidatedTranslations( $name, $this->_locale );
                        break;
                    default :
                        $messages = eZTranslationContext::fetchPendingTranslations( $name, $this->_locale );
                        break;
                }
            }
            
            foreach($messages as $message)
            {
                $source             = $message["source"];
                $translation        = $message["translation"];
                $newArray[$source]  = $translation;
            }

            $this->explodeRecursif(explode('/', $name), 0, $tabJs, $newArray);
        }

        $this->saveJS($tabJs['js']);
    }
    /**
     * @param string $clusterIdentifier
     * @param string $systemCategory
     * @return string
     */
    static public function fetchByClusterAndSystem( $clusterIdentifier, $systemCategory )
    {
        $sl = CacheTool::dailyValue( 'systemLocale' );

        if( $sl === false || is_null( $sl ) )
        {
            $db = MMDB::instance();
            $sls = self::fetchByClusterIdentifier( $clusterIdentifier );
            $cachedValues = array();
            foreach( $sls as $sl )
            {
                $referenceQuery = "SELECT code FROM bo_reference WHERE id = " . $sl->attribute( 'system_reference_id' );
                $ref = $db->arrayQuery( sprintf( $referenceQuery, $sl->attribute( 'system_reference_id' ) ) );
                if( count( $ref ) > 0 )
                {
                    $cachedValues[$ref[0]['code']] = $sl->attribute( 'value' );
                }
            }
            CacheTool::dailyValue( 'systemLocale', $cachedValues );
            $sl = CacheTool::dailyValue( 'systemLocale' );
        }

        return $sl[$systemCategory];
    }
 /**
  * @return eZMySQLiDB
  */
 private static function db()
 {
     return MMDB::instance();
 }
$ini = eZIni::instance('merck.ini');
$db = MMImportMonitorHelper::db();
$sql = '
    SELECT st.date as st_date, st.xml_file as st_xml_file, c.publisher_folder_id as c_publisher_folder_id
    FROM import_status as st
    LEFT JOIN article as a ON a.id = st.article_id
    LEFT JOIN content as c ON a.content_id = c.id
    LEFT JOIN publisher_folder as p ON c.publisher_folder_id = p.id
    WHERE st.id = "%s";
';
$row = reset($db->arrayQuery(sprintf($sql, $db->escapeString($statusId))));

if ( !empty( $row  ) ) {
    $sql = "SELECT p.path as p_path FROM mm_publisher_folder WHERE p.id={$row['c_publisher_folder_id']}";
    $publisherRow = reset( MMDB::instance()->arrayQuery( $sql ) );
    $row['p_path'] = ( empty( $publisherRow ) ? null : $publisherRow['p_path'] );

    $pathPrefix = $ini->variable('ImportMonitor', 'XmlFilePath');
    $path = sprintf('%s/%s/archived/%s_%s', $pathPrefix, $row['p_path'], date('Ymd', $row['st_date']), $row['st_xml_file']);

    if (!empty($row['p_path']) && file_exists($path)) {
        header ("Content-Type:text/xml");
        echo file_get_contents($path);
    }
}
else
{
    header("HTTP/1.0 404 Not Found");
}
    /**
     * @param XMLField[]|XMLField $xmlField
     * @return mixed
     */
    public function getFieldContent($xmlField)
    {
        $rootImport = $this->importINI->variable( 'XMLImportSettings', 'RootImport' );

        if (is_array($xmlField))
        {
            /* @type $xmlField XMLField[] */
            $mapping = XMLImportMapping::getByFieldName($xmlField[0]->getParentType(), $xmlField[0]->internalFieldName);
        }
        elseif (is_null($xmlField->fieldNode))
            return false;
        else
            $mapping = XMLImportMapping::getByFieldName($xmlField->getParentType(), $xmlField->internalFieldName);

        /* @type $xmlField XMLField */
        switch ($mapping['type'])
        {
            case 'text':
            {
                /* @type $xmlField XMLField */
                $fieldContent = strip_tags(trim($xmlField->fieldNode->nodeValue));
                $returnContent = $fieldContent;
            }
            break;
            case 'image':
            case 'video':
            case 'pdf':
            case 'audio':
            case 'contact':
            case 'file':
            case 'media_content':
            case 'html_media':
            {
                if (!is_array($xmlField))
                {
                    try
                    {
                        $xmlFieldBuilder    = new XMLFieldBuilder($this->xmlParser, $this->importINI, $xmlField->fieldNode);
                        $xmlFieldMixer      = new self($xmlFieldBuilder, $this->xmlParser, $this->importINI, $this->publisherInfos, $this->rootImportFolder);
                        $fieldContent       = $xmlFieldMixer->process($mapping['type']);

                        if ( !isset($fieldContent['language']) )
                        {
                            $emulatedXMLField                       = new stdClass();
                            $emulatedXMLField->calculatedValue      = $this->publisherInfos['default_language'];
                            $emulatedXMLField->internalFieldName    = 'language';
                            $fieldContent['language']               = $emulatedXMLField;
                            $illustrativeMediaFields                = XMLImportMapping::getByFieldName('illustrative_media', $xmlField->internalFieldName);

                            if ( $illustrativeMediaFields === false && $this->publisherInfos['default_language_medias'] == 0 )
                                XMLImportMonitor::log($xmlField->internalFieldName . ' : The Field\'s language has been defaulted to ' . $this->publisherInfos['default_language'] . ', publisher settings says it shouldn\'t have.', 'warning');
                        }

                        $returnContent = $fieldContent;
                    }
                    catch (MandatoryException $e)
                    {
                        XMLImportMonitor::log($xmlField->internalFieldName . ' : ' . $e->getMessage(), 'warning');
                    }
                }
                else
                {
                    $returnContent = false;

                    /* @type $xmlField XMLField[] */
                    foreach ($xmlField as $index => $field)
                    {
                        if (is_null($field->fieldNode))
                            continue;

                        try
                        {
                            $xmlFieldBuilder    = new XMLFieldBuilder($this->xmlParser, $this->importINI, $field->fieldNode);
                            $xmlFieldMixer      = new self($xmlFieldBuilder, $this->xmlParser, $this->importINI, $this->publisherInfos, $this->rootImportFolder);
                            $fieldContent       = $xmlFieldMixer->process($mapping['type']);

                            if (is_array($fieldContent) && count($fieldContent) > 0)
                            {
                                if ( !isset($fieldContent['language']) )
                                {
                                    $emulatedXMLField                       = new stdClass();
                                    $emulatedXMLField->calculatedValue      = $this->publisherInfos['default_language'];
                                    $emulatedXMLField->internalFieldName    = 'language';
                                    $fieldContent['language']               = $emulatedXMLField;
                                    $illustrativeMediaFields                = XMLImportMapping::getByFieldName('illustrative_media', $field->internalFieldName);

                                    if ( $illustrativeMediaFields === false && $this->publisherInfos['default_language_medias'] == 0 )
                                        XMLImportMonitor::log($field->internalFieldName . ' : The Field\'s language has been defaulted to ' . $this->publisherInfos['default_language'] . ', publisher settings says it shouldn\'t have.', 'warning');
                                }

                                $field->calculatedValue = $fieldContent;
                                $returnContent          = true;
                            }
                            else
                                unset($xmlField[$index]);

                            $this->blobedFiles = array_merge($this->blobedFiles, $xmlFieldMixer->blobedFiles);
                        }
                        catch (MandatoryException $e)
                        {
                            XMLImportMonitor::log($field->internalFieldName . ':' . $e->getMessage(), 'warning');

                            unset($xmlField[$index]);
                        }
                    }
                }
            }
            break;
            case 'richtext':
            {

                $fieldContent = str_replace(array(
                        "\n\r",
                        "\n",
                        "\r"
                    ), array(
                        ' ',
                        ' ',
                        ' '
                    ), trim($xmlField->fieldNode->nodeValue)
                );

                $returnContent = $fieldContent;
            }
            break;
            case 'taxonomy':
            {
                $fieldContent = str_replace( ' ', '', trim($xmlField->fieldNode->nodeValue) );
                $contentArray = explode('|', $fieldContent);

                if ($contentArray !== false && $contentArray != "")
                {
                    $mmDB = MMDB::instance();

                    foreach ($contentArray as $key => $value)
                    {
                        $value = trim($value);
                        if ($value != "")
                        {
                            //Check if key exists in table 'taxonomy'
                            $result = $mmDB->arrayQuery('SELECT 1 FROM mm_taxonomy WHERE code = "' . $contentArray[$key] . '"');

                            if (empty($result))
                            {
                                XMLImportMonitor::log('The taxonomy {' . $contentArray[$key] . '} in field {' . $xmlField->fieldName . '} doesn\'t exists', 'notice');

                                unset($contentArray[$key]);
                            }
                            else
                                $contentArray[$key] = $value;
                        }
                        else
                            unset($contentArray[$key]);
                    }
                    if (count($contentArray))
                    {
                        $returnContent = array_unique($contentArray);
                    }
                }
            }
            break;
            case 'integer':
            {
                $fieldContent = filter_var(trim($xmlField->fieldNode->nodeValue), FILTER_VALIDATE_INT);

                if ($fieldContent !== false)
                    $returnContent = $fieldContent;
            }
            break;
            case 'date':
            {
                $fieldContent = trim($xmlField->fieldNode->nodeValue);
                $datePattern  = "/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}) (?P<hour>\d{2}):(?P<minute>\d{2})/";

                if (preg_match($datePattern, $fieldContent, $m))
                    $returnContent = "{$m['year']}-{$m['month']}-{$m['day']} {$m['hour']}:{$m['minute']}:00";
            }
            break;
            case 'filename':
            {
                $folderMap = array(
                    'image' => 'images',
                    'html' => 'html',
                    'pdf' => 'pdf',
                    'audio' => 'audio',
                    'video' => 'videos',
                    'link' => 'link',
                    'file' => 'file',
                    'html_media' => 'html'
                );

                if ( trim($xmlField->fieldNode->nodeValue) != "" )
                {
                    $fieldContent = trim($xmlField->fieldNode->nodeValue);

                    if (isset($folderMap[$xmlField->getParentType()]))
                        $folder = $folderMap[$xmlField->getParentType()];
                    else
                        break;
                    
                    $filepathFromRootImport = "{$this->rootImportFolder}/{$this->publisherInfos['path']}/$folder/$fieldContent";

                    if ( file_exists( "$rootImport/$filepathFromRootImport" )
                        || file_exists ( "$rootImport/{$this->rootImportFolder}/{$this->publisherInfos['path']}/archived/$folder/$fieldContent" ) )
                    {
                        if ($mapping['specialProcess'] == 'storeBlob')
                            $returnContent = "$rootImport/$filepathFromRootImport";
                        else
                            $returnContent  = $filepathFromRootImport;
                    }
                    else
                        $fieldContent = "{$this->rootImportFolder}/{$this->publisherInfos['path']}/$folder/$fieldContent";
                }
            }
            break;
            case 'wxh':
            {
                $fieldContent = trim($xmlField->fieldNode->nodeValue);

                if (preg_match("/(\d+)\s*[xX\s]\s*(\d+)/", $fieldContent, $match))
                    $returnContent = "{$match[1]}x{$match[2]}";
            }
            break;
            case 'email':
            {
                $fieldContent = filter_var(trim($xmlField->fieldNode->nodeValue), FILTER_VALIDATE_EMAIL);

                if ($fieldContent !== false)
                    $returnContent = $fieldContent;
            }
            break;
            case 'media_type':
            {
                /* @type $availableRelatedContent array */
                $fieldContent            = strtolower(trim($xmlField->fieldNode->nodeValue));
                $availableRelatedContent = $this->importINI->variable('XMLImportSettings', 'AvailableRelatedContent');

                if (in_array($fieldContent, $availableRelatedContent))
                    $returnContent = $fieldContent;
            }
            break;
            case 'enum':
            {
                $fieldContent = strtolower(trim($xmlField->fieldNode->nodeValue));
                $enumMapping  = XMLImportMapping::getByFieldName('enum_values', $xmlField->internalFieldName);

                if ( $enumMapping !== false && in_array($fieldContent, $enumMapping) )
                    $returnContent = $fieldContent;
            }
            break;
            case 'boolean':
            {
                $fieldContent = filter_var(trim($xmlField->fieldNode->nodeValue), FILTER_VALIDATE_BOOLEAN);
                $returnContent = ($fieldContent === false) ? 0 : 1;
            }
            break;
            case 'reference_article_id':
            {
                $fieldContent  = trim($xmlField->fieldNode->nodeValue);
                $returnContent = $fieldContent;
            }
            break;
            default:
            {
                XMLImportMonitor::log('The field {' . $xmlField->fieldName . '} has an unknown type : {' . $mapping['type'] . '}', 'error');
                return false;
            }
        }

        if (!isset($returnContent))
        {
            if (!empty($fieldContent) && (is_string($fieldContent) || is_numeric($fieldContent)))
            {
                $reportValue = $fieldContent;

                XMLImportMonitor::log('The field {' . $xmlField->fieldName . '} of type {' . $mapping['type'] . '} has an incorrect value : {' . $reportValue . '}', 'warning');
            }

            return false;
        }

        if (!is_array($xmlField))
            $xmlField->calculatedValue = $returnContent;

        return $returnContent;
    }
/**
 * Selects applications from database that are localized in specified cluster and are of given type
 * @param string $clusterIdentifier
 * @param string $type
 * @return array
 */
function selectApplications( $clusterIdentifier, $type )
{
    $db = MMDB::instance();
    $query = <<<'EOT'
    SELECT identifier, internal_name 
    FROM mm_application 
    WHERE id IN (SELECT application_id FROM mm_application_localized WHERE cluster_identifier = '%s')
    AND application_type_id IN (SELECT id FROM mm_application_type WHERE internal_type = '%s')     
EOT;
    $query = sprintf( $query, $clusterIdentifier, $type );
    $result = $db->arrayQuery( $query );
    return $result;
}
    /**
     * @param string $sourceId
     * @param string $locale
     * @param eZDBInterface $db
     * @return mixed
     */
    public static function getTranslationFromDb( $sourceId, $locale, $db = null )
    {
        if ( is_null( $db ) )
        {
            $db = MMDB::instance();
        }
        $sql = sprintf( 'SELECT s.source as source, v.translation as translation
            FROM ezx_translation_source s
            JOIN ezx_translation_value v on v.source_id=s.id and v.locale="%s"
            where s.id = %u', $locale, $sourceId );
        $translation = $db->arrayQuery( $sql );

        return $translation[0];
    }
/**
 * Exports and creates new static page for the provided eZ static page
 *
 * This method will do all it's work inside one database transaction.
 *
 * @param eZContentObjectTreeNode $page Static page to export
 * @param string $clusterIdentifier Cluster identifier to use for new static
 * page.
 **/
function exportPage( $page, $clusterIdentifier )
{
    $db = MMDB::instance();
    $db->begin();

    $page = new eZStaticPage( $page );
    $importer = new MMPageImporter();
    $importer->import(
        $page->getUrl(),
        $clusterIdentifier,
        $page->getHeadline(),
        $page->getCoreContent(),
        $page->getLinkedBlockTemplates()
    );

    $db->commit();
}
    public static function buildClusterFeatures()
    {
        self::flushMemoryCache();

        $sql = "select code from mm_feature_definition d
                left join mm_feature_localized l on l.feature_definition_id=d.id
                where l.cluster_identifier = '%s'";

        foreach( MMDB::instance()->arrayQuery( sprintf($sql, ClusterTool::clusterIdentifier()) ) as $row )
        {
            self::getFeatureLocalizedByCode($row['code'], true, false);
        }

        self::store();
    }
    static public function getTaxonomyTranslationsByCategory($category)
    {
        $clusterIdentifier = ClusterTool::clusterIdentifier();

        $query = "SELECT t.code AS code, tt.label AS label
        FROM mm_taxonomy_translation tt
        JOIN mm_taxonomy t ON t.id = tt.taxonomy_id
        JOIN mm_taxonomy_category tc ON tc.id = t.taxonomy_category_id
        WHERE tc.identifier = '%s' AND tt.cluster_identifier = '%s'";

        $db = MMDB::instance();
        $results = $db->arrayQuery( sprintf($query, $category, $clusterIdentifier ));

        $result = array();

        foreach ($results as $row)
        {
            $result[$row['code']] = $row['label'];
        }

        return $result;
    }
function getFeedId($cli, MMDB $db, $clusterIdentifier, $typeId)
{
    $sql = sprintf("SELECT na.feed_id
            FROM mm_feed f
            INNER JOIN mm_newsletter_application na on na.feed_id = f.id
            INNER JOIN mm_newsletter_type nt on nt.id = f.newsletter_type_id
            INNER JOIN mm_application_localized al on al.id = na.application_localized_id
            WHERE al.cluster_identifier = '%s'
            AND newsletter_type_id = %d",
            $clusterIdentifier, $typeId);

    $rows = $db->arrayQuery($sql);

    if(!$rows)
    {
        $db->beginQuery();
        $db->query(sprintf("INSERT INTO mm_feed (newsletter_type_id, cluster_identifier) VALUES (%d, '%s')", $typeId, $clusterIdentifier));
        $feedId = $db->lastSerialID("mm_feed");
        $db->commitQuery();
        $cli->output( "New feed {$feedId}" );
        return $feedId;
    }

    return $rows[0]["feed_id"];
}
    /**
     * @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;
    }
    /**
     * 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;
    }
<?php

$db = MMDB::instance();
$cli->output($db->DB);
    private static function getAllTripLocalizedIds()
    {
        $db = MMDB::instance();
        $query 	= "SELECT id
		  	   FROM mm_application_localized
		  	   WHERE application_id='".self::$tripApplication->application_id."'";
        $buffer = $db->arrayQuery( $query );

        $tripIds = array();
        foreach($buffer as $row)
        {
            $tripIds[] = $row['id'];
        }

        return $tripIds;
    }
    /**
     * @param string $footerBlockIdentifier
     * @return string
     */
    public static function getFooterHTML($footerBlockIdentifier)
    {
        $currentCluster = ClusterTool::clusterIdentifier();
        $db = MMDB::instance();
        $sql = "SELECT content
            FROM mm_footer
            WHERE cluster_identifier = '$currentCluster'
            AND block_identifier = '$footerBlockIdentifier'";
        $result = $db->arrayQuery($sql);

        return str_replace('/bundles/static-data/', '/esibuild/static/', $result[0]['content']);
    }
    public static function getSeasonCount($clusterIdentifier)
    {
        $sql = <<<SQL
SELECT IF (COUNT(id) > 0, MAX(season), -1) AS season FROM quiz_hall_of_fame
WHERE user_cluster = '%s'
SQL;
        $db = MMDB::instance();
        $result = $db->arrayQuery(sprintf($sql, $db->escapeString($clusterIdentifier)));
        $season = $result[0]['season'];

        return $season;
    }
    /**
     * @param string $categoryIdentifier
     * @param string $searchValue
     * @param string $sorts
     * @param int $limit
     * @return array
     */
    static public function fetchReferentialByIdentifierForAutoComplete( $categoryIdentifier, $searchValue, $sorts='asc', $limit=null )
    {
        $category = ReferentialCategory::fetchByIdentifier( $categoryIdentifier );

        if ( $category instanceof ReferentialCategory )
        {
            $db = MMDB::instance();
            $sql = "SELECT DISTINCT label FROM mm_referential_value WHERE cluster_identifier='".ClusterTool::clusterIdentifier()."' AND referential_category_id='".$category->attribute( 'id' )."' AND label LIKE '".$searchValue."%' ORDER BY label ".$sorts." LIMIT ".$limit;
            $query = $db->arrayQuery($sql);

            $result = array();
            foreach ( $query as $value )
            {
                $result[]=$value['label'];
            }          
            return $result;
        }
    }
/**
 * Fetches count of results in mm_seo table for given cluster identifier and (if provided) application identifier
 * @param MMDB $db
 * @param $clusterIdentifier
 * @param string $applicationIdentifier
 * @return int
 */
function fetchSeoResultsCount(MMDB $db, $clusterIdentifier, $applicationIdentifier = null)
{
    $query = <<<SQL
SELECT COUNT(*) AS count FROM mm_seo WHERE cluster_identifier = '{$clusterIdentifier}'
SQL;
    if (!empty($applicationIdentifier)) {
        $query .= " AND application_identifier = '{$applicationIdentifier}';";
    }

    $result = $db->arrayQuery($query);
    return intval($result[0]['count']);
}
    public static function exportConfig($clusterIdentifier)
    {
        $db = MMDB::instance();
        $cli = eZCLI::instance();
        $config = array();

        $cli->output($clusterIdentifier);

        // GENERAL ABOUT CLUSTER
        $localized["view"] = ezpI18n::tr("merck", "NO VIEW");
        $localized["views"] = ezpI18n::tr("merck", "VIEWS");
        $localized["rating"] = ezpI18n::tr("merck", "NO RATING");
        $localized["ratings"] = ezpI18n::tr("merck", "RATING");
        $localized["dateForm"] = str_replace('%', '', eZINI::instance("date.ini")->variable($clusterIdentifier, 'DateFormat'));
        $localized["altDescription"] = ezpI18n::tr("seo", "ACTUALITIES");
        $config["localized"] = $localized;

        ClusterTool::setCurrentCluster($clusterIdentifier);
        // About application
        foreach($db->arrayQuery(sprintf("SELECT DISTINCT(application_identifier) FROM mm_seo WHERE cluster_identifier = '%s'", $clusterIdentifier)) as $row)
        {
            $applicationIdentifier = $row["application_identifier"];
            $filters = array();
            $config[$applicationIdentifier] = array();

            $appLocalized = ApplicationLocalized::getLocalizedApplicationByIdentifier($applicationIdentifier, $clusterIdentifier);
            $appUrl = $appLocalized->attribute('url');
            /** @var ContentListBase $app */
            $app = ApplicationFactory::fetchByUri( '/'.$appUrl );

            $isContentApplication = ( $app instanceof ContentListBase);
            if ( !$isContentApplication )
            {
                continue;
            }

            // CREATE FILTER
            $solrFilter = $app->getResultHandler()->solrFilter();
            $solrFacetsFiler = $app->getResultHandler()->solrFacetsFilter();
            if( $solrFilter )
                $filters[] = $solrFilter;
            if( $solrFacetsFiler )
                $filters[] = $solrFacetsFiler;

            $filters = implode(' AND ', $filters);
            $config[$applicationIdentifier]["filters"] = $filters;

            // CREATE MAPPING PUBLISHERS
            $publishers = array();
            foreach($app->applicationLocalized()->publisherFolders as $publisherFolder)
            {
                $publishers[$publisherFolder->attribute("path")] = $publisherFolder->getTranslation()->attribute("name");
            }
            $config[$applicationIdentifier]["publishers"] = $publishers;

            // CREATE CONFIGURATION TAGLINE
            $features = $app->resultHandler->features;
            $config[$applicationIdentifier]["tagline"] = $features["line"];
        }

        return $config;
    }
    /**
     * @param $feedId
     * @return array|bool
     */
    private function getApplicationTaxonomies($feedId)
    {
        /** @var eZMySQLiDB $db */
        $db = MMDB::instance();
        $sql = sprintf(
            "SELECT taxo.code as code, taxo_cat.identifier as identifier
            FROM mm_feed feed
            INNER JOIN mm_newsletter_type nl_type ON nl_type.id = feed.newsletter_type_id
                AND nl_type.type = '%s'
            INNER JOIN mm_feed_has_taxonomy feed_taxo ON feed_taxo.feed_id = feed.id
            INNER JOIN mm_taxonomy taxo ON taxo.id = feed_taxo.taxonomy_id
            INNER JOIN mm_taxonomy_category taxo_cat ON taxo_cat.id = taxo.taxonomy_category_id
            WHERE feed.id = '%d'",
            $db->escapeString($this->_type),
            $db->escapeString($feedId)
        );

        $result = $db->arrayQuery($sql);

        $taxonomiesPerCategories = array();

        //construct taxonomy query per result
        foreach ($result as $taxonomie)
        {
            if(!isset($taxonomiesPerCategories[$taxonomie['identifier']]))
            {
                $taxonomiesPerCategories[$taxonomie['identifier']] = $taxonomie['code'];
            }
            else
            {
                $taxonomiesPerCategories[$taxonomie['identifier']] .= ' AND ' . $taxonomie['code'];
            }
        }

        return $taxonomiesPerCategories;
    }