This method applies the conditionals which are common across the get_*()
methods and the count() method.

@param array $aData Data passed from the calling method

@return void
429618
protected function getCountCommonEvent($aData = [])
    {
        if (!empty($aData['keywords'])) {
            if (empty($aData['or_like'])) {
                $aData['or_like'] = [];
            }

            $sToSlug = strtolower(str_replace(' ', '_', $aData['keywords']));

            $aData['or_like'][] = [
                'column' => $this->sTableAlias . '.type',
                'value'  => $sToSlug,
            ];
            $aData['or_like'][] = [
                'column' => 'ue.email',
                'value'  => $aData['keywords'],
            ];
        }

        //  Common joins
        $oDb = Factory::service('Database');
        $oDb->join(NAILS_DB_PREFIX . 'user u', $this->sTableAlias . '.created_by = u.id', 'LEFT');
        $oDb->join(NAILS_DB_PREFIX . 'user_email ue', 'ue.user_id = u.id AND ue.is_primary = 1', 'LEFT');

        $this->getCountCommon($aData);
    }
639348
public function getSearch($aData = [])
    {
        if (!userHasPermission('admin:auth:accounts:browse')) {
            $oHttpCodes = Factory::service('HttpCodes');
            throw new ApiException(
                'You are not authorised to search users',
                $oHttpCodes::STATUS_UNAUTHORIZED
            );
        }

        return parent::getSearch($aData);
    }
349261
private function _getModuleIdsFromExtensions($aData)
    {
        $aModuleIds = [];
        $oModule = $this->getModule();
        foreach ($aData as $aModule) {
            foreach ($aModule as $sFilePath) {
                $sModuleId = $oModule->getIdByPath($sFilePath);
                $aModuleIds[] = $sModuleId;
            }
        }

        return $aModuleIds;
    }
1277255
public function setProcessing($iRefundId, $aData = [])
    {
        $aData['status'] = self::STATUS_PROCESSING;
        return $this->update($iRefundId, $aData);
    }
58394
public static function populateUserFeedback(array &$aData)
    {
        //  Set User Feedback alerts for the views
        $oSession          = Factory::service('Session', 'nails/module-auth');
        $oUserFeedback     = Factory::service('UserFeedback');
        $aData['error']    = $oUserFeedback->get('error') ?: $oSession->getFlashData('error');
        $aData['negative'] = $oUserFeedback->get('negative') ?: $oSession->getFlashData('negative');
        $aData['success']  = $oUserFeedback->get('success') ?: $oSession->getFlashData('success');
        $aData['positive'] = $oUserFeedback->get('positive') ?: $oSession->getFlashData('positive');
        $aData['info']     = $oUserFeedback->get('info') ?: $oSession->getFlashData('info');
        $aData['warning']  = $oUserFeedback->get('message') ?: $oSession->getFlashData('warning');

        //  @deprecated
        $aData['message'] = $oUserFeedback->get('message') ?: $oSession->getFlashData('message');
        $aData['notice']  = $oUserFeedback->get('notice') ?: $oSession->getFlashData('notice');
    }
1135331
public function execute($aData = [])
    {
        $oDb        = Factory::service('Database');
        $oUserModel = Factory::model('User', 'nails/module-auth');
        $oResponse  = Factory::factory('DataExportSourceResponse', 'nails/module-admin');

        $oSource = $oDb
            ->select('u.id, u.first_name, u.last_name, ue.email')
            ->join(NAILS_DB_PREFIX . 'user_email ue', 'u.id = ue.user_id AND ue.is_primary = 1', 'LEFT')
            ->get($oUserModel->getTableName() . ' u');

        return $oResponse
            ->setLabel($this->getLabel())
            ->setFileName($this->getFileName())
            ->setFields(['id', 'first_name', 'last_name', 'email'])
            ->setSource($oSource);
    }
276445
protected function applyConditions(array $where)
    {
        foreach ($where as $field => $value) {
            if (is_array($value)) {
                list($field, $condition, $val) = $value;
                $this->model = $this->model->where($field, $condition, $val);
            } else {
                $this->model = $this->model->where($field, '=', $value);
            }
        }
    }
454179
private function setIssuedAt($issuedAt)
    {
        if (1 !== \preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/', $issuedAt)) {
            throw new AccessTokenException('invalid "expires_at" (syntax)');
        }

        // make sure it is actually a valid date
        try {
            $this->issuedAt = new DateTime($issuedAt);
        } catch (Exception $e) {
            throw new AccessTokenException(
                \sprintf('invalid "expires_at": %s', $e->getMessage())
            );
        }
    }
