_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 33 8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q4300 | Email.send | train | public function send()
{
$this->logger->debug(
'Attempting to send an email',
$this->to()
);
$mail = $this->phpMailer;
try {
$this->setSmtpOptions($mail);
$mail->CharSet = 'UTF-8';
// Setting reply-to field, if required.
$replyTo = $this->replyTo();
if ($replyTo) {
$replyArr = $this->emailToArray($replyTo);
$mail->addReplyTo($replyArr['email'], $replyArr['name']);
}
// Setting from (sender) field.
$from = $this->from();
$fromArr = $this->emailToArray($from);
$mail->setFrom($fromArr['email'], $fromArr['name']);
// Setting to (recipients) field(s).
$to = $this->to();
foreach ($to as $recipient) {
$toArr = $this->emailToArray($recipient);
$mail->addAddress($toArr['email'], $toArr['name']);
}
// Setting cc (carbon-copy) field(s).
$cc = $this->cc();
foreach ($cc as $ccRecipient) {
$ccArr = $this->emailToArray($ccRecipient);
$mail->addCC($ccArr['email'], $ccArr['name']);
}
| php | {
"resource": ""
} |
q4301 | Email.setSmtpOptions | train | protected function setSmtpOptions(PHPMailer $mail)
{
$config = $this->config();
if (!$config['smtp']) {
return;
}
$this->logger->debug(
sprintf('Using SMTP "%s" server to send email', $config['smtp_hostname'])
| php | {
"resource": ""
} |
q4302 | Email.queue | train | public function queue($ts = null)
{
$recipients = $this->to();
$author = $this->from();
$subject = $this->subject();
$msgHtml = $this->msgHtml();
$msgTxt = $this->msgTxt();
$campaign = $this->campaign();
$queueId = $this->queueId();
foreach ($recipients as $to) {
| php | {
"resource": ""
} |
q4303 | Email.viewController | train | public function viewController()
{
$templateIdent = $this->templateIdent();
if (!$templateIdent) {
return [];
}
$templateFactory = clone($this->templateFactory());
$templateFactory->setDefaultClass(GenericEmailTemplate::class);
| php | {
"resource": ""
} |
q4304 | Email.generateMsgHtml | train | protected function generateMsgHtml()
{
$templateIdent = $this->templateIdent();
if (!$templateIdent) {
$message = '';
} else {
| php | {
"resource": ""
} |
q4305 | Email.stripHtml | train | protected function stripHtml($html)
{
$str = html_entity_decode($html);
// Strip HTML (Replace br with newline, remove "invisible" tags and strip other tags)
$str = preg_replace('#<br[^>]*?>#siu', "\n", $str);
$str = preg_replace(
[
'#<applet[^>]*?.*?</applet>#siu',
'#<embed[^>]*?.*?</embed>#siu',
'#<head[^>]*?>.*?</head>#siu',
'#<noframes[^>]*?.*?</noframes>#siu',
'#<noscript[^>]*?.*?</noscript>#siu',
'#<noembed[^>]*?.*?</noembed>#siu',
'#<object[^>]*?.*?</object>#siu',
'#<script[^>]*?.*?</script>#siu',
'#<style[^>]*?>.*?</style>#siu'
],
'',
$str
);
$str = strip_tags($str);
| php | {
"resource": ""
} |
q4306 | Email.logSend | train | protected function logSend($result, $mailer)
{
if ($this->log() === false) {
return;
}
if (!$result) {
$this->logger->error('Email could not be sent.');
} else {
$this->logger->debug(
sprintf('Email "%s" sent successfully.', $this->subject()),
$this->to()
);
}
$recipients = array_merge(
$this->to(),
$this->cc(),
$this->bcc()
);
foreach ($recipients as $to) {
| php | {
"resource": ""
} |
q4307 | Mo.get | train | public function get( $original )
{
$original = (string) $original;
if( isset( $this->messages[$original] ) ) {
| php | {
"resource": ""
} |
q4308 | Mo.extract | train | protected function extract()
{
$magic = $this->readInt( 'V' );
if( ( $magic === self::MAGIC1 ) || ( $magic === self::MAGIC3 ) ) { //to make sure it works for 64-bit platforms
$byteOrder = 'V'; //low endian
} elseif( $magic === ( self::MAGIC2 & 0xFFFFFFFF ) ) {
$byteOrder = 'N'; //big endian
} else {
throw new \Aimeos\MW\Translation\Exception( 'Invalid MO file' );
}
$this->readInt( $byteOrder );
$total = $this->readInt( $byteOrder ); //total string count
$originals = $this->readInt( $byteOrder ); //offset of original table
| php | {
"resource": ""
} |
q4309 | Mo.extractTable | train | protected function extractTable( $originalTable, $translationTable, $total )
{
$messages = [];
for( $i = 0; $i < $total; ++$i )
{
$plural = null;
$next = $i * 2;
$this->seekto( $originalTable[$next + 2] );
$original = $this->read( $originalTable[$next + 1] );
$this->seekto( $translationTable[$next + 2] );
$translated = $this->read( $translationTable[$next + 1] );
if( $original === '' || $translated === '' ) { // Headers
continue;
}
if( strpos( $original, "\x04" ) !== false ) {
list( $context, $original ) = explode( "\x04", $original, 2 );
}
if( strpos( $original, "\000" ) !== false ) {
| php | {
"resource": ""
} |
q4310 | Mo.readInt | train | protected function readInt( $byteOrder )
{
if( ( $content = $this->read( 4 )) === false ) {
return false;
}
$content = unpack( | php | {
"resource": ""
} |
q4311 | PagesWidgetsCell.pages | train | public function pages()
{
//Returns on pages index
if ($this->request->isUrl(['_name' => 'pagesCategories'])) {
return;
}
$pages = $this->Pages->find('active')
->select(['title', 'slug'])
| php | {
"resource": ""
} |
q4312 | Captcha.generate | train | public function generate()
{
try {
if (!$this->isEnabled()) {
throw new CaptchaDriverException(
'Captcha driver has not been configured.'
);
}
$oResponse = $this->oDriver->generate();
if (!($oResponse instanceof CaptchaForm)) {
throw new CaptchaDriverException(
'Driver must return an instance of \Nails\Captcha\Factory\CaptchaForm.'
);
| php | {
"resource": ""
} |
q4313 | AbstractConnector.getPdo | train | public function getPdo()
{
if ($this->pdo === null) { | php | {
"resource": ""
} |
q4314 | AbstractConnector.disconnect | train | public function disconnect()
{
if ($this->pdo !== null) {
| php | {
"resource": ""
} |
q4315 | MetaController.performAjaxValidation | train | protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) | php | {
"resource": ""
} |
q4316 | Group.setAsDefault | train | public function setAsDefault($mGroupIdOrSlug)
{
$oGroup = $this->getByIdOrSlug($mGroupIdOrSlug);
if (!$oGroup) {
$this->setError('Invalid Group');
}
// --------------------------------------------------------------------------
$oDb = Factory::service('Database');
$oDb->trans_begin();
// Unset old default
$oDb->set('is_default', false);
$oDb->set('modified', 'NOW()', false);
if (isLoggedIn()) {
$oDb->set('modified_by', activeUser('id'));
}
$oDb->where('is_default', true);
$oDb->update($this->getTableName());
// Set new default
$oDb->set('is_default', true);
| php | {
"resource": ""
} |
q4317 | Group.getDefaultGroup | train | public function getDefaultGroup()
{
$aGroups = $this->getAll([
'where' => [
['is_default', true],
],
]);
if (empty($aGroups)) {
throw new NailsException('A | php | {
"resource": ""
} |
q4318 | Group.hasPermission | train | public function hasPermission($sSearch, $mGroup)
{
// Fetch the correct ACL
if (is_numeric($mGroup)) {
$oGroup = $this->getById($mGroup);
if (isset($oGroup->acl)) {
$aAcl = $oGroup->acl;
unset($oGroup);
} else {
return false;
}
} elseif (isset($mGroup->acl)) {
$aAcl = $mGroup->acl;
} else {
return false;
}
if (!$aAcl) {
return false;
}
// --------------------------------------------------------------------------
// Super users or CLI users can do anything their heart's desire
$oInput = Factory::service('Input');
if (in_array('admin:superuser', $aAcl) || $oInput::isCli()) {
return true;
}
// --------------------------------------------------------------------------
/**
* Test the ACL
* We're going to use regular expressions here so we can allow for some
* flexibility in the search, i.e admin:* would return true if the user has
* access to any of admin.
*/
| php | {
"resource": ""
} |
q4319 | Utf8.defineCharsetConstants | train | protected static function defineCharsetConstants()
{
/**
* See vendor/codeigniter/framework/system/core/CodeIgniter.php for
* details of what/why this is happening.
*/
$sCharset = strtoupper(config_item('charset'));
ini_set('default_charset', $sCharset);
if (extension_loaded('mbstring')) {
define('MB_ENABLED', true);
@ini_set('mbstring.internal_encoding', $sCharset);
mb_substitute_character('none');
} else {
define('MB_ENABLED', false);
| php | {
"resource": ""
} |
q4320 | ArraySet.sortData | train | protected function sortData() {
$columns = $this->getOrder();
$order = [];
foreach ($columns as $column) {
if ($column[0] === '-') {
$column = substr($column, 1);
$order[$column] = -1;
} else {
$order[$column] = 1;
}
}
$cmp = function ($a, $b) use ($order) {
foreach ($order | php | {
"resource": ""
} |
q4321 | ArraySet.getData | train | public function getData() {
if ($this->toSort && !empty($this->getOrder())) {
$this->sortData();
}
if ($this->getLimit()) {
| php | {
"resource": ""
} |
q4322 | ArraySet.setData | train | public function setData($data) {
if ($data instanceof \Traversable) {
$this->data = iterator_to_array($data);
} else {
$this->data = $data;
}
| php | {
"resource": ""
} |
q4323 | Security.decryptMail | train | public static function decryptMail($mail, $key = null, $hmacSalt = null)
{
| php | {
"resource": ""
} |
q4324 | Security.encryptMail | train | public static function encryptMail($mail, $key = null, $hmacSalt = null)
{
| php | {
"resource": ""
} |
q4325 | Base.loadStyles | train | protected function loadStyles($sView)
{
// Test if a view has been provided by the app
if (!is_file($sView)) {
| php | {
"resource": ""
} |
q4326 | Json.getJson | train | public function getJson($jsonFile, $jsonSchema = null)
{
if (isset($jsonSchema) && array_key_exists($jsonSchema, $this->validation)) {
$validation = $this->validation[$jsonSchema];
} elseif ($jsonSchema === null) {
$validation = $jsonSchema;
} else {
throw new Exception('Invalid jsonSchema validation key');
}
try {
return $this->decodeFile($jsonFile, $validation);
} catch (\RuntimeException $e) {
// Runtime errors such as file not found
$this->errors[] = $e->getMessage();
} | php | {
"resource": ""
} |
q4327 | SystemsController.acceptCookies | train | public function acceptCookies()
{
$this->response = $this->response->withCookie((new Cookie('cookies-policy', true))->withNeverExpire());
| php | {
"resource": ""
} |
q4328 | SystemsController.contactUs | train | public function contactUs()
{
//Checks if the "contact us" form is enabled
if (!getConfig('default.contact_us')) {
$this->Flash->error(I18N_DISABLED);
return $this->redirect(['_name' => 'homepage']);
}
$contact = new ContactUsForm;
if ($this->request->is('post')) {
//Checks for reCAPTCHA, if requested
if (!getConfig('security.recaptcha') || $this->Recaptcha->verify()) {
//Sends the email
if ($contact->execute($this->request->getData())) {
$this->Flash->success(I18N_OPERATION_OK);
| php | {
"resource": ""
} |
q4329 | SystemsController.ipNotAllowed | train | public function ipNotAllowed()
{
//If the user's IP address is not banned
if (!$this->request->isBanned()) { | php | {
"resource": ""
} |
q4330 | SystemsController.sitemap | train | public function sitemap()
{
//Checks if the sitemap exist and is not expired
if (is_readable(SITEMAP)) {
$time = Time::createFromTimestamp(filemtime(SITEMAP));
if (!$time->modify(getConfigOrFail('main.sitemap_expiration'))->isPast()) {
| php | {
"resource": ""
} |
q4331 | PhotosAlbumsController.add | train | public function add()
{
$album = $this->PhotosAlbums->newEntity();
if ($this->request->is('post')) {
$album = $this->PhotosAlbums->patchEntity($album, $this->request->getData());
if ($this->PhotosAlbums->save($album)) {
$this->Flash->success(I18N_OPERATION_OK);
| php | {
"resource": ""
} |
q4332 | PhotosAlbumsController.edit | train | public function edit($id = null)
{
$album = $this->PhotosAlbums->get($id);
if ($this->request->is(['patch', 'post', 'put'])) {
$album = $this->PhotosAlbums->patchEntity($album, $this->request->getData());
if ($this->PhotosAlbums->save($album)) {
$this->Flash->success(I18N_OPERATION_OK);
| php | {
"resource": ""
} |
q4333 | PhotosAlbumsController.delete | train | public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$album = $this->PhotosAlbums->get($id);
//Before deleting, it checks if the album has some photos
if (!$album->photo_count) {
$this->PhotosAlbums->deleteOrFail($album);
| php | {
"resource": ""
} |
q4334 | DoughExtension.getAmount | train | public function getAmount(MoneyInterface $money = null, $currency = null)
{
if (null === $money) {
return 0.0;
}
$reduced = | php | {
"resource": ""
} |
q4335 | Toolbox.truncateHtmlText | train | public function truncateHtmlText($text, $characters = 300)
{
// Clean up html tags and special characters
$text = preg_replace('/<[^>]*>/', ' ', $text);
$text = str_replace("\r", '', $text); // replace with empty space
$text = str_replace("\n", ' ', $text); // replace with space
$text = str_replace("\t", ' ', $text); // replace with space
$text = preg_replace('/\s+/', ' ', $text); // remove multiple consecutive spaces
$text = preg_replace('/^[\s]/', '', $text); // Remove leading space from excerpt
$text = preg_replace('/[\s]$/', '', $text); // Remove trailing space from excerpt
// If we are already within the limit, just return the text
if (mb_strlen($text) <= $characters) {
| php | {
"resource": ""
} |
q4336 | Toolbox.getDirectoryFiles | train | public function getDirectoryFiles($dirPath, $ignore = null)
{
$files = [];
$pattern = '/^\..+'; // Ignore all dot files by default
$splitCamelCase = '/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/';
$ignoreDirectories = false;
if (is_string($ignore) && !empty($ignore)) {
// If 'dir' or 'directory' strings are set, then set flag to ignore directories
if ($ignore === 'dir' || $ignore === 'directory') {
$ignoreDirectories = true;
} else {
// Add it to the regex
$pattern .= '|' . $ignore;
}
} elseif (is_array($ignore)) {
// If 'dir' or 'directory' strings are set, then set flag to ignore directories
if (in_array('dir', $ignore) || in_array('directory', $ignore)) {
$ignoreDirectories = true;
$ignore = array_diff($ignore, ['dir', 'directory']);
}
// Add it to the regex
$multiIgnores = implode('|', $ignore);
$pattern .= empty($multiIgnores) ? '' : '|' . $multiIgnores;
}
$pattern .= '/'; // Close regex
| php | {
"resource": ""
} |
q4337 | AbstractAttackNumberByDistanceTable.getOrderedByDistanceAsc | train | protected function getOrderedByDistanceAsc(): array
{
$values = $this->getIndexedValues();
uksort($values, function ($oneDistanceInMeters, $anotherDistanceInMeters) {
/** @noinspection ExceptionsAnnotatingAndHandlingInspection */
$oneDistanceInMeters = ToFloat::toPositiveFloat($oneDistanceInMeters);
/** @noinspection ExceptionsAnnotatingAndHandlingInspection */
| php | {
"resource": ""
} |
q4338 | MySqlDb.buildSelect | train | protected function buildSelect($table, array $where, array $options = []) {
$options += ['limit' => 0];
$sql = '';
// Build the select clause.
if (!empty($options['columns'])) {
$columns = array();
foreach ($options['columns'] as $value) {
$columns[] = $this->escape($value);
}
$sql .= 'select '.implode(', ', $columns);
} else {
$sql .= "select *";
}
// Build the from clause.
if ($table instanceof Literal) {
$table = $table->getValue($this);
} else {
$table = $this->prefixTable($table);
}
$sql .= "\nfrom $table";
// Build the where clause.
$whereString = $this->buildWhere($where, Db::OP_AND);
if ($whereString) {
$sql .= "\nwhere ".$whereString;
}
// Build the order.
if (!empty($options['order'])) {
$orders = [];
foreach ($options['order'] as $column) {
if ($column[0] === '-') {
| php | {
"resource": ""
} |
q4339 | MySqlDb.getDbName | train | private function getDbName() {
if (!isset($this->dbname)) {
$this->dbname = $this->getPDO()->query('select | php | {
"resource": ""
} |
q4340 | MySqlDb.fetchIndexesDb | train | protected function fetchIndexesDb($table = '') {
$stm = $this->get(
new Identifier('information_schema', 'STATISTICS'),
[
'TABLE_SCHEMA' => $this->getDbName(),
'TABLE_NAME' => $this->prefixTable($table, false)
],
[
'columns' => [
'INDEX_NAME',
'COLUMN_NAME',
'NON_UNIQUE'
],
'order' => ['INDEX_NAME', 'SEQ_IN_INDEX']
]
);
$indexRows = $stm->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP);
$indexes = [];
foreach ($indexRows as $indexName => $columns) {
| php | {
"resource": ""
} |
q4341 | MySqlDb.buildInsert | train | protected function buildInsert($table, array $row, $options = []) {
if (self::val(Db::OPTION_UPSERT, $options)) {
return $this->buildUpsert($table, $row, $options);
} elseif (self::val(Db::OPTION_IGNORE, $options)) {
$sql = 'insert ignore ';
} elseif (self::val(Db::OPTION_REPLACE, $options)) {
$sql = 'replace ';
} else {
$sql = 'insert ';
}
| php | {
"resource": ""
} |
q4342 | MySqlDb.buildUpsert | train | protected function buildUpsert($table, array $row, $options = []) {
// Build the initial insert statement first.
unset($options[Db::OPTION_UPSERT]);
$sql = $this->buildInsert($table, $row, $options);
// Add the duplicate key stuff.
$updates = [];
foreach | php | {
"resource": ""
} |
q4343 | MySqlDb.indexDefString | train | protected function indexDefString($table, array $def) {
$indexName = $this->escape($this->buildIndexName($table, $def));
if (empty($def['columns'])) {
throw new \DomainException("The `$table`.$indexName index has no columns.", 500);
}
switch (self::val('type', $def, Db::INDEX_IX)) { | php | {
"resource": ""
} |
q4344 | MySqlDb.forceType | train | protected function forceType($value, $type) {
$type = strtolower($type);
if ($type === 'null') {
return null;
} elseif ($type === 'boolean') {
return filter_var($value, FILTER_VALIDATE_BOOLEAN);
} elseif (in_array($type, ['int', 'integer', 'tinyint', 'smallint',
'mediumint', 'bigint', 'unsigned big int', 'int2', 'int8', 'boolean'])) {
return | php | {
"resource": ""
} |
q4345 | MySqlDb.argValue | train | private function argValue($value) {
if (is_bool($value)) {
return (int)$value;
} elseif ($value | php | {
"resource": ""
} |
q4346 | InternalDetector.detectChangedPermalink | train | public function detectChangedPermalink()
{
// if permalink not changed, return, do nothing more
if ($this->permalinkBefore === $this->permalinkAfter && !$this->trashed) {
return false;
}
if ($this->trashed) {
App::$externalDetector->lookForBrokenLinks('internal', str_replace('__trashed', '', $this->permalinkBefore));
return true;
}
// Replace occurances of the old permalink with the new permalink
global $wpdb;
$wpdb->query(
$wpdb->prepare(
"UPDATE $wpdb->posts
SET post_content = REPLACE(post_content, %s, %s)
WHERE post_content LIKE %s",
$this->permalinkBefore,
$this->permalinkAfter,
| php | {
"resource": ""
} |
q4347 | Index.absolute | train | public function absolute($root = null)
{
//argument 1 must be a string or null
Argument::i()->test(1, 'string', 'null');
//if path is a directory or file
if (is_dir($this->data) || is_file($this->data)) {
return $this;
}
//if root is null
if (is_null($root)) {
//assume the root is doc root
$root = $_SERVER['DOCUMENT_ROOT'];
}
//get the absolute path
$absolute = $this->format($this->format($root).$this->data);
//if absolute is a directory or file
if (is_dir($absolute) || is_file($absolute)) {
| php | {
"resource": ""
} |
q4348 | Index.append | train | public function append($path)
{
//argument 1 must be a string
$argument = Argument::i()->test(1, 'string');
//each argument will be a path
$paths = func_get_args();
//for each path
foreach ($paths as $i => $path) {
| php | {
"resource": ""
} |
q4349 | Index.prepend | train | public function prepend($path)
{
//argument 1 must be a string
$error = Argument::i()->test(1, 'string');
//each argument will be a path
$paths = func_get_args();
//for each path
foreach ($paths as $i => $path) {
| php | {
"resource": ""
} |
q4350 | Index.pop | train | public function pop()
{
//get the path array
$pathArray = $this->getArray();
//remove the last
$path = array_pop($pathArray);
| php | {
"resource": ""
} |
q4351 | Index.replace | train | public function replace($path)
{
//argument 1 must be a string
Argument::i()->test(1, 'string');
//get the path array
$pathArray = $this->getArray();
//pop out the last
array_pop($pathArray);
//push in the | php | {
"resource": ""
} |
q4352 | Index.format | train | protected function format($path)
{
//replace back slash with forward
$path = str_replace('\\', '/', $path);
//replace double forward slash with 1 forward slash
$path = str_replace('//', '/', $path);
//if there is a last forward slash
if (substr($path, -1, 1) == '/') {
//remove it
$path = substr($path, 0, -1);
}
//if the path does not start with a foward slash
//and | php | {
"resource": ""
} |
q4353 | API.set_campus | train | public function set_campus($campus) {
$campus = !is_array($campus) ? array($campus) : $campus;
$this->_campus = array();
foreach ($campus as $c) {
$c = strtolower($c);
if (!in_array($c, array('canterbury', 'medway'))) {
| php | {
"resource": ""
} |
q4354 | API.get_item | train | public function get_item($url) {
$raw = $this->curl($url . '.json');
$json = json_decode($raw, true);
if (!$json) {
| php | {
"resource": ""
} |
q4355 | API.get_list | train | public function get_list($id, $campus = 'current') {
if ($campus == 'current') {
$campus = $this->_campus;
}
if (is_array($campus)) {
throw new \Exception("Campus cannot be an array!"); | php | {
"resource": ""
} |
q4356 | AccessToken.postIndex | train | public function postIndex()
{
$oInput = Factory::service('Input');
$oHttpCodes = Factory::service('HttpCodes');
$oAuthModel = Factory::model('Auth', 'nails/module-auth');
$oAccessTokenModel = Factory::model('UserAccessToken', 'nails/module-auth');
$sIdentifier = $oInput->post('identifier');
$sPassword = $oInput->post('password');
$sScope = $oInput->post('scope');
$sLabel = $oInput->post('label');
$bIsValid = $oAuthModel->verifyCredentials($sIdentifier, $sPassword);
if (!$bIsValid) {
throw new ApiException(
'Invalid login credentials',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
/**
* User credentials are valid, but a few other tests are still required:
* - User is not suspended
* - Password is not temporary
* - Password is not expired
* - @todo: handle 2FA, perhaps?
*/
$oUserModel | php | {
"resource": ""
} |
q4357 | AccessToken.postRevoke | train | public function postRevoke()
{
$oHttpCodes = Factory::service('HttpCodes');
$oAccessTokenModel = Factory::model('UserAccessToken', 'nails/module-auth');
if (!isLoggedIn()) {
throw new ApiException(
'You must be logged in',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oInput = Factory::service('Input');
$sAccessToken = $oInput->post('access_token');
if (empty($sAccessToken)) {
throw new ApiException(
'An access token to revoke must be provided',
| php | {
"resource": ""
} |
q4358 | User.init | train | public function init()
{
$oInput = Factory::service('Input');
$iTestingAsUser = $oInput->header(Testing::TEST_HEADER_USER_NAME);
if (Environment::not(Environment::ENV_PROD) && $iTestingAsUser) {
$oUser = $this->getById($iTestingAsUser);
if (empty($oUser)) {
set_status_header(500);
ErrorHandler::halt('Not a valid user ID');
}
$this->setLoginData($oUser->id);
| php | {
"resource": ""
} |
q4359 | User.loginRememberedUser | train | protected function loginRememberedUser()
{
// Is remember me functionality enabled?
$oConfig = Factory::service('Config');
$oConfig->load('auth/auth');
if (!$oConfig->item('authEnableRememberMe')) {
return false;
}
// --------------------------------------------------------------------------
// Get the credentials from the cookie set earlier
$remember = get_cookie($this->sRememberCookie);
if ($remember) {
$remember = explode('|', $remember);
$email = isset($remember[0]) ? $remember[0] : null;
$code = isset($remember[1]) ? $remember[1] : | php | {
"resource": ""
} |
q4360 | User.activeUser | train | public function activeUser($sKeys = '', $sDelimiter = ' ')
{
// Only look for a value if we're logged in
if (!$this->isLoggedIn()) {
return false;
}
// --------------------------------------------------------------------------
// If $sKeys is false just return the user object in its entirety
if (empty($sKeys)) {
return $this->activeUser;
}
// --------------------------------------------------------------------------
// If only one key is being requested then don't do anything fancy
if (strpos($sKeys, ',') === false) {
$val = isset($this->activeUser->{trim($sKeys)}) ? $this->activeUser->{trim($sKeys)} : null;
} else {
// More than one key
$aKeys = explode(',', $sKeys);
$aKeys = array_filter($aKeys);
$aOut = [];
foreach ($aKeys as $sKey) {
| php | {
"resource": ""
} |
q4361 | User.setActiveUser | train | public function setActiveUser($oUser)
{
$this->activeUser = $oUser;
$oDateTimeService = Factory::service('DateTime');
// Set the user's date/time formats
$sFormatDate = $this->activeUser('pref_date_format');
$sFormatDate = $sFormatDate ? $sFormatDate : $oDateTimeService->getDateFormatDefaultSlug();
| php | {
"resource": ""
} |
q4362 | User.setLoginData | train | public function setLoginData($mIdEmail, $bSetSessionData = true)
{
// Valid user?
if (is_numeric($mIdEmail)) {
$oUser = $this->getById($mIdEmail);
$sError = 'Invalid User ID.';
} elseif (is_string($mIdEmail)) {
Factory::helper('email');
if (valid_email($mIdEmail)) {
$oUser = $this->getByEmail($mIdEmail);
$sError = 'Invalid User email.';
} else {
$this->setError('Invalid User email.');
return false;
}
} else {
$this->setError('Invalid user ID or email.');
return false;
}
// --------------------------------------------------------------------------
// Test user
if (!$oUser) {
$this->setError($sError);
return false;
} elseif ($oUser->is_suspended) {
$this->setError('User is suspended.');
return false;
} else {
| php | {
"resource": ""
} |
q4363 | User.clearLoginData | train | public function clearLoginData()
{
// Clear the session
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->unsetUserData('id');
$oSession->unsetUserData('email');
$oSession->unsetUserData('group_id');
// Set the flag
$this->bIsLoggedIn = false;
| php | {
"resource": ""
} |
q4364 | User.bIsRemembered | train | public function bIsRemembered()
{
// Deja vu?
if (!is_null($this->bIsRemembered)) {
return $this->bIsRemembered;
}
// --------------------------------------------------------------------------
/**
* Look for the remember me cookie and explode it, if we're landed with a 2
* part array then it's likely this is a valid cookie - however, this test | php | {
"resource": ""
} |
q4365 | User.setAdminRecoveryData | train | public function setAdminRecoveryData($loggingInAs, $returnTo = '')
{
$oSession = Factory::service('Session', 'nails/module-auth');
$oInput = Factory::service('Input');
// Look for existing Recovery Data
$existingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField);
if (empty($existingRecoveryData)) {
$existingRecoveryData = [];
}
// Prepare the new element
$adminRecoveryData = new \stdClass();
$adminRecoveryData->oldUserId = activeUser('id');
$adminRecoveryData->newUserId = $loggingInAs;
$adminRecoveryData->hash = md5(activeUser('password'));
$adminRecoveryData->name = activeUser('first_name,last_name');
$adminRecoveryData->email = activeUser('email');
$adminRecoveryData->returnTo = empty($returnTo) ? $oInput->server('REQUEST_URI') : $returnTo;
| php | {
"resource": ""
} |
q4366 | User.getAdminRecoveryData | train | public function getAdminRecoveryData()
{
$oSession = Factory::service('Session', 'nails/module-auth');
$existingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField);
| php | {
"resource": ""
} |
q4367 | User.unsetAdminRecoveryData | train | public function unsetAdminRecoveryData()
{
$oSession = Factory::service('Session', 'nails/module-auth');
$aExistingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField);
if (empty($aExistingRecoveryData)) {
$aExistingRecoveryData = [];
} | php | {
"resource": ""
} |
q4368 | User.hasPermission | train | public function hasPermission($sSearch, $mUser = null)
{
// Fetch the correct ACL
if (is_numeric($mUser)) {
$oUser = $this->getById($mUser);
if (isset($oUser->acl)) {
$aAcl = $oUser->acl;
unset($oUser);
} else {
return false;
}
} elseif (isset($mUser->acl)) {
$aAcl = $mUser->acl;
} else {
$aAcl = (array) $this->activeUser('acl');
}
// --------------------------------------------------------------------------
// Super users or CLI users can do anything their heart desires
$oInput = Factory::service('Input');
if (in_array('admin:superuser', $aAcl) || $oInput::isCli()) {
return true;
}
// --------------------------------------------------------------------------
/**
* Test the ACL
* We're going to use regular expressions here so we can allow for some
* flexibility in the search, i.e admin:* would return true if the user has
* access to any of admin.
*/
| php | {
"resource": ""
} |
q4369 | User.getUserColumns | train | protected function getUserColumns($sPrefix = '', $aCols = [])
{
if ($this->aUserColumns === null) {
$oDb = Factory::service('Database');
$aResult = $oDb->query('DESCRIBE `' . $this->table . '`')->result();
$this->aUserColumns = [];
foreach ($aResult as | php | {
"resource": ""
} |
q4370 | User.getMetaColumns | train | protected function getMetaColumns($sPrefix = '', $aCols = [])
{
if ($this->aMetaColumns === null) {
$oDb = Factory::service('Database');
$aResult = $oDb->query('DESCRIBE `' . $this->tableMeta . '`')->result();
$this->aMetaColumns = [];
foreach ($aResult as $oResult) {
if ($oResult->Field !== 'user_id') {
| php | {
"resource": ""
} |
q4371 | User.prepareDbColumns | train | protected function prepareDbColumns($sPrefix = '', $aCols = [])
{
// Clean up
$aCols = array_unique($aCols);
$aCols = array_filter($aCols);
// Prefix all the values, if needed
if ($sPrefix) {
| php | {
"resource": ""
} |
q4372 | User.getByIdentifier | train | public function getByIdentifier($identifier)
{
switch (APP_NATIVE_LOGIN_USING) {
case 'EMAIL':
$user = $this->getByEmail($identifier);
break;
case 'USERNAME':
$user = $this->getByUsername($identifier);
break;
default:
Factory::helper('email');
if (valid_email($identifier)) {
| php | {
"resource": ""
} |
q4373 | User.getByEmail | train | public function getByEmail($email)
{
if (!is_string($email)) {
return false;
}
// --------------------------------------------------------------------------
// Look up the email, and if we find an ID then fetch that user
$oDb = Factory::service('Database');
$oDb->select('user_id'); | php | {
"resource": ""
} |
q4374 | User.getByUsername | train | public function getByUsername($username)
{
if (!is_string($username)) {
return false;
}
$data = [
'where' => [
[ | php | {
"resource": ""
} |
q4375 | User.getByHashes | train | public function getByHashes($md5Id, $md5Pw)
{
if (empty($md5Id) || empty($md5Pw)) {
return false;
}
$data = [
'where' => [
[
'column' => $this->tableAlias . '.id_md5',
'value' => $md5Id,
],
[
| php | {
"resource": ""
} |
q4376 | User.getByReferral | train | public function getByReferral($referralCode)
{
if (!is_string($referralCode)) {
return false;
}
$data = [
'where' => [
| php | {
"resource": ""
} |
q4377 | User.getEmailsForUser | train | public function getEmailsForUser($id)
{
$oDb = Factory::service('Database');
$oDb->where('user_id', $id);
$oDb->order_by('date_added');
| php | {
"resource": ""
} |
q4378 | User.setCacheUser | train | public function setCacheUser($iUserId, $aData = [])
{
$this->unsetCacheUser($iUserId);
$oUser = $this->getById($iUserId);
if (empty($oUser)) {
return false;
}
| php | {
"resource": ""
} |
q4379 | User.emailAddSendVerify | train | public function emailAddSendVerify($email_id, $iUserId = null)
{
// Fetch the email and the user's group
$oDb = Factory::service('Database');
$oDb->select(
[
$this->tableEmailAlias . '.id',
$this->tableEmailAlias . '.code',
$this->tableEmailAlias . '.is_verified',
$this->tableEmailAlias . '.user_id',
$this->tableAlias . '.group_id',
]
);
if (is_numeric($email_id)) {
$oDb->where($this->tableEmailAlias . '.id', $email_id);
} else {
$oDb->where($this->tableEmailAlias . '.email', $email_id);
}
if (!empty($iUserId)) {
$oDb->where($this->tableEmailAlias . '.user_id', $iUserId);
}
$oDb->join(
$this->table . ' ' . $this->tableAlias,
$this->tableAlias . '.id = ' . $this->tableEmailAlias . '.user_id'
);
$oEmailRow = $oDb->get($this->tableEmail . ' ' . $this->tableEmailAlias)->row();
if (!$oEmailRow) {
$this->setError('Invalid Email.');
return false;
}
if ($oEmailRow->is_verified) {
$this->setError('Email is already verified.');
return false;
}
// --------------------------------------------------------------------------
| php | {
"resource": ""
} |
q4380 | User.emailMakePrimary | train | public function emailMakePrimary($mIdEmail, $iUserId = null)
{
// Fetch email
$oDb = Factory::service('Database');
$oDb->select('id,user_id,email');
if (is_numeric($mIdEmail)) {
$oDb->where('id', $mIdEmail);
} else {
$oDb->where('email', $mIdEmail);
}
if (!is_null($iUserId)) {
$oDb->where('user_id', $iUserId);
}
$oEmail = $oDb->get($this->tableEmail)->row();
if (empty($oEmail)) {
return false;
}
// Update
$oDb->trans_begin();
try {
$oDb->set('is_primary', false);
$oDb->where('user_id', $oEmail->user_id);
$oDb->update($this->tableEmail);
$oDb->set('is_primary', true);
$oDb->where('id', $oEmail->id);
$oDb->update($this->tableEmail);
$this->unsetCacheUser($oEmail->user_id);
// Update the activeUser
if ($oEmail->user_id == $this->activeUser('id')) {
$oDate | php | {
"resource": ""
} |
q4381 | User.incrementFailedLogin | train | public function incrementFailedLogin($iUserId, $expires = 300)
{
$oDate = Factory::factory('DateTime');
$oDate->add(new \DateInterval('PT' . $expires . 'S'));
$oDb = Factory::service('Database');
| php | {
"resource": ""
} |
q4382 | User.resetFailedLogin | train | public function resetFailedLogin($iUserId)
{
$oDb = Factory::service('Database');
| php | {
"resource": ""
} |
q4383 | User.setRememberCookie | train | public function setRememberCookie($iId = null, $sPassword = null, $sEmail = null)
{
// Is remember me functionality enabled?
$oConfig = Factory::service('Config');
$oConfig->load('auth/auth');
if (!$oConfig->item('authEnableRememberMe')) {
return false;
}
// --------------------------------------------------------------------------
if (empty($iId) || empty($sPassword) || empty($sEmail)) {
if (!activeUser('id') || !activeUser('password') || !activeUser('email')) {
return false;
} else {
$iId = $this->activeUser('id');
$sPassword = $this->activeUser('password');
| php | {
"resource": ""
} |
q4384 | User.refreshSession | train | protected function refreshSession()
{
// Get the user; be wary of admin's logged in as other people
$oSession = Factory::service('Session', 'nails/module-auth');
if ($this->wasAdmin()) {
$recoveryData = $this->getAdminRecoveryData();
if (!empty($recoveryData->newUserId)) {
$me = $recoveryData->newUserId;
} else {
$me = $oSession->getUserData('id');
}
} else {
$me = $oSession->getUserData('id');
}
// Is anybody home? Hello...?
if (!$me) {
$me = $this->me;
if (!$me) {
return false;
}
}
$me = $this->getById($me);
// --------------------------------------------------------------------------
/**
* If the user is isn't found (perhaps deleted) or has been suspended then
* obviously don't proceed with the log in
*/
if (!$me || !empty($me->is_suspended)) {
$this->clearRememberCookie();
$this->clearActiveUser();
$this->clearLoginData();
$this->bIsLoggedIn = false;
return false;
| php | {
"resource": ""
} |
q4385 | User.generateReferral | train | protected function generateReferral()
{
Factory::helper('string');
$oDb = Factory::service('Database');
$sReferral = '';
while (1 > 0) {
$sReferral = random_string('alnum', 8);
$oQuery = $oDb->get_where($this->table, | php | {
"resource": ""
} |
q4386 | User.isValidUsername | train | public function isValidUsername($username, $checkDb = false, $ignoreUserId = null)
{
/**
* Check username doesn't contain invalid characters - we're actively looking
* for characters which are invalid so we can say "Hey! The following
* characters are invalid" rather than making the user guess, y'know, 'cause
* we're good guys.
*/
$invalidChars = '/[^a-zA-Z0-9\-_\.]/';
// Minimum length of the username
$minLength = 2;
// --------------------------------------------------------------------------
// Check for illegal characters
$containsInvalidChars = preg_match($invalidChars, $username);
if ($containsInvalidChars) {
$msg = 'Username can only contain alpha numeric characters, underscores, periods and dashes (no spaces).';
$this->setError($msg);
return false;
}
// --------------------------------------------------------------------------
// Check length
if (strlen($username) < $minLength) {
$this->setError('Usernames must be at least ' . $minLength . ' characters long.');
| php | {
"resource": ""
} |
q4387 | User.describeFields | train | public function describeFields($sTable = null)
{
$aFields = parent::describeFields($sTable);
$aMetaFields = parent::describeFields($this->tableMeta);
| php | {
"resource": ""
} |
q4388 | ProvidesDateTimeInformation.dayOfWeekLocal | train | public function dayOfWeekLocal(string $locale = null) : int
{
$calendar = $this->createCalendar($locale);
| php | {
"resource": ""
} |
q4389 | AttachmentWidget.attachmentTypes | train | public function attachmentTypes()
{
$attachableObjects = $this->attachableObjects();
$out = [];
if (!$attachableObjects) {
return $out;
}
$i = 0;
foreach ($attachableObjects as $attType => $attMeta) {
$i++;
$label = $attMeta['label'];
$out[] = [
'id' => (isset($attMeta['att_id']) ? $attMeta['att_id'] : null),
'ident' => $this->createIdent($attType),
'skipForm' => $attMeta['skipForm'],
'formIdent' | php | {
"resource": ""
} |
q4390 | AttachmentWidget.attachments | train | public function attachments()
{
$attachableObjects = $this->attachableObjects();
$attachments = $this->obj()->getAttachments([
'group' => $this->group()
]);
foreach ($attachments as $attachment) {
$GLOBALS['widget_template'] = (string)$attachment->rawPreview();
if (isset($attachableObjects[$attachment->objType()])) {
| php | {
"resource": ""
} |
q4391 | AttachmentWidget.setData | train | public function setData(array $data)
{
$this->isMergingData = true;
/**
* @todo Kinda hacky, but works with the concept of form.
* Should work embeded in a form group or in a dashboard.
*/
$data = array_merge($_GET, $data);
parent::setData($data);
/** Merge any available presets */
| php | {
"resource": ""
} |
q4392 | AttachmentWidget.setAttachmentOptions | train | public function setAttachmentOptions(array $settings)
{
$this->attachmentOptions = array_merge(
$this->defaultAttachmentOptions(),
| php | {
"resource": ""
} |
q4393 | AttachmentWidget.setGroup | train | public function setGroup($group)
{
if (!is_string($group) && $group !== null) {
throw new InvalidArgumentException(sprintf(
'Attachment group must be string, received %s',
| php | {
"resource": ""
} |
q4394 | AttachmentWidget.attachmentOptions | train | public function attachmentOptions()
{
if ($this->attachmentOptions === null) { | php | {
"resource": ""
} |
q4395 | AttachmentWidget.widgetOptions | train | public function widgetOptions()
{
$options = [
'obj_type' => $this->obj()->objType(),
'obj_id' => $this->obj()->id(),
'group' => $this->group(),
'attachment_options' => $this->attachmentOptions(),
'attachable_objects' => $this->attachableObjects(),
| php | {
"resource": ""
} |
q4396 | MultiCurrencyMoney.equals | train | public function equals(Money $money)
{
if (!$money instanceof MultiCurrencyMoney) {
| php | {
"resource": ""
} |
q4397 | MultiCurrencyMoney.reduce | train | public function reduce(BankInterface $bank = null, $toCurrency = null)
{
if (null === $bank) {
$bank = static::getBank();
}
if (!$bank instanceof MultiCurrencyBankInterface) {
throw new \InvalidArgumentException('The supplied bank must implement MultiCurrencyBankInterface');
}
$rate = $bank->getRate($this->currency, $toCurrency);
| php | {
"resource": ""
} |
q4398 | Builder.build | train | public function build(array $strings)
{
$strings = array_unique($strings);
sort($strings);
if ($this->isEmpty($strings))
{
return '';
}
$strings = | php | {
"resource": ""
} |
q4399 | AdminView.render | train | public function render($view = null, $layout = null)
{
//Sets some view vars
$this->set('priorities', [
'1' => sprintf('1 - %s', __d('me_cms', 'Very low')),
'2' => sprintf('2 - %s', __d('me_cms', 'Low')),
'3' => sprintf('3 - %s', __d('me_cms', 'Normal')),
| php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.