After addExtendedFieldFilters, and the query is fully built, we must correct extended fields to use
the correct table aliases instead of "l.".

@param LeadListQueryBuilderGeneratedEvent $event
426839
public function correctExtendedFieldColumns(LeadListQueryBuilderGeneratedEvent $event)
    {
        $q            = $event->getQueryBuilder();
        $parts        = $q->getQueryParts();
        $changedParts = [];
        $aliases      = [];
        if (isset($parts['join']['l']) && !empty($this->aliases)) {
            // Confirm the aliases are for the current query by present joins.
            foreach ($parts['join']['l'] as $key => $join) {
                if (
                    is_array($join)
                    && isset($join['joinType'])
                    && 'left' === $join['joinType']
                    && isset($this->aliases[$join['joinAlias']])
                ) {
                    $aliases[$join['joinAlias']] = $this->aliases[$join['joinAlias']];
                }
            }
            if (count($aliases)) {
                foreach ($aliases as $joinAlias => $fieldAlias) {
                    foreach (['where', 'orWhere', 'andWhere', 'having', 'orHaving', 'andHaving'] as $type) {
                        if (isset($parts[$type])) {
                            $changedParts[$type] = $this->partCorrect($parts[$type], $fieldAlias, $this->seen[$fieldAlias]);
                        }
                    }
                }
            }
            foreach ($changedParts as $type => $t) {
                $q->setQueryPart($type, $parts[$type]);
            }
        }
    }
89146
public function beforeQuery(Event $event, DbAdapterInterface $connection)
    {
        $this->profiler->startProfile(
            $connection->getSQLStatement(), $connection->getSQLVariables()
        );
    }
854908
public function beforeFilter(\Cake\Event\Event $event)
    {
        parent::beforeFilter($event);

        // get the type-string
        $type = $this->PostTypes->postTypeFinder($this->request);
        $this->_type = $type;

        // check if the string exists. Will throw an exception
        $this->PostTypes->check($type, ['exception' => true]);

        // intialize the settings
        $this->Settings = $this->PostTypes->get($type);

        // lets initialize the model too
        $this->Model = $this->loadModel($this->Settings['model']);
    }
410479
public function add(EntityAdded $event)
    {
        $entity = $event->getEntity();
        $table = $this->getParentTableName();
        $pmk = $this->getParentPrimaryKey();
        $value = $event->getCollection()->parentEntity()->getId();
        Sql::createSql($this->getAdapter())
            ->update($table)
            ->set([$this->getForeignKey() => $value])
            ->where(["{$pmk} = :id" => [':id' => $entity->getId()]])
            ->execute();
    }
476455
public function filterConditions(IndexEngineIndexEvent $event)
    {
        $conditions = $event->getConditions();
        $event->setConditions([]);

        $event->addCondition("criteria", $conditions);
    }
658899
private void createExtendedElement(StringBuilder sb, RepositoryLogRecord record){
		sb.append(lineSeparator).append(INDENT[0]).append("<extendedDataElements name=\"CommonBaseEventLogRecord:level\" type=\"noValue\">");
		sb.append(lineSeparator).append(INDENT[1]).append("<children name=\"CommonBaseEventLogRecord:name\" type=\"string\">");
		sb.append(lineSeparator).append(INDENT[2]).append("<values>").append(record.getLevel().getName()).append("</values>");
		sb.append(lineSeparator).append(INDENT[1]).append("</children>");
		sb.append(lineSeparator).append(INDENT[1]).append("<children name=\"CommonBaseEventLogRecord:value\" type=\"int\">");
		sb.append(lineSeparator).append(INDENT[2]).append("<values>").append(record.getLevel().intValue()).append("</values>");
		sb.append(lineSeparator).append(INDENT[1]).append("</children>");
		sb.append(lineSeparator).append(INDENT[0]).append("</extendedDataElements>");    	
	}
168002
private function getExtendedField($alias)
    {
        $qf = $this->_em->getConnection()->createQueryBuilder();
        $qf->select('lf.id, lf.object, lf.type, lf.alias, lf.field_group as "group", lf.object, lf.label')
            ->from(MAUTIC_TABLE_PREFIX.'lead_fields', 'lf')
            ->where(
                $qf->expr()->andX(
                    $qf->expr()->eq('lf.alias', ':alias'),
                    $qf->expr()->orX(
                        $qf->expr()->eq('lf.object', $qf->expr()->literal('extendedField')),
                        $qf->expr()->eq('lf.object', $qf->expr()->literal('extendedFieldSecure'))
                    )
                )
            )
            ->setParameter('alias', $alias);

        return $qf->execute()->fetch();
    }