515475
protected function iniReadExpandLevelsAndReType (array & $iniData) {
		//$this->objectTypes[''] = [0, & $this->data];
		$oldIniScannerMode = $this->_iniScannerMode === 1;
		foreach ($iniData as $rawKey => $rawValue) {
			$current = & $this->data;
			// prepare keys to build levels and configure stdClass/array types
			$rawKeys = [];
			$lastRawKey = $rawKey;
			$lastDotPos = strrpos($rawKey, '.');
			if ($lastDotPos !== FALSE) {
				$rawKeys = explode('.', substr($rawKey, 0, $lastDotPos));
				$lastRawKey = substr($rawKey, $lastDotPos + 1);
			}
			// prepare levels structure and configure stdClass or array type change where necessary
			$levelKey = '';
			$prevLevelKey = '';
			foreach ($rawKeys as $key) {
				$prevLevelKey = $levelKey;
				$levelKey .= ($levelKey ? '.' : '') . $key;
				if (!isset($current[$key])) {
					$current[$key] = [];
					$this->objectTypes[$levelKey] = [1, & $current[$key]]; // object type switch -> object by default
					if (is_numeric($key) && isset($this->objectTypes[$prevLevelKey])) {
						$this->objectTypes[$prevLevelKey][0] = 0; // object type switch -> set array if it was object
					}
				}
				$current = & $current[$key];
			}
			// set up value into levels structure and configure type into array if necessary
			if ($oldIniScannerMode) {
				$typedValue = $this->getTypedValue($rawValue);
			} else {
				$typedValue = $rawValue;
			}
			if (isset($current[$lastRawKey])) {
				$current[$lastRawKey][] = $typedValue;
				$this->objectTypes[$levelKey ? $levelKey : $lastRawKey][0] = 0; // object type switch -> set array
			} else {
				if (!is_array($current)) {
					$current = [$current];
					$this->objectTypes[$levelKey] = [0, & $current]; // object type switch -> set array
				}
				$current[$lastRawKey] = $typedValue;
				if (is_numeric($lastRawKey)) $this->objectTypes[$levelKey][0] = 0; // object type switch -> set array
			}
		}
	}
712795
function addData( $cdata ) {
		// check we're in a valid field
		if ( isset( $this->data[$this->row][$this->current_field] ) ) {
			// add data to field
			$this->data[$this->row][$this->current_field] .= $cdata;
		}
	}
151669
protected function verifyExpiration(array $tokenData)
    {
        if (!isset($tokenData['expirationDateTime'])) {
            return;
        }
        $expirationDateTime = \DateTime::createFromFormat(\DateTime::ISO8601, $tokenData['expirationDateTime']);
        if ($this->now instanceof DependencyProxy) {
            $this->now->_activateDependency();
        }
        if ($expirationDateTime < $this->now) {
            throw new AccessDeniedException(sprintf('Token expired!%sThis token expired at "%s"', chr(10),
                $expirationDateTime->format(\DateTime::ISO8601)), 1429697439);
        }
    }
537980
public function stream_write($aData): int
    {
        if ($this->normaliseForWin) {
            $data = preg_replace('/(?<!\r)\n/', "\r\n", $aData);
        } else {
            $data = $aData;
        }

        if ($this->write) {
            $left = substr($this->string, 0, $this->position);
            $right = substr($this->string, $this->position + strlen($data));
            $this->string = $left . $data . $right;
            $this->position += strlen($data);

            return strlen($data);
        }

        return 0;
    }
785144
public function add(Array $addData)
    {
        $addFields = array();
        $addValues = array();
        foreach ($addData as $key => $value) {
            $addFields[] = $key;
            $addValues[] = '\'' . $value . '\'';
        }
        $fields = implode(',', $addFields);
        $values = implode(',', $addValues);
        $this->sql = "INSERT INTO {$this->_table} ($fields)VALUES($values)";
        return $this->execute()->rowCount();
    }
