_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | 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']);
}
// Setting bcc (black-carbon-copy) field(s).
$bcc = $this->bcc();
foreach ($bcc as $bccRecipient) {
$bccArr = $this->emailToArray($bccRecipient);
$mail->addBCC($bccArr['email'], $bccArr['name']);
}
// Setting attachment(s), if required.
$attachments = $this->attachments();
foreach ($attachments as $att) {
$mail->addAttachment($att);
}
$mail->isHTML(true);
$mail->Subject = $this->subject();
$mail->Body = $this->msgHtml();
$mail->AltBody = $this->msgTxt();
$ret = $mail->send();
$this->logSend($ret, $mail);
return $ret;
} catch (Exception $e) {
$this->logger->error(
sprintf('Error sending email: %s', $e->getMessage())
);
}
} | 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'])
);
$mail->isSMTP();
$mail->Host = $config['smtp_hostname'];
$mail->Port = $config['smtp_port'];
$mail->SMTPAuth = $config['smtp_auth'];
$mail->Username = $config['smtp_username'];
$mail->Password = $config['smtp_password'];
$mail->SMTPSecure = $config['smtp_security'];
} | 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) {
$queueItem = $this->queueItemFactory()->create(EmailQueueItem::class);
$queueItem->setTo($to);
$queueItem->setFrom($author);
$queueItem->setSubject($subject);
$queueItem->setMsgHtml($msgHtml);
$queueItem->setMsgTxt($msgTxt);
$queueItem->setCampaign($campaign);
$queueItem->setProcessingDate($ts);
$queueItem->setQueueId($queueId);
$res = $queueItem->save();
}
return true;
} | php | {
"resource": ""
} |
q4303 | Email.viewController | train | public function viewController()
{
$templateIdent = $this->templateIdent();
if (!$templateIdent) {
return [];
}
$templateFactory = clone($this->templateFactory());
$templateFactory->setDefaultClass(GenericEmailTemplate::class);
$template = $templateFactory->create($templateIdent);
$template->setData($this->templateData());
return $template;
} | php | {
"resource": ""
} |
q4304 | Email.generateMsgHtml | train | protected function generateMsgHtml()
{
$templateIdent = $this->templateIdent();
if (!$templateIdent) {
$message = '';
} else {
$message = $this->renderTemplate($templateIdent);
}
return $message;
} | 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);
// Trim whitespace
$str = str_replace("\t", '', $str);
$str = preg_replace('#\n\r|\r\n#', "\n", $str);
$str = preg_replace('#\n{3,}#', "\n\n", $str);
$str = preg_replace('/ {2,}/', ' ', $str);
$str = implode("\n", array_map('trim', explode("\n", $str)));
$str = trim($str)."\n";
return $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) {
$log = $this->logFactory()->create('charcoal/email/email-log');
$log->setType('email');
$log->setAction('send');
$log->setRawResponse($mailer);
$log->setMessageId($mailer->getLastMessageId());
$log->setCampaign($this->campaign());
$log->setSendDate('now');
$log->setFrom($mailer->From);
$log->setTo($to);
$log->setSubject($this->subject());
$log->save();
}
} | php | {
"resource": ""
} |
q4307 | Mo.get | train | public function get( $original )
{
$original = (string) $original;
if( isset( $this->messages[$original] ) ) {
return $this->messages[$original];
}
return false;
} | 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
$trans = $this->readInt( $byteOrder ); //offset of translation table
$this->seekto( $originals );
$originalTable = $this->readIntArray( $byteOrder, $total * 2 );
$this->seekto( $trans );
$translationTable = $this->readIntArray( $byteOrder, $total * 2 );
return $this->extractTable( $originalTable, $translationTable, $total );
} | 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 ) {
list( $original, $plural ) = explode( "\000", $original );
}
if( $plural === null )
{
$messages[$original] = $translated;
continue;
}
$messages[$original] = [];
foreach( explode( "\x00", $translated ) as $idx => $value ) {
$messages[$original][$idx] = $value;
}
}
return $messages;
} | php | {
"resource": ""
} |
q4310 | Mo.readInt | train | protected function readInt( $byteOrder )
{
if( ( $content = $this->read( 4 )) === false ) {
return false;
}
$content = unpack( $byteOrder, $content );
return array_shift( $content );
} | 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'])
->order([sprintf('%s.title', $this->Pages->getAlias()) => 'ASC'])
->cache(sprintf('widget_list'), $this->Pages->getCacheName())
->all();
$this->set(compact('pages'));
} | 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.'
);
}
} catch (\Exception $e) {
$oResponse = Factory::factory('CaptchaForm', 'nails/module-captcha');
$oResponse->setHtml(
'<p style="color: red; padding: 1rem; border: 1px solid red;">ERROR: ' . $e->getMessage() . '</p>'
);
}
return $oResponse;
} | php | {
"resource": ""
} |
q4313 | AbstractConnector.getPdo | train | public function getPdo()
{
if ($this->pdo === null) {
$this->pdo = $this->doConnect();
}
return $this->pdo;
} | php | {
"resource": ""
} |
q4314 | AbstractConnector.disconnect | train | public function disconnect()
{
if ($this->pdo !== null) {
$this->doDisconnect($this->pdo);
$this->pdo = null;
}
} | php | {
"resource": ""
} |
q4315 | MetaController.performAjaxValidation | train | protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='ommu-meta-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
} | 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);
$oDb->set('modified', 'NOW()', false);
if (isLoggedIn()) {
$oDb->set('modified_by', activeUser('id'));
}
$oDb->where('id', $oGroup->id);
$oDb->update($this->getTableName());
if ($oDb->trans_status() === false) {
$oDb->trans_rollback();
return false;
} else {
$oDb->trans_commit();
$this->getDefaultGroup();
return true;
}
} | php | {
"resource": ""
} |
q4317 | Group.getDefaultGroup | train | public function getDefaultGroup()
{
$aGroups = $this->getAll([
'where' => [
['is_default', true],
],
]);
if (empty($aGroups)) {
throw new NailsException('A default user group must be defined.');
}
$this->oDefaultGroup = reset($aGroups);
return $this->oDefaultGroup;
} | 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.
*/
$bHasPermission = false;
/**
* Replace :* with :.* - this is a common mistake when using the permission
* system (i.e., assuming that star on it's own will match)
*/
$sSearch = preg_replace('/:\*/', ':.*', $sSearch);
foreach ($aAcl as $sPermission) {
$sPattern = '/^' . $sSearch . '$/';
$bMatch = preg_match($sPattern, $sPermission);
if ($bMatch) {
$bHasPermission = true;
break;
}
}
return $bHasPermission;
} | 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);
}
if (extension_loaded('iconv')) {
define('ICONV_ENABLED', true);
@ini_set('iconv.internal_encoding', $sCharset);
} else {
define('ICONV_ENABLED', false);
}
if (is_php('5.6')) {
ini_set('php.internal_encoding', $sCharset);
}
} | 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 as $column => $desc) {
$r = strnatcmp($a[$column], $b[$column]);
if ($r !== 0) {
return $r * $desc;
}
}
return 0;
};
usort($this->data, $cmp);
} | php | {
"resource": ""
} |
q4321 | ArraySet.getData | train | public function getData() {
if ($this->toSort && !empty($this->getOrder())) {
$this->sortData();
}
if ($this->getLimit()) {
return array_slice($this->data, $this->getOffset(), $this->getLimit());
} else {
return $this->data;
}
} | php | {
"resource": ""
} |
q4322 | ArraySet.setData | train | public function setData($data) {
if ($data instanceof \Traversable) {
$this->data = iterator_to_array($data);
} else {
$this->data = $data;
}
if (!empty($this->getOrder())) {
$this->toSort = true;
}
return $this;
} | php | {
"resource": ""
} |
q4323 | Security.decryptMail | train | public static function decryptMail($mail, $key = null, $hmacSalt = null)
{
return parent::decrypt(base64_decode($mail), $key ?: Configure::read('RecaptchaMailhide.encryptKey'), $hmacSalt);
} | php | {
"resource": ""
} |
q4324 | Security.encryptMail | train | public static function encryptMail($mail, $key = null, $hmacSalt = null)
{
return base64_encode(parent::encrypt($mail, $key ?: Configure::read('RecaptchaMailhide.encryptKey'), $hmacSalt));
} | php | {
"resource": ""
} |
q4325 | Base.loadStyles | train | protected function loadStyles($sView)
{
// Test if a view has been provided by the app
if (!is_file($sView)) {
$oAsset = Factory::service('Asset');
$oAsset->clear();
$oAsset->load('nails.min.css', 'nails/common');
$oAsset->load('styles.min.css', 'nails/module-auth');
}
} | 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();
} catch (ValidationFailedException $e) {
// Schema validation errors
$this->errors[] = $e->getMessage();
} catch (\Exception $e) {
// Anything else we did not anticipate
$this->errors[] = 'Unknown Exception in getPageDefinition()';
$this->errors[] = $e->getMessage();
}
return null;
} | php | {
"resource": ""
} |
q4327 | SystemsController.acceptCookies | train | public function acceptCookies()
{
$this->response = $this->response->withCookie((new Cookie('cookies-policy', true))->withNeverExpire());
return $this->redirect($this->referer(['_name' => 'homepage'], true));
} | 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);
return $this->redirect(['_name' => 'homepage']);
}
$this->Flash->error(I18N_OPERATION_NOT_OK);
} else {
$this->Flash->error(__d('me_cms', 'You must fill in the {0} control correctly', 'reCAPTCHA'));
}
}
$this->set(compact('contact'));
} | php | {
"resource": ""
} |
q4329 | SystemsController.ipNotAllowed | train | public function ipNotAllowed()
{
//If the user's IP address is not banned
if (!$this->request->isBanned()) {
return $this->redirect($this->referer(['_name' => 'homepage'], true));
}
$this->viewBuilder()->setLayout('login');
} | 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()) {
$sitemap = file_get_contents(SITEMAP);
}
}
if (empty($sitemap)) {
$sitemap = gzencode(Sitemap::generate(), 9);
(new File(SITEMAP, true, 0777))->write($sitemap);
}
return $this->response->withFile(SITEMAP);
} | 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);
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(I18N_OPERATION_NOT_OK);
}
$this->set(compact('album'));
} | 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);
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(I18N_OPERATION_NOT_OK);
}
$this->set(compact('album'));
} | 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);
$this->Flash->success(I18N_OPERATION_OK);
} else {
$this->Flash->alert(I18N_BEFORE_DELETE);
}
return $this->redirect(['action' => 'index']);
} | php | {
"resource": ""
} |
q4334 | DoughExtension.getAmount | train | public function getAmount(MoneyInterface $money = null, $currency = null)
{
if (null === $money) {
return 0.0;
}
$reduced = $this->bank->reduce($money, $currency);
return $reduced->getAmount();
} | 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) {
return $text;
}
// Truncate to character limit if longer than requested
$text = substr($text, 0, $characters);
// We don't want the string cut mid-word, so search for the last space and trim there
$lastSpacePosition = strrpos($text, ' ');
if (isset($lastSpacePosition)) {
// Cut the text at this last word
$text = substr($text, 0, $lastSpacePosition);
}
return $text;
} | 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
if (is_dir($dirPath)) {
foreach (new FilesystemIterator($dirPath) as $dirObject) {
if (($ignoreDirectories && $dirObject->isDir()) || preg_match($pattern, $dirObject->getFilename())) {
continue;
}
$baseName = $dirObject->getBasename('.' . $dirObject->getExtension());
$readableFileName = preg_replace($splitCamelCase, '$1 ', $baseName);
$readableFileName = ucwords($readableFileName);
$files[] = [
'filename' => $dirObject->getFilename(),
'basename' => $baseName,
'readname' => $readableFileName
];
}
}
return $files;
} | 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 */
$anotherDistanceInMeters = ToFloat::toPositiveFloat($anotherDistanceInMeters);
return $oneDistanceInMeters <=> $anotherDistanceInMeters; // lowest first
});
return $values;
} | 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] === '-') {
$order = $this->escape(substr($column, 1)).' desc';
} else {
$order = $this->escape($column);
}
$orders[] = $order;
}
$sql .= "\norder by ".implode(', ', $orders);
}
// Build the limit, offset.
if (!empty($options['limit'])) {
$limit = (int)$options['limit'];
$sql .= "\nlimit $limit";
}
if (!empty($options['offset'])) {
$sql .= ' offset '.((int)$options['offset']);
} elseif (isset($options['page'])) {
$offset = $options['limit'] * ($options['page'] - 1);
$sql .= ' offset '.$offset;
}
return $sql;
} | php | {
"resource": ""
} |
q4339 | MySqlDb.getDbName | train | private function getDbName() {
if (!isset($this->dbname)) {
$this->dbname = $this->getPDO()->query('select database()')->fetchColumn();
}
return $this->dbname;
} | 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) {
$index = [
'type' => null,
'columns' => array_column($columns, 'COLUMN_NAME'),
'name' => $indexName
];
if ($indexName === 'PRIMARY') {
$index['type'] = Db::INDEX_PK;
} else {
$index['type'] = $columns[0]['NON_UNIQUE'] ? Db::INDEX_IX : Db::INDEX_UNIQUE;
}
$indexes[] = $index;
}
return $indexes;
} | 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 ';
}
$sql .= $this->prefixTable($table);
// Add the list of values.
$sql .=
"\n".$this->bracketList(array_keys($row), '`').
"\nvalues".$this->bracketList($row, "'");
return $sql;
} | 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 ($row as $key => $value) {
$updates[] = $this->escape($key).' = values('.$this->escape($key).')';
}
$sql .= "\non duplicate key update ".implode(', ', $updates);
return $sql;
} | 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)) {
case Db::INDEX_IX:
return "index $indexName ".$this->bracketList($def['columns'], '`');
case Db::INDEX_UNIQUE:
return "unique $indexName ".$this->bracketList($def['columns'], '`');
case Db::INDEX_PK:
return "primary key ".$this->bracketList($def['columns'], '`');
}
return null;
} | 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 filter_var($value, FILTER_VALIDATE_INT);
} elseif (in_array($type, ['real', 'double', 'double precision', 'float',
'numeric', 'number', 'decimal(10,5)'])) {
return filter_var($value, FILTER_VALIDATE_FLOAT);
} else {
return (string)$value;
}
} | php | {
"resource": ""
} |
q4345 | MySqlDb.argValue | train | private function argValue($value) {
if (is_bool($value)) {
return (int)$value;
} elseif ($value instanceof \DateTimeInterface) {
return $value->format(self::MYSQL_DATE_FORMAT);
} else {
return $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,
'%' . $wpdb->esc_like($this->permalinkBefore) . '%'
)
);
$this->permalinksUpdated += $wpdb->rows_affected;
if ($this->permalinksUpdated > 0) {
add_notice(sprintf('%d links to this post was updated to use the new permalink.', $this->permalinksUpdated));
}
return true;
} | 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)) {
$this->data = $absolute;
return $this;
}
//if we are here then it means that no path was found so we should throw an exception
Exception::i()
->setMessage(self::ERROR_FULL_PATH_NOT_FOUND)
->addVariable($this->data)
->addVariable($absolute)
->trigger();
} | 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) {
//check for type errors
$argument->test($i + 1, $path, 'string');
//add to path
$this->data .= $this->format($path);
}
return $this;
} | 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) {
//check for type errors
$error->test($i + 1, $path, 'string');
//add to path
$this->data = $this->format($path).$this->data;
}
return $this;
} | php | {
"resource": ""
} |
q4350 | Index.pop | train | public function pop()
{
//get the path array
$pathArray = $this->getArray();
//remove the last
$path = array_pop($pathArray);
//set path
$this->data = implode('/', $pathArray);
return $path;
} | 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 new
$pathArray[] = $path;
//assign back to path
$this->data = implode('/', $pathArray);
return $this;
} | 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 the path does not have a colon
//(this is a test for windows)
if (substr($path, 0, 1) != '/' && !preg_match("/^[A-Za-z]+\:/", $path)) {
//it's safe to add a slash
$path = '/'.$path;
}
return $path;
} | 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'))) {
throw new \Exception("Invalid campus: '{$campus}'.");
}
$this->_campus[] = $c;
}
} | php | {
"resource": ""
} |
q4354 | API.get_item | train | public function get_item($url) {
$raw = $this->curl($url . '.json');
$json = json_decode($raw, true);
if (!$json) {
return null;
}
return new Item($this, $url, $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!");
}
$url = self::CANTERBURY_URL;
if ($campus == 'medway') {
$url = self::MEDWAY_URL;
}
$raw = $this->curl($url . '/sections/' . $id . '.json');
$parser = new Parser($this, $url, $raw);
return $parser->get_list($id);
} | 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 = Factory::model('User', 'nails/module-auth');
$oUserPasswordModel = Factory::model('UserPassword', 'nails/module-auth');
$oUser = $oUserModel->getByIdentifier($sIdentifier);
$bIsSuspended = $oUser->is_suspended;
$bPwIsTemp = $oUser->temp_pw;
$bPwIsExpired = $oUserPasswordModel->isExpired($oUser->id);
if ($bIsSuspended) {
throw new ApiException(
'User account is suspended',
$oHttpCodes::STATUS_UNAUTHORIZED
);
} elseif ($bPwIsTemp) {
throw new ApiException(
'Password is temporary',
$oHttpCodes::STATUS_UNAUTHORIZED
);
} elseif ($bPwIsExpired) {
throw new ApiException(
'Password has expired',
$oHttpCodes::STATUS_UNAUTHORIZED
);
}
$oToken = $oAccessTokenModel->create([
'user_id' => $oUser->id,
'label' => $sLabel,
'scope' => $sScope,
]);
if (!$oToken) {
throw new ApiException(
'Failed to generate access token. ' . $oAccessTokenModel->lastError(),
$oHttpCodes::STATUS_INTERNAL_SERVER_ERROR
);
}
return Factory::factory('ApiResponse', 'nails/module-api')
->setData([
'token' => $oToken->token,
'expires' => $oToken->expires,
]);
} | 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',
$oHttpCodes::STATUS_BAD_REQUEST
);
}
if (!$oAccessTokenModel->revoke(activeUser('id'), $sAccessToken)) {
throw new ApiException(
'Failed to revoke access token. ' . $oAccessTokenModel->lastError(),
$oHttpCodes::STATUS_INTERNAL_SERVER_ERROR
);
}
return Factory::factory('ApiResponse', 'nails/module-api');
} | 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);
} else {
// Refresh user's session
$this->refreshSession();
// If no user is logged in, see if there's a remembered user to be logged in
if (!$this->isLoggedIn()) {
$this->loginRememberedUser();
}
}
} | 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] : null;
if ($email && $code) {
// Look up the user so we can cross-check the codes
$user = $this->getByEmail($email);
if ($user && $code === $user->remember_code) {
// User was validated, log them in!
$this->setLoginData($user->id);
$this->me = $user->id;
}
}
}
return true;
} | 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) {
// If something is found, use that.
if (isset($this->activeUser->{trim($sKey)})) {
$aOut[] = $this->activeUser->{trim($sKey)};
}
}
// If nothing was found, just return null
if (empty($aOut)) {
$val = null;
} else {
$val = implode($sDelimiter, $aOut);
}
}
return $val;
} | 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();
$sFormatTime = $this->activeUser('pref_time_format');
$sFormatTime = $sFormatTime ? $sFormatTime : $oDateTimeService->getTimeFormatDefaultSlug();
$oDateTimeService->setFormats($sFormatDate, $sFormatTime);
} | 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 {
// Set the flag
$this->bIsLoggedIn = true;
// Set session variables
if ($bSetSessionData) {
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setUserData([
'id' => $oUser->id,
'email' => $oUser->email,
'group_id' => $oUser->group_id,
]);
}
// Set the active user
$this->setActiveUser($oUser);
return true;
}
} | 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;
// Reset the activeUser
$this->clearActiveUser();
// Remove any remember me cookie
$this->clearRememberCookie();
} | 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
* is, obviously, not gonna detect a spoof.
*/
$cookie = get_cookie($this->sRememberCookie);
$cookie = explode('|', $cookie);
$this->bIsRemembered = count($cookie) == 2 ? true : false;
return $this->bIsRemembered;
} | 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;
$adminRecoveryData->loginUrl = 'auth/override/login_as/';
$adminRecoveryData->loginUrl .= md5($adminRecoveryData->oldUserId) . '/' . $adminRecoveryData->hash;
$adminRecoveryData->loginUrl .= '?returningAdmin=1';
$adminRecoveryData->loginUrl = site_url($adminRecoveryData->loginUrl);
// Put the new session onto the stack and save to the session
$existingRecoveryData[] = $adminRecoveryData;
$oSession->setUserData($this->sAdminRecoveryField, $existingRecoveryData);
} | php | {
"resource": ""
} |
q4366 | User.getAdminRecoveryData | train | public function getAdminRecoveryData()
{
$oSession = Factory::service('Session', 'nails/module-auth');
$existingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField);
if (empty($existingRecoveryData)) {
return [];
} else {
return end($existingRecoveryData);
}
} | 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 = [];
} else {
array_pop($aExistingRecoveryData);
}
$oSession->setUserData($this->sAdminRecoveryField, $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.
*/
$bHasPermission = false;
/**
* Replace :* with :.* - this is a common mistake when using the permission
* system (i.e., assuming that star on it's own will match)
*/
$sSearch = strtolower(preg_replace('/:\*/', ':.*', $sSearch));
foreach ($aAcl as $sPermission) {
$sPattern = '/^' . $sSearch . '$/';
$bMatch = preg_match($sPattern, $sPermission);
if ($bMatch) {
$bHasPermission = true;
break;
}
}
return $bHasPermission;
} | 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 $oResult) {
$this->aUserColumns[] = $oResult->Field;
}
}
$aCols = array_merge($aCols, $this->aUserColumns);
return $this->prepareDbColumns($sPrefix, $aCols);
} | 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') {
$this->aMetaColumns[] = $oResult->Field;
}
}
}
$aCols = array_merge($aCols, $this->aMetaColumns);
return $this->prepareDbColumns($sPrefix, $aCols);
} | 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) {
foreach ($aCols as $key => &$value) {
$value = $sPrefix . '.' . $value;
}
}
return $aCols;
} | 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)) {
$user = $this->getByEmail($identifier);
} else {
$user = $this->getByUsername($identifier);
}
break;
}
return $user;
} | 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');
$oDb->where('email', trim($email));
$user = $oDb->get($this->tableEmail)->row();
return $user ? $this->getById($user->user_id) : false;
} | php | {
"resource": ""
} |
q4374 | User.getByUsername | train | public function getByUsername($username)
{
if (!is_string($username)) {
return false;
}
$data = [
'where' => [
[
'column' => $this->tableAlias . '.username',
'value' => $username,
],
],
];
$user = $this->getAll(null, null, $data);
return empty($user) ? false : $user[0];
} | 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,
],
[
'column' => $this->tableAlias . '.password_md5',
'value' => $md5Pw,
],
],
];
$user = $this->getAll(null, null, $data);
return empty($user) ? false : $user[0];
} | php | {
"resource": ""
} |
q4376 | User.getByReferral | train | public function getByReferral($referralCode)
{
if (!is_string($referralCode)) {
return false;
}
$data = [
'where' => [
[
'column' => $this->tableAlias . '.referral',
'value' => $referralCode,
],
],
];
$user = $this->getAll(null, null, $data);
return empty($user) ? false : $user[0];
} | php | {
"resource": ""
} |
q4377 | User.getEmailsForUser | train | public function getEmailsForUser($id)
{
$oDb = Factory::service('Database');
$oDb->where('user_id', $id);
$oDb->order_by('date_added');
$oDb->order_by('email', 'ASC');
return $oDb->get($this->tableEmail)->result();
} | php | {
"resource": ""
} |
q4378 | User.setCacheUser | train | public function setCacheUser($iUserId, $aData = [])
{
$this->unsetCacheUser($iUserId);
$oUser = $this->getById($iUserId);
if (empty($oUser)) {
return false;
}
$this->setCache(
$this->prepareCacheKey($this->tableIdColumn, $oUser->id, $aData),
$oUser
);
return true;
} | 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;
}
// --------------------------------------------------------------------------
$oEmailer = Factory::service('Emailer', 'nails/module-email');
$oEmail = new \stdClass();
$oEmail->type = 'verify_email_' . $oEmailRow->group_id;
$oEmail->to_id = $oEmailRow->user_id;
$oEmail->data = new \stdClass();
$oEmail->data->verifyUrl = site_url('email/verify/' . $oEmailRow->user_id . '/' . $oEmailRow->code);
if (!$oEmailer->send($oEmail, true)) {
// Failed to send using the group email, try using the generic email template
$oEmail->type = 'verify_email';
if (!$oEmailer->send($oEmail, true)) {
// Email failed to send, for now, do nothing.
$this->setError('The verification email failed to send.');
return false;
}
}
return true;
} | 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 = Factory::factory('DateTime');
$this->activeUser->last_update = $oDate->format('Y-m-d H:i:s');
// @todo: update the rest of the activeUser
}
$oDb->trans_commit();
return true;
} catch (\Exception $e) {
$this->setError('Failed to set primary email. ' . $e->getMessage());
$oDb->trans_rollback();
return false;
}
} | 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');
$oDb->set('failed_login_count', '`failed_login_count`+1', false);
$oDb->set('failed_login_expires', $oDate->format('Y-m-d H:i:s'));
return $this->update($iUserId);
} | php | {
"resource": ""
} |
q4382 | User.resetFailedLogin | train | public function resetFailedLogin($iUserId)
{
$oDb = Factory::service('Database');
$oDb->set('failed_login_count', 0);
$oDb->set('failed_login_expires', 'null', false);
return $this->update($iUserId);
} | 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');
$sEmail = $this->activeUser('email');
}
}
// --------------------------------------------------------------------------
// Generate a code to remember the user by and save it to the DB
$oEncrypt = Factory::service('Encrypt');
$sSalt = $oEncrypt->encode(sha1($iId . $sPassword . $sEmail . APP_PRIVATE_KEY . time()));
$oDb = Factory::service('Database');
$oDb->set('remember_code', $sSalt);
$oDb->where('id', $iId);
$oDb->update($this->table);
// --------------------------------------------------------------------------
// Set the cookie
set_cookie([
'name' => $this->sRememberCookie,
'value' => $sEmail . '|' . $sSalt,
'expire' => 1209600, // 2 weeks
]);
// --------------------------------------------------------------------------
// Update the flag
$this->bIsRemembered = true;
return true;
} | 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;
}
// --------------------------------------------------------------------------
// Store this entire user in memory
$this->setActiveUser($me);
// --------------------------------------------------------------------------
// Set the user's logged in flag
$this->bIsLoggedIn = true;
// --------------------------------------------------------------------------
// Update user's `last_seen` and `last_ip` properties
$oDb = Factory::service('Database');
$oInput = Factory::service('Input');
$oDb->set('last_seen', 'NOW()', false);
$oDb->set('last_ip', $oInput->ipAddress());
$oDb->where('id', $me->id);
$oDb->update($this->table);
return true;
} | 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, ['referral' => $sReferral]);
if ($oQuery->num_rows() == 0) {
break;
}
}
return $sReferral;
} | 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.');
return false;
}
// --------------------------------------------------------------------------
if ($checkDb) {
$oDb = Factory::service('Database');
$oDb->where('username', $username);
if (!empty($ignoreUserId)) {
$oDb->where('id !=', $ignoreUserId);
}
if ($oDb->count_all_results($this->table)) {
$this->setError('Username is already in use.');
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q4387 | User.describeFields | train | public function describeFields($sTable = null)
{
$aFields = parent::describeFields($sTable);
$aMetaFields = parent::describeFields($this->tableMeta);
unset($aMetaFields['user_id']);
return array_merge($aFields, $aMetaFields);
} | php | {
"resource": ""
} |
q4388 | ProvidesDateTimeInformation.dayOfWeekLocal | train | public function dayOfWeekLocal(string $locale = null) : int
{
$calendar = $this->createCalendar($locale);
return $calendar->get(\IntlCalendar::FIELD_DOW_LOCAL);
} | 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' => $attMeta['formIdent'],
'quickFormIdent' => $attMeta['quickFormIdent'],
'hasFaIcon' => !!$attMeta['faIcon'],
'faIcon' => $attMeta['faIcon'],
'label' => $label,
'val' => $attType,
'locked' => $attMeta['locked'],
'active' => ($i == 1)
];
}
return $out;
} | 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()])) {
$attachment->attachmentType = $attachableObjects[$attachment->objType()];
} else {
continue;
}
yield $attachment;
$GLOBALS['widget_template'] = '';
}
} | 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 */
$data = $this->mergePresets($data);
parent::setData($data);
$this->isMergingData = false;
if ($this->lang()) {
$this->translator()->setLocale($this->lang());
}
return $this;
} | php | {
"resource": ""
} |
q4392 | AttachmentWidget.setAttachmentOptions | train | public function setAttachmentOptions(array $settings)
{
$this->attachmentOptions = array_merge(
$this->defaultAttachmentOptions(),
$this->parseAttachmentOptions($settings)
);
return $this;
} | 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',
is_object($group) ? get_class($group) : gettype($group)
));
}
$this->group = $group;
return $this;
} | php | {
"resource": ""
} |
q4394 | AttachmentWidget.attachmentOptions | train | public function attachmentOptions()
{
if ($this->attachmentOptions === null) {
$this->attachmentOptions = $this->defaultAttachmentOptions();
}
return $this->attachmentOptions;
} | 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(),
'title' => $this->title(),
'lang' => $this->translator()->getLocale()
];
return json_encode($options, true);
} | php | {
"resource": ""
} |
q4396 | MultiCurrencyMoney.equals | train | public function equals(Money $money)
{
if (!$money instanceof MultiCurrencyMoney) {
return false;
}
return $money->currency == $this->currency && $money->getAmount() == $this->getAmount();
} | 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);
$rounder = $bank->getRounder();
$amount = bcmul($this->getAmount(), $rate, $rounder->getPrecision() + 1);
return $bank->createMoney($rounder->round($amount, $toCurrency), $toCurrency);
} | php | {
"resource": ""
} |
q4398 | Builder.build | train | public function build(array $strings)
{
$strings = array_unique($strings);
sort($strings);
if ($this->isEmpty($strings))
{
return '';
}
$strings = $this->splitStrings($strings);
$strings = $this->meta->replaceMeta($strings);
$strings = $this->runner->run($strings);
return $this->serializer->serializeStrings($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')),
'4' => sprintf('4 - %s', __d('me_cms', 'High')),
'5' => sprintf('5 - %s', __d('me_cms', 'Very high'))
]);
return parent::render($view, $layout);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.