178508
public function afterCreate(PersistenceEvent $event) {
    if ($event->getAction() == PersistenceAction::CREATE) {
      $oldOid = $event->getOldOid();
      $oldOidStr = $oldOid != null ? $oldOid->__toString() : null;
      if ($oldOidStr != null && isset($this->createdTranslations[$oldOidStr])) {
        foreach ($this->createdTranslations[$oldOidStr] as $translation) {
          $translation->setValue('objectid', $event->getObject()->getOID()->__toString());
        }
      }
    }
  }
910593
public function afterSelect(Select $event)
    {
        if ($this->lazyLoad) {
            return;
        }
        $data = $event->data;
        $multiple = $data instanceof RecordList;
        if ($multiple) {
            $data = $event->data->getArrayCopy();
        } else {
            $data = [$data];
        }
        if (empty($data)) {
            return;
        }
        $related = Entity\Manager::getInstance()
            ->get($this->getRelatedEntity());
        $relatedTable = $related->getEntity()->getTableName();
        $class = $related->getEntity()->getClassName();
        $dataCopy = $data;
        foreach ($dataCopy as $key => $row) {

            $pmk =  $this->getEntity()->getPrimaryKey();
            if (isset($row[$pmk]) && is_array($row[$pmk])) {
                $data[$key][$pmk] = reset($row[$pmk]);
            }
            $options = [];
            if (is_array($row)) {
                foreach ($row as $column => $value) {
                    if (preg_match('/^' . $relatedTable . '_(.*)/', $column)) {
                        unset($data[$key][$column]);
                        $name = str_replace($relatedTable . '_', '', $column);
                        $options[$name] = $value;
                    }
                }
            }
            $data[$key][$this->getPropertyName()] = new $class($options);
        }

        if ($multiple) {
            $event->data = new RecordList(['data' => $data]);
        } else {
            $event->data = reset($data);
        }
    }
1264103
public function onPostSearchQueryBuilder(GenericEvent $event)
    {
        $queryBuilder = $event->getArgument('query_builder');

        if ($event->hasArgument('request')) {
            $this->applyRequestFilters($queryBuilder, $event->getArgument('request')->get('filters', []));
        }
    }
289911
static function createExtendedAttributeFilterSQLStrings( &$extendedAttributeFilter )
    {
        $filter = array( 'tables'   => '',
                         'joins'    => '',
                         'columns'  => '',
                         'group_by' => '' );

        if ( $extendedAttributeFilter and count( $extendedAttributeFilter ) > 1 )
        {
            $extendedAttributeFilterID      = $extendedAttributeFilter['id'];
            $extendedAttributeFilterParams  = $extendedAttributeFilter['params'];
            $filterINI                      = eZINI::instance( 'extendedattributefilter.ini' );

            if ( !$filterINI->hasGroup( $extendedAttributeFilterID ) )
            {
                eZDebug::writeError( "Unable to find configuration for the extended attribute filter '$extendedAttributeFilterID', the filter will be ignored", __METHOD__ );
                return $filter;
            }

            $filterClassName    = $filterINI->variable( $extendedAttributeFilterID, 'ClassName' );
            $filterMethodName   = $filterINI->variable( $extendedAttributeFilterID, 'MethodName' );

            if ( $filterINI->hasVariable( $extendedAttributeFilterID, 'FileName' ) )
            {
                $filterFile = $filterINI->variable( $extendedAttributeFilterID, 'FileName' );

                if ( $filterINI->hasVariable( $extendedAttributeFilterID, 'ExtensionName' ) )
                {
                    $extensionName = $filterINI->variable( $extendedAttributeFilterID, 'ExtensionName' );
                    include_once( eZExtension::baseDirectory() . "/$extensionName/$filterFile" );
                }
                else
                {
                    include_once( $filterFile );
                }
            }

            if ( !class_exists( $filterClassName, true ) )
            {
                eZDebug::writeError( "Unable to find the PHP class '$filterClassName' associated with the extended attribute filter '$extendedAttributeFilterID', the filter will be ignored", __METHOD__ );
                return $filter;
            }

            $classObject        = new $filterClassName();
            $parameterArray     = array( $extendedAttributeFilterParams );

            $sqlResult          = call_user_func_array( array( $classObject, $filterMethodName ), $parameterArray );

            $filter['tables']   = $sqlResult['tables'];
            $filter['joins']    = $sqlResult['joins'];
            $filter['columns']  = isset( $sqlResult['columns'] ) ? $sqlResult['columns'] : '';

            if( isset( $sqlResult['group_by'] ) )
                $filter['group_by'] =  $sqlResult['group_by'];
        }

        return $filter;
    }
1233620
private void addFieldsToBuilder(String[] fieldsToSelect, Class clazz, MetamodelImpl metaModel,
            SearchRequestBuilder builder)
    {
        if (fieldsToSelect != null && fieldsToSelect.length > 1 && !(fieldsToSelect[1] == null))
        {
            logger.debug("Fields added in query are: ");
            for (int i = 1; i < fieldsToSelect.length; i++)
            {
                logger.debug(i + " : " + fieldsToSelect[i]);
                builder = builder.addField(((AbstractAttribute) metaModel.entity(clazz).getAttribute(fieldsToSelect[i]))
                        .getJPAColumnName());
            }
        }
    }