57615
protected function getCountCommonCompileWheres(array &$aData)
    {
        $oDb = Factory::service('Database');

        /**
         * Handle where's
         *
         * This is an array of the various type of where that can be passed in via $aData.
         * The first element is the key and the second is how multiple items within the
         * group should be glued together.
         *
         * Each type of where is grouped in it's own set of parenthesis, multiple groups
         * are glued together with ANDs
         */

        $aWheres = [
            'where'           => 'AND',
            'or_where'        => 'OR',
            'where_in'        => 'AND',
            'or_where_in'     => 'OR',
            'where_not_in'    => 'AND',
            'or_where_not_in' => 'OR',
        ];

        $aWhereCompiled = [];

        foreach ($aWheres as $sWhereType => $sWhereGlue) {

            if (!empty($aData[$sWhereType])) {

                $aWhereCompiled[$sWhereType] = [];

                if (is_array($aData[$sWhereType])) {

                    /**
                     * The value is an array. For each element we need to compile as appropriate
                     * and add to $aWhereCompiled.
                     */

                    foreach ($aData[$sWhereType] as $mWhere) {

                        if (is_string($mWhere)) {

                            /**
                             * The value is a straight up string, assume this is a compiled
                             * where string,
                             */

                            $aWhereCompiled[$sWhereType][] = $mWhere;

                        } else {

                            /**
                             * The value is an array, try and determine the various parts
                             * of the query. We use strings which are unlikely to be found
                             * as falsey values (such as null) are perfectly likely.
                             */

                            //  Work out column
                            $mColumn = isset($mWhere['column']) ? $mWhere['column'] : '[NAILS-COL-NOT-FOUND]';

                            if ($mColumn === '[NAILS-COL-NOT-FOUND]') {
                                $mColumn = isset($mWhere[0]) && is_string($mWhere[0]) ? $mWhere[0] : null;
                            }

                            //  Work out value
                            $mVal = isset($mWhere['value']) ? $mWhere['value'] : '[NAILS-VAL-NOT-FOUND]';

                            if ($mVal === '[NAILS-VAL-NOT-FOUND]') {
                                $mVal = isset($mWhere[1]) ? $mWhere[1] : null;
                            }

                            //  Escaped?
                            $bEscape = isset($mWhere['escape']) ? (bool) $mWhere['escape'] : '[NAILS-ESCAPE-NOT-FOUND]';

                            if ($bEscape === '[NAILS-ESCAPE-NOT-FOUND]') {
                                $bEscape = isset($mWhere[2]) ? $mWhere[2] : true;
                            }

                            //  If the $mColumn is an array then we should concat them together
                            if (is_array($mColumn)) {
                                $mColumn = 'CONCAT_WS(" ", ' . implode(',', $mColumn) . ')';
                            }

                            //  Test if there's an SQL operator
                            if (!(bool) preg_match('/(<|>|!|=|\sIS NULL|\sIS NOT NULL|\sEXISTS|\sBETWEEN|\sLIKE|\sIN\s*\(|\s)/i', trim($mColumn))) {
                                $sOperator = is_null($mVal) ? ' IS ' : '=';
                            } else {
                                $sOperator = '';
                            }

                            //  Got something?
                            if ($mColumn) {

                                switch ($sWhereType) {

                                    case 'where' :
                                    case 'or_where' :

                                        if ($bEscape) {
                                            $mVal = $oDb->escape($mVal);
                                        }

                                        $aWhereCompiled[$sWhereType][] = $mColumn . $sOperator . $mVal;
                                        break;

                                    case 'where_in' :
                                    case 'or_where_in' :

                                        if (!is_array($mVal)) {
                                            $mVal = (array) $mVal;
                                        }

                                        if (!empty($mVal)) {
                                            if ($bEscape) {
                                                foreach ($mVal as &$sValue) {
                                                    $sValue = $oDb->escape($sValue);
                                                }
                                            }

                                            $aWhereCompiled[$sWhereType][] = $mColumn . ' IN (' . implode(',', $mVal) . ')';
                                        }
                                        break;

                                    case 'where_not_in' :
                                    case 'or_where_not_in' :

                                        if (!is_array($mVal)) {
                                            $mVal = (array) $mVal;
                                        }

                                        if (!empty($mVal)) {
                                            if ($bEscape) {
                                                foreach ($mVal as &$sValue) {
                                                    $sValue = $oDb->escape($sValue);
                                                }
                                            }

                                            $aWhereCompiled[$sWhereType][] = $mColumn . ' NOT IN (' . implode(',', $mVal) . ')';
                                        }
                                        break;
                                }
                            }
                        }
                    }

                } elseif (is_string($aData[$sWhereType])) {

                    /**
                     * The value is a straight up string, assume this is a compiled
                     * where string,
                     */

                    $aWhereCompiled[$sWhereType][] = $aData[$sWhereType];
                }
            }
        }

        /**
         * Now we need to compile all the conditionals into one big super query.
         * $aWhereStr is an array of the compressed where strings... will make
         * sense shortly...
         */

        if (!empty($aWhereCompiled)) {

            $aWhereStr = [];

            foreach ($aWhereCompiled as $sWhereType => $sValue) {
                if (!empty($sValue)) {
                    $aWhereStr[] = '(' . implode(' ' . $aWheres[$sWhereType] . ' ', $sValue) . ')';
                }
            }

            //  And reduce $aWhereStr to an actual string, like the name suggests
            if (!empty($aWhereStr)) {
                $aWhereStr = implode(' AND ', $aWhereStr);
                $oDb->where($aWhereStr);
            }
        }
    }
