_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q900
FileOutputPrinter.setOutputPath
train
public function setOutputPath($path) { if (!file_exists($path)) { if (!mkdir($path, 0755, true)) { throw new BadOutputPathException( sprintf( 'Output path %s does not exist and could not be created!', $path ), $path ); } } else { if (!is_dir($path)) { throw new BadOutputPathException( sprintf( 'The argument to `output` is expected to the a directory, but got %s!', $path ), $path ); } } $this->path = $path; }
php
{ "resource": "" }
q901
FoxyStripeController.processFoxyRequest
train
protected function processFoxyRequest(HTTPRequest $request) { $encryptedData = $request->postVar('FoxyData') ? urldecode($request->postVar('FoxyData')) : urldecode($request->postVar('FoxySubscriptionData')); $decryptedData = $this->decryptFeedData($encryptedData); $this->parseFeedData($encryptedData, $decryptedData); $this->extend('addIntegrations', $encryptedData); }
php
{ "resource": "" }
q902
FoxyStripeController.parseFeedData
train
private function parseFeedData($encryptedData, $decryptedData) { $orders = new \SimpleXMLElement($decryptedData); // loop over each transaction to find FoxyCart Order ID foreach ($orders->transactions->transaction as $transaction) { $this->processTransaction($transaction, $encryptedData); } }
php
{ "resource": "" }
q903
FoxyStripeController.sso
train
public function sso() { // GET variables from FoxyCart Request $fcsid = $this->request->getVar('fcsid'); $timestampNew = strtotime('+30 days'); // get current member if logged in. If not, create a 'fake' user with Customer_ID = 0 // fake user will redirect to FC checkout, ask customer to log in // to do: consider a login/registration form here if not logged in if (!$Member = Security::getCurrentUser()) { $Member = new Member(); $Member->Customer_ID = 0; } $auth_token = sha1($Member->Customer_ID . '|' . $timestampNew . '|' . FoxyCart::getStoreKey()); $config = FoxyStripeSetting::current_foxystripe_setting(); if ($config->CustomSSL) { $link = FoxyCart::getFoxyCartStoreName(); } else { $link = FoxyCart::getFoxyCartStoreName() . '.foxycart.com'; } $params = [ 'fc_auth_token' => $auth_token, 'fcsid' => $fcsid, 'fc_customer_id' => $Member->Customer_ID, 'timestamp' => $timestampNew, ]; $httpQuery = http_build_query($params); $this->redirect("https://{$link}/checkout?$httpQuery"); }
php
{ "resource": "" }
q904
Cluster.terminate
train
private static function terminate(): Promise { if (self::$onClose === null) { return Promise\any([]); } if (self::$signalWatchers) { foreach (self::$signalWatchers as $watcher) { Loop::cancel($watcher); } } $onClose = self::$onClose; self::$onClose = null; $promises = []; foreach ($onClose as $callable) { $promises[] = call($callable); } return Promise\any($promises); }
php
{ "resource": "" }
q905
Cluster.onReceivedMessage
train
private static function onReceivedMessage(string $event, $data) { foreach (self::$onMessage[$event] ?? [] as $callback) { asyncCall($callback, $data); } }
php
{ "resource": "" }
q906
Cluster.createLogHandler
train
public static function createLogHandler(string $logLevel = LogLevel::DEBUG, bool $bubble = false): HandlerInterface { if (!self::isWorker()) { throw new \Error(__FUNCTION__ . " should only be called when running as a worker. " . "Create your own log handler when not running as part of a cluster"); } return new Internal\IpcLogHandler(self::$client, $logLevel, $bubble); }
php
{ "resource": "" }
q907
Util.prepareOptions
train
public static function prepareOptions($value, $defaults = []) { if (is_string($value)) { $value = json_decode($value, true); } return is_array($value) ? array_merge($defaults, $value) : $defaults; }
php
{ "resource": "" }
q908
EzRSSAggregator.process
train
public function process(DOMElement $node, Item $item) { foreach ($this->keys as $key) { $item->setExtra($key, $this->getValue($node, $key)); } }
php
{ "resource": "" }
q909
CustomerExtension.onAfterWrite
train
public function onAfterWrite() { parent::onAfterWrite(); if ($this->owner->PasswordEncryption != Security::config()->get('password_encryption_algorithm')) { $this->resetPasswordEncryption(); } }
php
{ "resource": "" }
q910
CustomerExtension.setDataFromTransaction
train
public function setDataFromTransaction($transaction) { foreach ($this->owner->config()->get('customer_map') as $type => $map) { switch ($type) { case 'int': foreach ($map as $foxyField => $foxyStripeField) { if ((int)$transaction->{$foxyField}) { $this->owner->{$foxyStripeField} = (int)$transaction->{$foxyField}; } } break; case 'string': foreach ($map as $foxyField => $foxyStripeField) { if ((string)$transaction->{$foxyField}) { $this->owner->{$foxyStripeField} = (string)$transaction->{$foxyField}; } } break; } } $this->owner->PasswordEncryption = 'none'; return $this->owner; }
php
{ "resource": "" }
q911
CustomerExtension.resetPasswordEncryption
train
private function resetPasswordEncryption() { $defaultEncryption = Security::config()->get('password_encryption_algorithm'); if ($this->owner->PasswordEncryption != $defaultEncryption) { DB::prepared_query( 'UPDATE "Member" SET "PasswordEncryption" = ? WHERE ID = ?', [$defaultEncryption, $this->owner->ID] ); } }
php
{ "resource": "" }
q912
ExtraFormBuilder.buildConstraint
train
protected function buildConstraint(array $constraint) { $extraFormConstraint = $this ->constraintRegistry ->getConstraint($constraint['extra_form_constraint']) ; $className = $extraFormConstraint->getClassName(); $options = isset($constraint['options']) ? $constraint['options'] : array(); return new $className($options); }
php
{ "resource": "" }
q913
ExtraFormBuilder.buildFormOptions
train
protected function buildFormOptions($name, array $field, $data = null) { // Allow sub options structure (collection case) if (isset($field['options']['constraints'])) { $field['options']['options'] = $this->buildFormOptions('', $field['options']); } $constraints = array(); foreach ($field['constraints'] as $constraint) { $constraints[] = $this->buildConstraint($constraint); } $field['options']['constraints'] = $constraints; if (null !== $data && isset($data[$name])) { $field['options']['data'] = $data[$name]; } return $field['options']; }
php
{ "resource": "" }
q914
DonationProductController.updatevalue
train
public function updatevalue(\SilverStripe\Control\HTTPRequest $request) { if ($request->getVar('Price') && FoxyStripeSetting::current_foxystripe_setting()->CartValidation) { $vars = $request->getVars(); $signedPrice = FoxyCart_Helper::fc_hash_value($this->Code, 'price', $vars['Price'], 'name', false); $json = json_encode(['Price' => $signedPrice]); $this->response->setBody($json); $this->response->addHeader('Content-Type', 'application/json'); return $this->response; } return 'false'; }
php
{ "resource": "" }
q915
FastFeed.addFeed
train
public function addFeed($channel, $feed) { if (!filter_var($feed, FILTER_VALIDATE_URL)) { throw new LogicException('You tried to add a invalid url.'); } $this->feeds[$channel][] = $feed; }
php
{ "resource": "" }
q916
FastFeed.getFeed
train
public function getFeed($channel) { if (!isset($this->feeds[$channel])) { throw new LogicException('You tried to get a not existent channel'); } return $this->feeds[$channel]; }
php
{ "resource": "" }
q917
FastFeed.setFeed
train
public function setFeed($channel, $feed) { if (!is_string($channel)) { throw new LogicException('You tried to add a invalid channel.'); } $this->feeds[$channel] = array(); $this->addFeed($channel, $feed); }
php
{ "resource": "" }
q918
FastFeed.get
train
protected function get($url) { $request = $this->http->get( $url, array('User-Agent' => self::USER_AGENT.' v.'.self::VERSION) ); $response = $request->send(); if (!$response->isSuccessful()) { $this->log('fail with '.$response->getStatusCode().' http code in url "'.$url.'" '); return; } $this->logger->log(LogLevel::INFO, 'retrieved url "'.$url.'" '); return $response->getBody(); }
php
{ "resource": "" }
q919
Permutation.getPermutations
train
public function getPermutations(array $sourceDataSet, $subsetSize = null) { $combinationMap = $this->_combination->getCombinations($sourceDataSet, $subsetSize); $permutationsMap = []; foreach ($combinationMap as $combination) { $permutationsMap = array_merge( $permutationsMap, $this->_findPermutations($combination) ); } return $permutationsMap; }
php
{ "resource": "" }
q920
Permutation._findPermutations
train
private function _findPermutations($combination) { // If the combination only has 1 element, then the permutation is the same as the combination if (count($combination) <= 1) { return [$combination]; } $permutationList = []; $startKey = $this->_processSubPermutations($combination, $permutationList); // Now that the first element has been rotated to the end, we calculate permutations until // we reach the first element which is now at the end of the combiatnion. $key = key($combination); while ($key != $startKey) { $this->_processSubPermutations($combination, $permutationList); $key = key($combination); } return $permutationList; }
php
{ "resource": "" }
q921
ContentElement.generate
train
public function generate() { // Get the content element object $this->objElement = \ElementsModel::findPublishedByAlias($this->type); if ($this->objElement === null) { return; } // Register the custom template if (!array_key_exists($this->objElement->template, TemplateLoader::getFiles())) { TemplateLoader::addFile($this->objElement->template, $this->objElement->getRelated('pid')->templates); } if (TL_MODE == 'BE' && $this->objElement->backendTpl) { $this->strTemplate = $this->objElement->backendTpl; } else { $this->strTemplate = $this->objElement->template; } if (TL_MODE == 'FE' && !BE_USER_LOGGED_IN && ($this->invisible || ($this->start != '' && $this->start > time()) || ($this->stop != '' && $this->stop < time()))) { return ''; } $this->Template = new Template($this->strTemplate); // Deliver some general element data $this->Template->setData( array ( 'id' => $this->id, 'pid' => $this->pid, 'ptable' => $this->ptable, 'element' => $this->type, 'tstamp' => $this->tstamp, 'start' => $this->start, 'stop' => $this->stop, 'protected' => $this->protected, 'inColumn' => $this->strColumn ) ); // compile pattern to prepare values $this->compile(); return $this->Template->parse(); }
php
{ "resource": "" }
q922
ContentElement.compile
train
protected function compile() { // Get the pattern model collection $colPattern = \PatternModel::findVisibleByPid($this->objElement->id); if ($colPattern === null) { return; } // Get correct content element id (included content element) see #37 $intPid = ($this->origId) ? $this->origId : $this->id; // Get the data $colData = \DataModel::findByPid($intPid); if ($colData !== null) { foreach ($colData as $objData) { $arrData[$objData->pattern] = $objData; } } // Prepare values for every pattern foreach($colPattern as $objPattern) { if (!Pattern::hasOutput($objPattern->type)) { continue; } $strClass = Pattern::findClass($objPattern->type); if (!class_exists($strClass)) { System::log('Pattern element class "'.$strClass.'" (pattern element "'.$objPattern->type.'") does not exist', __METHOD__, TL_ERROR); } else { $objPatternClass = new $strClass($objPattern); $objPatternClass->pid = $intPid; $objPatternClass->Template = $this->Template; $objPatternClass->data = $arrData[$objPattern->alias]; $objPatternClass->compile(); } } }
php
{ "resource": "" }
q923
RequestHandler.setPath
train
protected static function setPath($path = null) { if (!static::$pathStack) { $requestURI = parse_url($_SERVER['REQUEST_URI']); static::$pathStack = static::$requestPath = explode('/', ltrim($requestURI['path'], '/')); } static::$_path = isset($path) ? $path : static::$pathStack; }
php
{ "resource": "" }
q924
IbanToArrayTransformer.reverseTransform
train
public function reverseTransform($out) { if (null !== $out && is_array($out)) { return strtoupper( sprintf( '%s%s%s%s%s%s%s%s', $out['c1'], $out['c2'], $out['c3'], $out['c4'], $out['c5'], $out['c6'], $out['c7'], $out['c8'] ) ); } return $out; }
php
{ "resource": "" }
q925
tl_elements.setDefaultType
train
public function setDefaultType ($value, DataContainer $dc) { $db = Database::getInstance(); if ($value) { // There can only be one default element $db->prepare("UPDATE tl_elements SET defaultType='' WHERE NOT id=? AND pid=?") ->execute($dc->activeRecord->id, $dc->activeRecord->pid); } return $value; }
php
{ "resource": "" }
q926
tl_elements.checkTitle
train
public function checkTitle ($value, DataContainer $dc) { $db = Database::getInstance(); $objTitle = $db->prepare("SELECT id FROM tl_elements WHERE NOT id=? AND pid=? AND title=?") ->execute($dc->activeRecord->id, $dc->activeRecord->pid, $value); if ($objTitle->numRows > 0) { throw new Exception(sprintf($GLOBALS['TL_LANG']['ERR']['aliasExists'], $value)); } return $value; }
php
{ "resource": "" }
q927
tl_elements.generateAlias
train
public function generateAlias (DataContainer $dc) { $db = Database::getInstance(); // Generate alias from theme name and title $alias = \StringUtil::generateAlias(\ThemeModel::findById($dc->activeRecord->pid)->name . '-' . $dc->activeRecord->title); if ($alias != $dc->activeRecord->alias) { // Save alias to database $db->prepare("UPDATE tl_elements SET alias=? WHERE id=?") ->execute($alias, $dc->activeRecord->id); if ($dc->activeRecord->alias) { // Also change the type (=alias) in tl_content table $db->prepare("UPDATE tl_content SET type=? WHERE type=?") ->execute($alias, $dc->activeRecord->alias); } } }
php
{ "resource": "" }
q928
tl_elements.getContentElementTemplates
train
public function getContentElementTemplates(DataContainer $dc) { $arrTemplates = array(); // Get the default templates foreach (\TemplateLoader::getPrefixedFiles('ce_') as $strTemplate) { $arrTemplates[$strTemplate][] = 'root'; } $arrCustomized = glob(TL_ROOT . '/templates/ce_*'); // Add the customized templates if (is_array($arrCustomized)) { foreach ($arrCustomized as $strFile) { $strTemplate = basename($strFile, strrchr($strFile, '.')); $arrTemplates[$strTemplate][] = $GLOBALS['TL_LANG']['MSC']['global']; } } // Add the customized theme templates $theme = \ThemeModel::findById($dc->activeRecord->pid); $arrCustomized = glob(TL_ROOT . '/' . $theme->templates . '/' . 'ce_*'); if (is_array($arrCustomized)) { foreach ($arrCustomized as $strFile) { $strTemplate = basename($strFile, strrchr($strFile, '.')); $arrTemplates[$strTemplate][] = $theme->name; } } // Show the template sources foreach ($arrTemplates as $k=>$v) { $v = array_filter($v, function($a) { return $a != 'root'; }); if (empty($v)) { $arrTemplates[$k] = $k; } else { $arrTemplates[$k] = $k . ' (' . implode(', ', $v) . ')'; } } // Sort the template names ksort($arrTemplates); return $arrTemplates; }
php
{ "resource": "" }
q929
tl_elements.editButton
train
public function editButton($row, $href, $label, $title, $icon, $attributes) { switch ($row['type']) { case 'group': return \Image::getHtml(str_replace('.', '_.', $icon), $label) . ' '; case 'element': return '<a href="'.$this->addToUrl($href.'&amp;id='.$row['id']).'" title="'.\StringUtil::specialchars($title).'"'.$attributes.'>'.\Image::getHtml($icon, $label).'</a> '; } }
php
{ "resource": "" }
q930
ConfiguredTypeRepository.findByTags
train
public function findByTags(array $tags) { $qb = $this->createQueryBuilder('c'); foreach ($tags as $key => $tag) { $operator = substr($tag, 0, 1); if ($operator === '+' || $operator === '-') { $tag = substr($tag, 1); } $literalExpr = $qb->expr()->literal('%'.$tag.'%'); if ($operator === '-') { $qb->andWhere($qb->expr()->notLike('c.tags', $literalExpr)); } elseif ($operator === '+') { $qb->andWhere($qb->expr()->like('c.tags', $literalExpr)); } elseif ($key === 0) { $qb->where($qb->expr()->like('c.tags', $literalExpr)); } else { $qb->orWhere($qb->expr()->like('c.tags', $literalExpr)); } } return $qb->getQuery()->getResult(); }
php
{ "resource": "" }
q931
ConfiguredTypeRepository.getAllTags
train
public function getAllTags() { $qb = $this->createQueryBuilder('c'); $qb ->select('c.tags') ->where($qb->expr()->isNotNull('c.tags')) ->distinct() ; $tagStrings = array_map('current', $qb->getQuery()->getScalarResult()); $distinctTags = array(); foreach ($tagStrings as $tagString) { foreach (explode(',', $tagString) as $tag) { if (!in_array($tag, $distinctTags)) { array_push($distinctTags, $tag); } } } return $distinctTags; }
php
{ "resource": "" }
q932
UserEndpoint.find
train
public function find($username) { $parameters['username'] = $username; return $this->apiClient->callEndpoint(self::ENDPOINT, $parameters); }
php
{ "resource": "" }
q933
UserEndpoint.update
train
public function update($username, $parameters = array()) { $parameters['username'] = $username; return $this->apiClient->callEndpoint( self::ENDPOINT, $parameters, null, HttpMethod::REQUEST_PUT ); }
php
{ "resource": "" }
q934
UserEndpoint.add
train
public function add($username, $parameters = array()) { $parameters['username'] = $username; return $this->apiClient->callEndpoint( self::ENDPOINT, $parameters, null, HttpMethod::REQUEST_POST ); }
php
{ "resource": "" }
q935
UserEndpoint.findAvatars
train
public function findAvatars($username) { $parameters['username'] = $username; return $this->apiClient->callEndpoint(sprintf('%s/avatars', self::ENDPOINT), $parameters); }
php
{ "resource": "" }
q936
UserEndpoint.updatePassword
train
public function updatePassword($username, $password) { $parameters['username'] = $username; $parameters['password'] = $password; return $this->apiClient->callEndpoint( sprintf('%s/avatars', self::ENDPOINT), $parameters, null, HttpMethod::REQUEST_PUT ); }
php
{ "resource": "" }
q937
UserEndpoint.picker
train
public function picker($query, $maxResults = null, $showAvatar = null, $exclude = null) { $parameters = array( 'query' => $query, 'maxResults' => $maxResults, 'showAvatar' => $showAvatar, 'exclude' => $exclude ); return $this->apiClient->callEndpoint(sprintf('%s/picker', self::ENDPOINT), $parameters); }
php
{ "resource": "" }
q938
UserEndpoint.search
train
public function search($username, $startAt = null, $maxResults = null, $includeActive = null, $includeInactive = null) { $parameters = array( 'username' => $username, 'startAt' => $startAt, 'maxResults' => $maxResults, 'includeActive' => $includeActive, 'includeInactive' => $includeInactive ); return $this->apiClient->callEndpoint(sprintf('%s/search', self::ENDPOINT), $parameters); }
php
{ "resource": "" }
q939
Versioning.getRevisionRecords
train
public static function getRevisionRecords($options = []) { $options = Util::prepareOptions($options, [ 'indexField' => false, 'conditions' => [], 'order' => false, 'limit' => false, 'offset' => 0, ]); $query = 'SELECT * FROM `%s` WHERE (%s)'; $params = [ static::getHistoryTable(), count($options['conditions']) ? join(') AND (', static::_mapConditions($options['conditions'])) : 1, ]; if ($options['order']) { $query .= ' ORDER BY ' . join(',', static::_mapFieldOrder($options['order'])); } if ($options['limit']) { $query .= sprintf(' LIMIT %u,%u', $options['offset'], $options['limit']); } if ($options['indexField']) { return DB::table(static::_cn($options['indexField']), $query, $params); } else { return DB::allRecords($query, $params); } }
php
{ "resource": "" }
q940
Versioning.beforeVersionedSave
train
public function beforeVersionedSave() { $this->wasDirty = false; if ($this->isDirty && static::$createRevisionOnSave) { // update creation time $this->Created = time(); $this->wasDirty = true; } }
php
{ "resource": "" }
q941
Versioning.afterVersionedSave
train
public function afterVersionedSave() { if ($this->wasDirty && static::$createRevisionOnSave) { // save a copy to history table $recordValues = $this->_prepareRecordValues(); $set = static::_mapValuesToSet($recordValues); DB::nonQuery( 'INSERT INTO `%s` SET %s', [ static::getHistoryTable(), join(',', $set), ] ); } }
php
{ "resource": "" }
q942
AuthenticationEndpoint.authentication
train
public function authentication($username, $password) { $endpoint = sprintf('authentication?username=%s', urlencode($username)); $parameters['value'] = $password; return $this->apiClient->callEndpoint( $endpoint, $parameters, null, HttpMethod::REQUEST_POST ); }
php
{ "resource": "" }
q943
ConfiguredType.getExtraFormConstraints
train
public function getExtraFormConstraints() { if (null === $this->extraFormType) { return null; } $configurationArray = json_decode($this->configuration, true); return $configurationArray['extra_form_constraints']; }
php
{ "resource": "" }
q944
CaptchaTheme._theme
train
protected function _theme($theme_name = NULL, $options = array()) { if ( count($options) > 0 ) { // Avoid invalid options passed via array foreach ($options as $opt => $value) { if ( !array_key_exists($opt, $this->_recaptchaOptions) ) { unset($options[$opt]); } } } // Avoid empty values foreach ($this->_recaptchaOptions as $key => $value) { if ( NULL === $value || $value === 0 ) { unset($this->_recaptchaOptions[$key]); } } $this->_recaptchaOptions = array_merge($this->_recaptchaOptions, $options); if ( NULL !== $theme_name ) { $this->_recaptchaOptions['theme'] = $theme_name; } // Skip to default reCAPTCHA theme if there is no options if ( count($this->_recaptchaOptions) == 0 ) { return; } // Whether lang option value is not built-in try to set it from a translation file if ( isset($this->_recaptchaOptions['lang']) && !in_array($this->_recaptchaOptions['lang'], $this->_builtInlang) && !isset($this->_recaptchaOptions['custom_translations']) ) { $this->setTranslation($this->_recaptchaOptions['lang']); } // Whether theme empty set default theme to default for FALLBACK if ( !isset($this->_recaptchaOptions['theme']) && count($this->_recaptchaOptions) > 0 ) { $this->_recaptchaOptions['theme'] = 'red'; } // Skip to default reCAPTCHA theme if it's set to 'red' and there is no options at all if ( $this->_recaptchaOptions['theme'] === 'red' && count($this->_recaptchaOptions) == 1 ) { return; } // Whether the theme name is Standard_Themes or not if ( in_array($this->_recaptchaOptions['theme'], $this->_standardThemes) ) { unset($this->_recaptchaOptions['custom_theme_widget']); $js_options = json_encode($this->_recaptchaOptions); return sprintf($this->_optionsWrapper, $js_options); } elseif ( $this->_recaptchaOptions['theme'] === 'custom' ) { // Custom theme MUST have an option [custom_theme_widget: ID_some_widget_name] set for recaptcha // If this option is not set, we make it. if ( !isset($this->_recaptchaOptions['custom_theme_widget']) ) { $this->_recaptchaOptions['custom_theme_widget'] = 'recaptcha_widget'; } $custom_template = $this->custom_theme($this->_recaptchaOptions['custom_theme_widget']); $js_options = json_encode($this->_recaptchaOptions); return sprintf($this->_optionsWrapper, $js_options) . $custom_template; } // FALLBACK to red one default theme return; }
php
{ "resource": "" }
q945
CaptchaTheme.i18n
train
protected function i18n($key = NULL, $path = NULL) { static $RECAPTCHA_LANG; if ( $RECAPTCHA_LANG ) { return isset($key) ? $RECAPTCHA_LANG[$key] : $RECAPTCHA_LANG; } if ( !isset($this->_recaptchaOptions['lang']) ) { $language = $this->clientLang(); } else { $language = $this->_recaptchaOptions['lang']; } $RECAPTCHA_LANG = array( 'instructions_visual' => 'Enter the words above:', 'instructions_audio' => 'Type what you hear:', 'play_again' => 'Play sound again', 'cant_hear_this' => 'Download sound as MP3', 'visual_challenge' => 'Get an image CAPTCHA', 'audio_challenge' => 'Get an audio CAPTCHA', 'refresh_btn' => 'Get another CAPTCHA', 'help_btn' => 'Help', 'incorrect_try_again' => 'Incorrect, please try again.' ); // default: path/to/vendor/lib/ReCaptcha/I18n/recaptcha.lang.[langcode].php $path = ( NULL === $path ) ? __DIR__ . DIRECTORY_SEPARATOR . 'I18n' : $path; $language_file = rtrim($path, '/') . DIRECTORY_SEPARATOR . 'recaptcha.lang.' . $language . '.php'; if ( file_exists( $language_file ) ) { include_once $language_file; } return isset($key) ? $RECAPTCHA_LANG[$key] : $RECAPTCHA_LANG; }
php
{ "resource": "" }
q946
CaptchaTheme.clientLang
train
public function clientLang() { if ( isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ) { $language = explode(',', preg_replace('/(;\s?q=[0-9\.]+)|\s/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])))); return strtolower($language[0]); } return; }
php
{ "resource": "" }
q947
ReCaptchaType.isEnabled
train
private function isEnabled() { if (!$this->enabled) { return false; } if ($this->authorizationChecker) { foreach ($this->trustedRoles as $trustedRole) { if ($this->authorizationChecker->isGranted($trustedRole)) { return false; } } } return true; }
php
{ "resource": "" }
q948
ActiveRecord.init
train
public static function init() { $className = get_called_class(); if (empty(static::$_fieldsDefined[$className])) { static::_defineFields(); static::_initFields(); static::$_fieldsDefined[$className] = true; } if (empty(static::$_relationshipsDefined[$className]) && static::isRelational()) { static::_defineRelationships(); static::_initRelationships(); static::$_relationshipsDefined[$className] = true; } if (empty(static::$_eventsDefined[$className])) { static::_defineEvents(); static::$_eventsDefined[$className] = true; } }
php
{ "resource": "" }
q949
ActiveRecord.setValue
train
public function setValue($name, $value) { // handle field if (static::fieldExists($name)) { $this->_setFieldValue($name, $value); } // undefined else { return false; } }
php
{ "resource": "" }
q950
ActiveRecord.create
train
public static function create($values = [], $save = false) { $className = get_called_class(); // create class $ActiveRecord = new $className(); $ActiveRecord->setFields($values); if ($save) { $ActiveRecord->save(); } return $ActiveRecord; }
php
{ "resource": "" }
q951
ActiveRecord.changeClass
train
public function changeClass($className = false, $fieldValues = false) { if (!$className) { return $this; } $this->_record[static::_cn('Class')] = $className; $ActiveRecord = new $className($this->_record, true, $this->isPhantom); if ($fieldValues) { $ActiveRecord->setFields($fieldValues); } if (!$this->isPhantom) { $ActiveRecord->save(); } return $ActiveRecord; }
php
{ "resource": "" }
q952
ActiveRecord.setFields
train
public function setFields($values) { foreach ($values as $field => $value) { $this->_setFieldValue($field, $value); } }
php
{ "resource": "" }
q953
ActiveRecord.getData
train
public function getData() { $data = []; foreach (static::$_classFields[get_called_class()] as $field => $options) { $data[$field] = $this->_getFieldValue($field); } if ($this->validationErrors) { $data['validationErrors'] = $this->validationErrors; } return $data; }
php
{ "resource": "" }
q954
ActiveRecord.save
train
public function save($deep = true) { // run before save $this->beforeSave(); if (static::isVersioned()) { $this->beforeVersionedSave(); } // set created if (static::fieldExists('Created') && (!$this->Created || ($this->Created == 'CURRENT_TIMESTAMP'))) { $this->Created = time(); } // validate if (!$this->validate($deep)) { throw new Exception('Cannot save invalid record'); } $this->clearCaches(); if ($this->isDirty) { // prepare record values $recordValues = $this->_prepareRecordValues(); // transform record to set array $set = static::_mapValuesToSet($recordValues); // create new or update existing if ($this->_isPhantom) { DB::nonQuery( 'INSERT INTO `%s` SET %s', [ static::$tableName, join(',', $set), ], [static::class,'handleError'] ); $this->_record[static::$primaryKey ? static::$primaryKey : 'ID'] = DB::insertID(); $this->_isPhantom = false; $this->_isNew = true; } elseif (count($set)) { DB::nonQuery( 'UPDATE `%s` SET %s WHERE `%s` = %u', [ static::$tableName, join(',', $set), static::_cn(static::$primaryKey ? static::$primaryKey : 'ID'), $this->getPrimaryKeyValue(), ], [static::class,'handleError'] ); $this->_isUpdated = true; } // update state $this->_isDirty = false; if (static::isVersioned()) { $this->afterVersionedSave(); } } $this->afterSave(); }
php
{ "resource": "" }
q955
ActiveRecord.destroy
train
public function destroy() { if (static::isVersioned()) { if (static::$createRevisionOnDestroy) { // save a copy to history table if ($this->fieldExists('Created')) { $this->Created = time(); } $recordValues = $this->_prepareRecordValues(); $set = static::_mapValuesToSet($recordValues); DB::nonQuery( 'INSERT INTO `%s` SET %s', [ static::getHistoryTable(), join(',', $set), ] ); } } return static::delete($this->getPrimaryKeyValue()); }
php
{ "resource": "" }
q956
ActiveRecord.delete
train
public static function delete($id) { DB::nonQuery('DELETE FROM `%s` WHERE `%s` = %u', [ static::$tableName, static::_cn(static::$primaryKey ? static::$primaryKey : 'ID'), $id, ], [static::class,'handleError']); return DB::affectedRows() > 0; }
php
{ "resource": "" }
q957
ActiveRecord.getByID
train
public static function getByID($id) { $record = static::getRecordByField(static::$primaryKey ? static::$primaryKey : 'ID', $id, true); return static::instantiateRecord($record); }
php
{ "resource": "" }
q958
ActiveRecord.getByField
train
public static function getByField($field, $value, $cacheIndex = false) { $record = static::getRecordByField($field, $value, $cacheIndex); return static::instantiateRecord($record); }
php
{ "resource": "" }
q959
ActiveRecord.getRecordByField
train
public static function getRecordByField($field, $value, $cacheIndex = false) { $query = 'SELECT * FROM `%s` WHERE `%s` = "%s" LIMIT 1'; $params = [ static::$tableName, static::_cn($field), DB::escape($value), ]; if ($cacheIndex) { $key = sprintf('%s/%s:%s', static::$tableName, $field, $value); return DB::oneRecordCached($key, $query, $params, [static::class,'handleError']); } else { return DB::oneRecord($query, $params, [static::class,'handleError']); } }
php
{ "resource": "" }
q960
ActiveRecord.getRecordByWhere
train
public static function getRecordByWhere($conditions, $options = []) { if (!is_array($conditions)) { $conditions = [$conditions]; } $options = Util::prepareOptions($options, [ 'order' => false, ]); // initialize conditions and order $conditions = static::_mapConditions($conditions); $order = $options['order'] ? static::_mapFieldOrder($options['order']) : []; return DB::oneRecord( 'SELECT * FROM `%s` WHERE (%s) %s LIMIT 1', [ static::$tableName, join(') AND (', $conditions), $order ? 'ORDER BY '.join(',', $order) : '', ], [static::class,'handleError'] ); }
php
{ "resource": "" }
q961
ActiveRecord.getAllByContextObject
train
public static function getAllByContextObject(ActiveRecord $Record, $options = []) { return static::getAllByContext($Record::$rootClass, $Record->getPrimaryKeyValue(), $options); }
php
{ "resource": "" }
q962
ActiveRecord.buildExtraColumns
train
public static function buildExtraColumns($columns) { if (!empty($columns)) { if (is_array($columns)) { foreach ($columns as $key => $value) { return ', '.$value.' AS '.$key; } } else { return ', ' . $columns; } } }
php
{ "resource": "" }
q963
ActiveRecord.buildHaving
train
public static function buildHaving($having) { if (!empty($having)) { return ' HAVING (' . (is_array($having) ? join(') AND (', static::_mapConditions($having)) : $having) . ')'; } }
php
{ "resource": "" }
q964
ActiveRecord.getAllRecordsByWhere
train
public static function getAllRecordsByWhere($conditions = [], $options = []) { $className = get_called_class(); $options = Util::prepareOptions($options, [ 'indexField' => false, 'order' => false, 'limit' => false, 'offset' => 0, 'calcFoundRows' => !empty($options['limit']), 'extraColumns' => false, 'having' => false, ]); // initialize conditions if ($conditions) { if (is_string($conditions)) { $conditions = [$conditions]; } $conditions = static::_mapConditions($conditions); } // build query $query = 'SELECT %1$s `%3$s`.*'; $query .= static::buildExtraColumns($options['extraColumns']); $query .= ' FROM `%2$s` AS `%3$s`'; $query .= ' WHERE (%4$s)'; $query .= static::buildHaving($options['having']); $params = [ $options['calcFoundRows'] ? 'SQL_CALC_FOUND_ROWS' : '', static::$tableName, $className::$rootClass, $conditions ? join(') AND (', $conditions) : '1', ]; if ($options['order']) { $query .= ' ORDER BY ' . join(',', static::_mapFieldOrder($options['order'])); } if ($options['limit']) { $query .= sprintf(' LIMIT %u,%u', $options['offset'], $options['limit']); } if ($options['indexField']) { return DB::table(static::_cn($options['indexField']), $query, $params, null, [static::class,'handleError']); } else { return DB::allRecords($query, $params, [static::class,'handleError']); } }
php
{ "resource": "" }
q965
ActiveRecord.getAllRecords
train
public static function getAllRecords($options = []) { $options = Util::prepareOptions($options, [ 'indexField' => false, 'order' => false, 'limit' => false, 'calcFoundRows' => false, 'offset' => 0, ]); $query = 'SELECT '.($options['calcFoundRows'] ? 'SQL_CALC_FOUND_ROWS' : '').'* FROM `%s`'; $params = [ static::$tableName, ]; if ($options['order']) { $query .= ' ORDER BY ' . join(',', static::_mapFieldOrder($options['order'])); } if ($options['limit']) { $query .= sprintf(' LIMIT %u,%u', $options['offset'], $options['limit']); } if ($options['indexField']) { return DB::table(static::_cn($options['indexField']), $query, $params, null, [static::class,'handleError']); } else { return DB::allRecords($query, $params, [static::class,'handleError']); } }
php
{ "resource": "" }
q966
ActiveRecord.instantiateRecords
train
public static function instantiateRecords($records) { foreach ($records as &$record) { $className = static::_getRecordClass($record); $record = new $className($record); } return $records; }
php
{ "resource": "" }
q967
ActiveRecord.getFieldOptions
train
public static function getFieldOptions($field, $optionKey = false) { if ($optionKey) { return static::$_classFields[get_called_class()][$field][$optionKey]; } else { return static::$_classFields[get_called_class()][$field]; } }
php
{ "resource": "" }
q968
ActiveRecord.getColumnName
train
public static function getColumnName($field) { static::init(); if (!static::fieldExists($field)) { throw new Exception('getColumnName called on nonexisting column: ' . get_called_class().'->'.$field); } return static::$_classFields[get_called_class()][$field]['columnName']; }
php
{ "resource": "" }
q969
ActiveRecord.getValidationError
train
public function getValidationError($field) { // break apart path $crumbs = explode('.', $field); // resolve path recursively $cur = &$this->_validationErrors; while ($crumb = array_shift($crumbs)) { if (array_key_exists($crumb, $cur)) { $cur = &$cur[$crumb]; } else { return null; } } // return current value return $cur; }
php
{ "resource": "" }
q970
ActiveRecord._getRecordClass
train
protected static function _getRecordClass($record) { $static = get_called_class(); if (!static::fieldExists('Class')) { return $static; } $columnName = static::_cn('Class'); if (!empty($record[$columnName]) && is_subclass_of($record[$columnName], $static)) { return $record[$columnName]; } else { return $static; } }
php
{ "resource": "" }
q971
ActiveRecord._getFieldValue
train
protected function _getFieldValue($field, $useDefault = true) { $fieldOptions = static::$_classFields[get_called_class()][$field]; if (isset($this->_record[$fieldOptions['columnName']])) { $value = $this->_record[$fieldOptions['columnName']]; // apply type-dependent transformations switch ($fieldOptions['type']) { case 'password': { return $value; } case 'timestamp': { if (!isset($this->_convertedValues[$field])) { if ($value && $value != '0000-00-00 00:00:00') { $this->_convertedValues[$field] = strtotime($value); } else { $this->_convertedValues[$field] = null; } } return $this->_convertedValues[$field]; } case 'serialized': { if (!isset($this->_convertedValues[$field])) { $this->_convertedValues[$field] = is_string($value) ? unserialize($value) : $value; } return $this->_convertedValues[$field]; } case 'set': case 'list': { if (!isset($this->_convertedValues[$field])) { $delim = empty($fieldOptions['delimiter']) ? ',' : $fieldOptions['delimiter']; $this->_convertedValues[$field] = array_filter(preg_split('/\s*'.$delim.'\s*/', $value)); } return $this->_convertedValues[$field]; } case 'boolean': { if (!isset($this->_convertedValues[$field])) { $this->_convertedValues[$field] = (boolean)$value; } return $this->_convertedValues[$field]; } default: { return $value; } } } elseif ($useDefault && isset($fieldOptions['default'])) { // return default return $fieldOptions['default']; } else { switch ($fieldOptions['type']) { case 'set': case 'list': { return []; } default: { return null; } } } }
php
{ "resource": "" }
q972
ActiveRecord._setFieldValue
train
protected function _setFieldValue($field, $value) { // ignore setting versioning fields if (static::isVersioned()) { if (array_key_exists($field, static::$versioningFields)) { return false; } } if (!static::fieldExists($field)) { return false; } $fieldOptions = static::$_classFields[get_called_class()][$field]; // no overriding autoincrements if ($fieldOptions['autoincrement']) { return false; } // pre-process value $forceDirty = false; switch ($fieldOptions['type']) { case 'clob': case 'string': { $value = $this->_setStringValue($fieldOptions, $value); break; } case 'boolean': { $value = $this->_setBooleanValue($value); break; } case 'decimal': { $value = $this->_setDecimalValue($value); break; } case 'int': case 'uint': case 'integer': { $value = $this->_setIntegerValue($fieldOptions, $value); break; } case 'timestamp': { $value = $this->_setTimestampValue($value); break; } case 'date': { $value = $this->_setDateValue($value); break; } // these types are converted to strings from another PHP type on save case 'serialized': { $this->_convertedValues[$field] = $value; $value = $this->_setSerializedValue($value); break; } case 'enum': { $value = $this->_setEnumValue($fieldOptions, $value); break; } case 'set': case 'list': { $value = $this->_setListValue($fieldOptions, $value); $this->_convertedValues[$field] = $value; $forceDirty = true; break; } } if ($forceDirty || (empty($this->_record[$field]) && isset($value)) || ($this->_record[$field] !== $value)) { $columnName = static::_cn($field); if (isset($this->_record[$columnName])) { $this->_originalValues[$field] = $this->_record[$columnName]; } $this->_record[$columnName] = $value; $this->_isDirty = true; // unset invalidated relationships if (!empty($fieldOptions['relationships']) && static::isRelational()) { foreach ($fieldOptions['relationships'] as $relationship => $isCached) { if ($isCached) { unset($this->_relatedObjects[$relationship]); } } } return true; } else { return false; } }
php
{ "resource": "" }
q973
ElementsModel.findPublishedByAlias
train
public function findPublishedByAlias($strAlias, array $arrOptions=array()) { $t = static::$strTable; $arrColumns = array("$t.alias=? AND $t.invisible=''"); return static::findOneBy($arrColumns, $strAlias, $arrOptions); }
php
{ "resource": "" }
q974
CollectionEventSubscriber.preSubmitData
train
public function preSubmitData(FormEvent $event) { $form = $event->getForm(); $data = $event->getData(); if (null === $data || '' === $data) { $data = array(); } foreach ($form as $name => $child) { if (!isset($data[$name])) { $form->remove($name); } } }
php
{ "resource": "" }
q975
CollectionEventSubscriber.buildCollection
train
public function buildCollection(FormEvent $event, $eventName) { $form = $event->getForm(); for ($i = 0; $i < $this->options['max_items']; ++$i) { $required = $i < $this->options['min_items'] ? true : false; $displayed = $i < $this->options['min_items'] || $this->isDisplayable($event, $i, $eventName); $options = $this->options['options']; $options['required'] = isset($options['required']) ? $options['required'] && $required : $required ; $options['attr'] = array_replace( isset($options['attr']) ? $options['attr'] : array(), array( 'data-collection-id' => $this->options['collection_id'], 'data-display' => $displayed ? 'show' : 'hide', 'data-position' => $i, ) ); if (!$displayed) { self::disableConstraints($options); } $form->add($i, $this->options['type'], $options); $form->get($i)->add('__to_remove', CheckboxType::class, array( 'mapped' => false, 'required' => false, 'data' => !$displayed, 'attr' => array( 'class' => 'idci_collection_item_remove', ), )); } }
php
{ "resource": "" }
q976
CollectionEventSubscriber.changeData
train
public function changeData(FormEvent $event) { $data = $event->getData(); if (null === $data) { $data = array(); } if ($data instanceof \Doctrine\Common\Collections\Collection) { $event->setData($data->getValues()); } else { $event->setData(array_values($data)); } }
php
{ "resource": "" }
q977
CollectionEventSubscriber.onSubmit
train
public function onSubmit(FormEvent $event) { $form = $event->getForm(); $data = $event->getData(); if (null === $data) { $data = array(); } if (!is_array($data) && !($data instanceof \Traversable && $data instanceof \ArrayAccess)) { throw new UnexpectedTypeException($data, 'array or (\Traversable and \ArrayAccess)'); } // The data mapper only adds, but does not remove items, so do this here $toDelete = array(); foreach ($data as $name => $child) { if (null === $child || ( $form->get($name)->has('__to_remove') && true === $form->get($name)->get('__to_remove')->getData() )) { $toDelete[] = $name; } } foreach ($toDelete as $name) { unset($data[$name]); } if ($data instanceof \Doctrine\Common\Collections\Collection) { $event->setData($data->getValues()); } else { $event->setData($data); } }
php
{ "resource": "" }
q978
CollectionEventSubscriber.isDisplayable
train
protected function isDisplayable(FormEvent $event, $i, $eventName) { $form = $event->getForm(); $data = $event->getData(); if (!isset($data[$i])) { return false; } $item = is_object($data[$i]) ? (array) $data[$i] : $data[$i]; if (!is_array($item)) { return true; } if (FormEvents::PRE_SUBMIT === $eventName) { if (isset($item['__to_remove'])) { return !(bool) $item['__to_remove']; } } foreach ($item as $k => $v) { if (FormEvents::PRE_SUBMIT === $eventName && HiddenType::class === get_class($form->get($i)->get($k)->getConfig()->getType()->getInnerType()) ) { continue; } // Value not null if (null !== $v && '' !== $v) { return true; } } return false; }
php
{ "resource": "" }
q979
SQL.getCreateTable
train
public static function getCreateTable($recordClass, $historyVariant = false) { $indexes = $historyVariant ? [] : $recordClass::$indexes; $fulltextColumns = []; $queryString = []; // history table revisionID field if ($historyVariant) { $queryString[] = '`RevisionID` int(10) unsigned NOT NULL auto_increment'; $queryString[] = 'PRIMARY KEY (`RevisionID`)'; } $queryString = array_merge($queryString, static::compileFields($recordClass, $historyVariant)); if (!$historyVariant) { // If ContextClass && ContextID are members of this model let's index them if ($recordClass::fieldExists('ContextClass') && $recordClass::fieldExists('ContextID')) { $queryString[] = static::getContextIndex($recordClass); } $fulltextColumns = static::getFullTextColumns($recordClass); } // compile indexes foreach ($indexes as $indexName => $index) { // translate field names foreach ($index['fields'] as &$indexField) { $indexField = $recordClass::getColumnName($indexField); } if (!empty($index['fulltext'])) { $fulltextColumns = array_unique(array_merge($fulltextColumns, $index['fields'])); continue; } $queryString[] = sprintf( '%s KEY `%s` (`%s`)', !empty($index['unique']) ? 'UNIQUE' : '', $indexName, join('`,`', $index['fields']) ); } if (!empty($fulltextColumns)) { $queryString[] = 'FULLTEXT KEY `FULLTEXT` (`'.join('`,`', $fulltextColumns).'`)'; } $createSQL = sprintf( "CREATE TABLE IF NOT EXISTS `%s` (\n\t%s\n) ENGINE=MyISAM DEFAULT CHARSET=utf8;", $historyVariant ? $recordClass::getHistoryTable() : $recordClass::$tableName, join("\n\t,", $queryString) ); // append history table SQL if (!$historyVariant && is_subclass_of($recordClass, 'VersionedRecord')) { $createSQL .= PHP_EOL.PHP_EOL.PHP_EOL.static::getCreateTable($recordClass, true); } return $createSQL; }
php
{ "resource": "" }
q980
Watcher.stop
train
public function stop() { if (!$this->running) { return; } $this->running = false; $promise = call(function () { $promises = []; foreach (clone $this->workers as $worker) { \assert($worker instanceof Internal\IpcParent); $promises[] = call(function () use ($worker) { list($process, $promise) = $this->workers[$worker]; \assert($process instanceof Process); try { yield $worker->shutdown(); yield Promise\timeout($promise, self::WORKER_TIMEOUT); } catch (ContextException $exception) { // Ignore if the worker has already died unexpectedly. } finally { if ($process->isRunning()) { $process->kill(); } } }); } list($exceptions) = yield Promise\any($promises); $this->workers = new \SplObjectStorage; if (!empty($exceptions)) { $exception = new MultiReasonException($exceptions); $message = \implode('; ', \array_map(function (\Throwable $exception): string { return $exception->getMessage(); }, $exceptions)); throw new ClusterException("Stopping the cluster failed: " . $message, 0, $exception); } }); $this->deferred->resolve($promise); }
php
{ "resource": "" }
q981
MySQL.escape
train
public static function escape($data) { if (is_string($data)) { $data = static::getConnection()->quote($data); $data = substr($data, 1, strlen($data)-2); return $data; } elseif (is_array($data)) { foreach ($data as $key=>$string) { if (is_string($string)) { $data[$key] = static::escape($string); } } return $data; } return $data; }
php
{ "resource": "" }
q982
MySQL.allRecords
train
public static function allRecords($query, $parameters = [], $errorHandler = null) { // execute query $result = static::query($query, $parameters, $errorHandler); $records = []; while ($record = $result->fetch(PDO::FETCH_ASSOC)) { $records[] = $record; } return $records; }
php
{ "resource": "" }
q983
MySQL.allValues
train
public static function allValues($valueKey, $query, $parameters = [], $errorHandler = null) { // execute query $result = static::query($query, $parameters, $errorHandler); $records = []; while ($record = $result->fetch(PDO::FETCH_ASSOC)) { $records[] = $record[$valueKey]; } return $records; }
php
{ "resource": "" }
q984
MySQL.oneRecordCached
train
public static function oneRecordCached($cacheKey, $query, $parameters = [], $errorHandler = null) { // check for cached record if (array_key_exists($cacheKey, static::$_record_cache)) { // return cache hit return static::$_record_cache[$cacheKey]; } // preprocess and execute query $result = static::query($query, $parameters, $errorHandler); // get record $record = $result->fetch(PDO::FETCH_ASSOC); // save record to cache if ($cacheKey) { static::$_record_cache[$cacheKey] = $record; } // return record return $record; }
php
{ "resource": "" }
q985
MySQL.oneRecord
train
public static function oneRecord($query, $parameters = [], $errorHandler = null) { // preprocess and execute query $result = static::query($query, $parameters, $errorHandler); // get record $record = $result->fetch(PDO::FETCH_ASSOC); // return record return $record; }
php
{ "resource": "" }
q986
MySQL.oneValue
train
public static function oneValue($query, $parameters = [], $errorHandler = null) { // get the first record $record = static::oneRecord($query, $parameters, $errorHandler); if ($record) { // return first value of the record return array_shift($record); } else { return false; } }
php
{ "resource": "" }
q987
MySQL.handleError
train
public static function handleError($query = '', $queryLog = false, $errorHandler = null) { if (is_callable($errorHandler, false, $callable)) { return call_user_func($errorHandler, $query, $queryLog); } // save queryLog if ($queryLog) { $error = static::getConnection()->errorInfo(); $queryLog['error'] = $error[2]; static::finishQueryLog($queryLog); } // get error message $error = static::getConnection()->errorInfo(); $message = $error[2]; if (App::$Config['environment']=='dev') { $Handler = \Divergence\App::$whoops->popHandler(); $Handler->addDataTable("Query Information", [ 'Query' => $query, 'Error' => $message, 'ErrorCode' => static::getConnection()->errorCode(), ]); \Divergence\App::$whoops->pushHandler($Handler); throw new \RuntimeException("Database error!"); } else { throw new \RuntimeException("Database error!"); } }
php
{ "resource": "" }
q988
MySQL.preprocessQuery
train
protected static function preprocessQuery($query, $parameters = []) { if (is_array($parameters) && count($parameters)) { return vsprintf($query, $parameters); } else { if (isset($parameters)) { return sprintf($query, $parameters); } else { return $query; } } }
php
{ "resource": "" }
q989
MySQL.finishQueryLog
train
protected static function finishQueryLog(&$queryLog, $result = false) { if ($queryLog == false) { return false; } // save finish time and number of affected rows $queryLog['time_finish'] = sprintf('%f', microtime(true)); $queryLog['time_duration_ms'] = ($queryLog['time_finish'] - $queryLog['time_start']) * 1000; // save result information if ($result) { $queryLog['result_fields'] = $result->field_count; $queryLog['result_rows'] = $result->num_rows; } // build backtrace string // TODO: figure out a nice toString option that isn't too bulky //$queryLog['backtrace'] = debug_backtrace(); // monolog here }
php
{ "resource": "" }
q990
RequestSerializer.serialize
train
public static function serialize(RequestInterface $request): string { return self::requestLine($request).self::headers($request).$request->getBody(); }
php
{ "resource": "" }
q991
BelongsTo.getContent
train
public function getContent() { return strtr($this->getRelationStubContent(), [ '{{name}}' => $this->name, '{{relatedTable}}' => $this->relatedModel->getTable(), '{{relatedModel}}' => $this->relatedModel->getClass(), '{{foreignKey}}' => $this->foreignKey, ]); }
php
{ "resource": "" }
q992
ThrottlingMiddleware.safeHandle
train
protected function safeHandle(Request $request, Closure $next, int $limit, $decay, bool $global, bool $headers) { if ($this->shouldPassThrough($request)) { return $next($request); } $key = $global ? sha1($request->ip()) : $request->fingerprint(); if ($this->limiter->tooManyAttempts($key, $limit, $decay)) { throw $this->buildException($key, $limit, $headers); } $this->limiter->hit($key, $decay); $response = $next($request); $response->headers->add($this->getHeaders($key, $limit, $headers)); return $response; }
php
{ "resource": "" }
q993
RecordsRequestHandler.handleRequest
train
public static function handleRequest() { // save static class static::$calledClass = get_called_class(); // handle JSON requests if (static::peekPath() == 'json') { // check access for API response modes static::$responseMode = static::shiftPath(); if (in_array(static::$responseMode, ['json','jsonp'])) { if (!static::checkAPIAccess()) { return static::throwAPIUnAuthorizedError(); } } } return static::handleRecordsRequest(); }
php
{ "resource": "" }
q994
Controller.addContentElementsCSS
train
public function addContentElementsCSS ($strBuffer='', $objTemplate=null) { foreach (array('CSS', 'SCSS' , 'LESS') as $strType) { if ($GLOBALS['TL_CTB_' . $strType] == '') { continue; } $strKey = substr(md5($strType . $GLOBALS['TL_CTB_CSS'] . $GLOBALS['TL_CTB_SCSS'] . $GLOBALS['TL_CTB_LESS']), 0, 12); $strPath = 'assets/css/' . $strKey . '.' . strtolower($strType); // Write to a temporary file in the assets folder if (!file_exists($strPath)) { $objFile = new File($strPath, true); $objFile->write($GLOBALS['TL_CTB_' . $strType]); $objFile->close(); } $strPath .= '|static'; // add file path to TL_USER_CSS $GLOBALS['TL_USER_CSS'][] = $strPath; } return $strBuffer; }
php
{ "resource": "" }
q995
Controller.addContentElementsJS
train
public function addContentElementsJS ($strBuffer='', $objTemplate=null) { if ($GLOBALS['TL_CTB_JS'] == '') { return $strBuffer; } $strKey = substr(md5('js' . $GLOBALS['TL_CTB_JS']), 0, 12); $strPath = 'assets/js/' . $strKey . '.js'; // Write to a temporary file in the assets folder if (!file_exists($strPath)) { $objFile = new File($strPath, true); $objFile->write($GLOBALS['TL_CTB_JS']); $objFile->close(); } $strPath .= '|static'; // add file path to TL_JAVASCRIPT $GLOBALS['TL_JAVASCRIPT'][] = $strPath; return $strBuffer; }
php
{ "resource": "" }
q996
Controller.registerBlockElements
train
public function registerBlockElements () { // Don´t register twice if (isset($GLOBALS['TL_CTE']['CTE'])) { return; } $db = \Database::getInstance(); if ($db->tableExists("tl_elements")) { $arrElements = $db->prepare("SELECT * FROM tl_elements ORDER BY sorting ASC") ->execute() ->fetchAllAssoc(); } if ($arrElements === null) { return; } // Add content blocks as content elements foreach ($arrElements as $arrElement) { $GLOBALS['TL_CTE']['CTE'][$arrElement['alias']] = 'Agoat\CustomContentElementsBundle\Contao\ContentElement'; $GLOBALS['TL_LANG']['CTE'][$arrElement['alias']] = array($arrElement['title'],$arrElement['description']); } }
php
{ "resource": "" }
q997
Controller.getRootPageId
train
public static function getRootPageId ($strTable, $intId) { if ($strTable == 'tl_article') { $objArticle = \ArticleModel::findById($intId); if ($objArticle === null) { return null; } $objPage = \PageModel::findWithDetails($objArticle->pid); if ($objPage === null) { return null; } return $objPage->rootId; } elseif($strTable == 'tl_news') { $objNews = \NewsModel::findById($intId); if ($objNews === null) { return null; } $objPage = \PageModel::findWithDetails($objNews->getRelated('pid')->jumpTo); if ($objPage === null) { return null; } return $objPage->rootId; } else { // HOOK: custom method to discover the layout id if (isset($GLOBALS['TL_HOOKS']['getRootPageId']) && is_array($GLOBALS['TL_HOOKS']['getRootPageId'])) { foreach ($GLOBALS['TL_HOOKS']['getRootPageId'] as $callback) { //$this->import($callback[0]); $rootId = static::importStatic($callback[0])->{$callback[1]}($strTable, $intId); if (rootId) { return $rootId; } } } } return null; }
php
{ "resource": "" }
q998
Controller.addBackendCSS
train
private static function addBackendCSS($objLayout) { $arrCSS = \StringUtil::deserialize($objLayout->backendCSS); if (!empty($arrCSS) && is_array($arrCSS)) { // Consider the sorting order (see #5038) if ($objLayout->orderBackendCSS != '') { $tmp = \StringUtil::deserialize($objLayout->orderBackendCSS); if (!empty($tmp) && is_array($tmp)) { // Remove all values $arrOrder = array_map(function(){}, array_flip($tmp)); // Move the matching elements to their position in $arrOrder foreach ($arrCSS as $k=>$v) { if (array_key_exists($v, $arrOrder)) { $arrOrder[$v] = $v; unset($arrCSS[$k]); } } // Append the left-over style sheets at the end if (!empty($arrCSS)) { $arrOrder = array_merge($arrOrder, array_values($arrCSS)); } // Remove empty (unreplaced) entries $arrCSS = array_values(array_filter($arrOrder)); unset($arrOrder); } } // Get the file entries from the database $objFiles = \FilesModel::findMultipleByUuids($arrCSS); if ($objFiles !== null) { while ($objFiles->next()) { if (file_exists(TL_ROOT . '/' . $objFiles->path)) { $GLOBALS['TL_USER_CSS'][] = $objFiles->path . '|static'; } } } unset($objFiles); } }
php
{ "resource": "" }
q999
Controller.addBackendJS
train
private static function addBackendJS($objLayout) { $arrJS = \StringUtil::deserialize($objLayout->backendJS); if (!empty($arrJS) && is_array($arrJS)) { // Consider the sorting order (see #5038) if ($objLayout->orderBackendJS != '') { $tmp = \StringUtil::deserialize($objLayout->orderBackendJS); if (!empty($tmp) && is_array($tmp)) { // Remove all values $arrOrder = array_map(function(){}, array_flip($tmp)); // Move the matching elements to their position in $arrOrder foreach ($arrJS as $k=>$v) { if (array_key_exists($v, $arrOrder)) { $arrOrder[$v] = $v; unset($arrJS[$k]); } } // Append the left-over style sheets at the end if (!empty($arrJS)) { $arrOrder = array_merge($arrOrder, array_values($arrJS)); } // Remove empty (unreplaced) entries $arrJS = array_values(array_filter($arrOrder)); unset($arrOrder); } } // Get the file entries from the database $objFiles = \FilesModel::findMultipleByUuids($arrJS); if ($objFiles !== null) { while ($objFiles->next()) { if (file_exists(TL_ROOT . '/' . $objFiles->path)) { $GLOBALS['TL_JAVASCRIPT'][] = $objFiles->path . '|static'; } } } unset($objFiles); } }
php
{ "resource": "" }