748204
protected function applyFormFilters(QueryBuilder $queryBuilder, array $filters = [])
    {
        foreach ($filters as $field => $listFilter) {
            if (null === $listFilter) {
                continue;
            }

            $this->filterQueryBuilder($queryBuilder, $field, $listFilter);
        }
    }
1106064
public function beforeFilter(Event $event)
    {
        $this->TimebasedCurrencyPayment = TableRegistry::getTableLocator()->get('TimebasedCurrencyPayments');
        $this->TimebasedCurrencyOrderDetail = TableRegistry::getTableLocator()->get('TimebasedCurrencyOrderDetails');
        parent::beforeFilter($event);
    }
854171
public function filterQuery(QueryBuilder &$query, &$selects = null)
    {
        $model = $this->config->getDataModel();

        //if this field has a min/max range, set it
        if ($this->getOption('min_max')) {
            if ($minValue = $this->getOption('min_value')) {
                $query->where($model->getTable().'.'.$this->getOption('field_name'), '>=', $minValue);
            }

            if ($maxValue = $this->getOption('max_value')) {
                $query->where($model->getTable().'.'.$this->getOption('field_name'), '<=', $maxValue);
            }
        }
    }
699592
private function getExtendedFieldValuesMultiple(
        $extendedFieldList = [],
        $leadIds = []
    ) {
        /** @var EntityManager $em */
        $em = $this->getEntityManager();

        $leadIdsStr = "'".implode("','", $leadIds)."'";

        $selects = [];
        foreach (['string', 'float', 'boolean', 'date', 'datetime', 'time', 'text'] as $data_type) {
            foreach (['', '_secure'] as $secure) {
                $xrefTable = MAUTIC_TABLE_PREFIX."lead_fields_leads_{$data_type}{$secure}_xref";

                $selects[] = <<<EOSQL
SELECT lead_id, lead_field_id, value, '{$data_type}' AS data_type 
FROM  {$xrefTable}
WHERE lead_id IN ({$leadIdsStr})
EOSQL;
            }
        }
        $xrefQuery = implode("\nUNION\n", $selects);

        $leadsTable      = $em->getRepository('MauticLeadBundle:Lead')->getTableName();
        $lt              = $em->getRepository('MauticLeadBundle:Lead')->getTableAlias();
        $leadFieldsTable = $em->getRepository('MauticLeadBundle:LeadField')->getTableName();
        $lft             = $em->getRepository('MauticLeadBundle:LeadField')->getTableAlias();

        $where = "{$lft}.object IN ('extendedField','extendedFieldSecure') ";
        if (!empty($extendedFieldList)) {
            $ids             = array_map(
                function ($e) {
                    return $e['id'];
                },
                $extendedFieldList
            );
            $leadFiieldIdStr = "'".implode("','", $ids)."'";
            $where           = "{$lft}.id IN ({$leadFiieldIdStr}) ";
        }

        $sql = <<<EOSQL
SELECT x.lead_id, x.alias, v.value, v.data_type
FROM
(
    SELECT {$lt}.id AS lead_id,
    {$lft}.id as lead_field_id,
    {$lft}.alias
    FROM {$leadsTable} {$lt} CROSS JOIN {$leadFieldsTable} {$lft}
    WHERE {$where}
    AND {$lt}.id  IN ({$leadIdsStr})
) x
LEFT JOIN
(
    {$xrefQuery}
) v USING (lead_id, lead_field_id)
EOSQL;

        $query = $em->getConnection()->prepare($sql);
        $query->execute();
        $results = $query->fetchAll();

        // Group results by leadId.
        $leads = [];
        foreach ($results as $row => $result) {
            $leads[$result['lead_id']][$result['alias']] = $result['value'];
            unset($results[$row]);
        }

        return $leads;
    }
1048588
public function filterQuery(QueryBuilder &$query, &$selects = null)
    {
        //run the parent method
        parent::filterQuery($query, $selects);

        //get the values
        $value   = $this->getOption('value');
        $table   = $this->getOption('table');
        $column  = $this->getOption('column');
        $column2 = $this->getOption('column2');

        //if there is no value, return
        if (!$value) {
            return;
        }

        $model = $this->config->getDataModel();

        //if the table hasn't been joined yet, join it
        if (!$this->validator->isJoined($query, $table)) {
            $query->join($table, $model->getTable().'.'.$model->getKeyName(), '=', $column);
        }

        //add where clause
        $query->whereIn($column2, $value);

        //add having clauses
        $query->havingRaw('COUNT(DISTINCT '.$query->getConnection()->getTablePrefix().$column2.') = '.count($value));

        //add select field
        if ($selects && !in_array($column2, $selects)) {
            $selects[] = $column2;
        }
    }