326005
protected function getCountCommon(array $aData = [])
    {
        //  @deprecated - searching should use the search() method, but this in place
        //  as a quick fix for loads of admin controllers
        if (!empty($aData['keywords']) && !empty($this->searchableFields)) {
            if (empty($aData['or_like'])) {
                $aData['or_like'] = [];
            }

            $sAlias = $this->getTableAlias(true);

            foreach ($this->searchableFields as $mField) {

                //  If the field is an array then search across the columns concatenated together
                if (is_array($mField)) {

                    $sMappedFields = array_map(function ($sInput) use ($sAlias) {
                        if (strpos($sInput, '.') !== false) {
                            return $sInput;
                        } else {
                            return $sAlias . $sInput;
                        }
                    }, $mField);

                    $aData['or_like'][] = ['CONCAT_WS(" ", ' . implode(',', $sMappedFields) . ')', $aData['keywords']];

                } else {
                    if (strpos($mField, '.') !== false) {
                        $aData['or_like'][] = [$mField, $aData['keywords']];
                    } else {
                        $aData['or_like'][] = [$sAlias . $mField, $aData['keywords']];
                    }
                }
            }
        }

        // --------------------------------------------------------------------------

        $this->getCountCommonCompileSelect($aData);
        $this->getCountCommonCompileFilters($aData);
        $this->getCountCommonCompileWheres($aData);
        $this->getCountCommonCompileLikes($aData);
        $this->getCountCommonCompileHavings($aData);
        $this->getCountCommonCompileSort($aData);
    }
1102382
public function update($iId, $aData)
    {
        $aCategoryData = array();

        // --------------------------------------------------------------------------

        //  Some basic sanity testing
        if (empty($aData['label'])) {

            $this->setError('"label" is a required field.');
            return false;

        } else {

            $aCategoryData['label'] = trim($aData['label']);
        }

        // --------------------------------------------------------------------------

        $aCategoryData['slug'] = $this->generateSlug($aData['label'], $iId);

        if (isset($aData['description'])) {

            $aCategoryData['description'] = $aData['description'];
        }

        if (isset($aData['seo_title'])) {

            $aCategoryData['seo_title'] = strip_tags($aData['seo_title']);
        }

        if (isset($aData['seo_description'])) {

            $aCategoryData['seo_description'] = strip_tags($aData['seo_description']);
        }

        if (isset($aData['seo_keywords'])) {

            $aCategoryData['seo_keywords'] = strip_tags($aData['seo_keywords']);
        }

        return parent::update($iId, $aCategoryData);
    }
104418
public function update($iId, $aData)
    {
        $aTagData = array();

        // --------------------------------------------------------------------------

        //  Some basic sanity testing
        if (empty($aData['label'])) {

            $this->setError('"label" is a required field.');
            return false;

        } else {

            $aTagData['label'] = trim($aData['label']);
        }

        // --------------------------------------------------------------------------

        $aTagData['slug'] = $this->generateSlug($aData['label'], $iId);

        if (isset($aData['description'])) {

            $aTagData['description'] = $aData['description'];
        }

        if (isset($aData['seo_title'])) {

            $aTagData['seo_title'] = strip_tags($aData['seo_title']);
        }

        if (isset($aData['seo_description'])) {

            $aTagData['seo_description'] = strip_tags($aData['seo_description']);
        }

        if (isset($aData['seo_keywords'])) {

            $aTagData['seo_keywords'] = strip_tags($aData['seo_keywords']);
        }

        return parent::update($iId, $aTagData);
    }