_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
33
8k
language
stringclasses
1 value
meta_information
dict
q4600
Db.query
train
protected function query(string $sql, array $params = [], array $options = []): \PDOStatement { $options += [ Db::OPTION_FETCH_MODE => $this->getFetchArgs() ]; $stm = $this->getPDO()->prepare($sql); if ($options[Db::OPTION_FETCH_MODE]) { $stm->setFetchMode(...(array)$options[Db::OPTION_FETCH_MODE]); } $r = $stm->execute($params);
php
{ "resource": "" }
q4601
Db.queryModify
train
protected function queryModify(string $sql, array $params = [], array $options = []): int { $options += [Db::OPTION_FETCH_MODE => 0];
php
{ "resource": "" }
q4602
Db.queryID
train
protected function queryID(string $sql, array $params = [], array $options = []) { $options += [Db::OPTION_FETCH_MODE => 0]; $this->query($sql, $params, $options);
php
{ "resource": "" }
q4603
Db.queryDefine
train
protected function queryDefine(string $sql, array $options = []) { $options
php
{ "resource": "" }
q4604
Db.escape
train
public function escape($identifier): string { if ($identifier instanceof Literal) { return $identifier->getValue($this);
php
{ "resource": "" }
q4605
Db.prefixTable
train
protected function prefixTable($table, bool $escape = true): string { if ($table instanceof Identifier) { return $escape ? $table->escape($this) : (string)$table; } else {
php
{ "resource": "" }
q4606
Db.stripPrefix
train
protected function stripPrefix(string $table): string { $len = strlen($this->px); if (strcasecmp(substr($table, 0, $len), $this->px) === 0) {
php
{ "resource": "" }
q4607
ThemeHandle.getThemesFromDir
train
public function getThemesFromDir() { $themeList = array(); $themePath = Yii::getPathOfAlias('webroot.themes'); $themes = scandir($themePath); foreach($themes as $theme) { $themeName = $this->urlTitle($theme);
php
{ "resource": "" }
q4608
ThemeHandle.cacheThemeConfig
train
public function cacheThemeConfig($return=false) { $themes = $this->getThemesFromDb(); $arrayTheme = array(); foreach($themes as $theme) { if(!in_array($theme->folder, $arrayTheme)) $arrayTheme[] = $theme->folder; } if($return == false) { $filePath
php
{ "resource": "" }
q4609
ThemeHandle.getThemeConfig
train
public function getThemeConfig($theme) { Yii::import('mustangostang.spyc.Spyc'); define('DS', DIRECTORY_SEPARATOR); $themeName = $this->urlTitle($theme); $configPath =
php
{ "resource": "" }
q4610
ThemeHandle.deleteThemeDb
train
public function deleteThemeDb($theme) { if($theme != null) { $model = OmmuThemes::model()->findByAttributes(array('folder'=>$theme)); if($model !=
php
{ "resource": "" }
q4611
ThemeHandle.setThemes
train
public function setThemes() { $installedTheme = $this->getThemesFromDir(); $cacheTheme = file(Yii::getPathOfAlias('application.config').'/cache_theme.php'); $toBeInstalled = array(); $caches = array(); foreach($cacheTheme as $val) { $caches[] = $val; } if(!$installedTheme) $installedTheme = array(); foreach($caches as $cache) { $cache = trim($cache); if(!in_array($cache, array_map("trim", $installedTheme))) { $this->deleteTheme($cache, true); } } $themeDb = $this->cacheThemeConfig(true); foreach($installedTheme as $theme) { if(!in_array(trim($theme), array_map("trim", $themeDb))) {
php
{ "resource": "" }
q4612
PhotosAlbumsTable.afterSave
train
public function afterSave(Event $event, Entity $entity, ArrayObject $options) {
php
{ "resource": "" }
q4613
CreateAdminCommand.execute
train
public function execute(Arguments $args, ConsoleIo $io) { $command = new AddUserCommand;
php
{ "resource": "" }
q4614
ReqAttr.getReferrer
train
public static function getReferrer(ServerRequestInterface $request) { if ($referrer = $request->getAttribute(self::REFERRER)) { return $referrer; } if ($referrer = Respond::session()->get(self::REFERRER)) { return $referrer;
php
{ "resource": "" }
q4615
ReqAttr.withBasePath
train
public static function withBasePath(ServerRequestInterface $request, $basePath, $pathInfo = null) { $path = $request->getUri()->getPath(); if (strpos($path, $basePath) !== 0) { throw new \InvalidArgumentException; } $pathInfo = is_null($pathInfo)
php
{ "resource": "" }
q4616
ReqAttr.getPathInfo
train
public static function getPathInfo(ServerRequestInterface $request) {
php
{ "resource": "" }
q4617
QueueManager.run
train
public function run($eventname, $count) { $queueEvents = $this->loadQueue($eventname, $count); if ($queueEvents->numRows) { while ($queueEvents->next()) { if ($this->checkInterval($queueEvents)) { $this->setStartTime($queueEvents->id); $jobEvent = $this->dispatch($queueEvents);
php
{ "resource": "" }
q4618
QueueManager.setError
train
protected function setError($id) { $queueEvent = new QueueSetErrorEvent();
php
{ "resource": "" }
q4619
QueueManager.saveJobResult
train
protected function saveJobResult($id, $jobEvent) { if ($jobEvent) { $queueEvent = new QueueSaveJobResultEvent(); $queueEvent->setId($id);
php
{ "resource": "" }
q4620
QueueManager.dispatch
train
protected function dispatch($queueEvent) { $event = urldecode($queueEvent->data); $event = unserialize($event); if ($event) { $this->dispatcher->dispatch($event::NAME, $event); if ($event->getHasError()) { $this->setError($queueEvent->id); $this->response($event::NAME, $event->getError(),
php
{ "resource": "" }
q4621
MessageMapper.markAsRead
train
public function markAsRead(int $messageId) { $this->sql = 'update message set
php
{ "resource": "" }
q4622
MessageMapper.markAsUnread
train
public function markAsUnread(int $messageId) { $this->sql = 'update message set
php
{ "resource": "" }
q4623
DateInterval.fromSpecification
train
public static function fromSpecification(string $specification) : self { $microseconds = 0; // Parse the microsecond component. if (false !== ($position = stripos($specification, 'U'))) { // Step backwards consuming digits until we hit a duration designator. // Note that we always expect at least the duration designator (P), but for loop safety we break if // the first character in the specification is reached too. $microseconds = ''; while ($position > 0) { $char = $specification[--$position]; if (!is_numeric($char)) { break; } $microseconds = $char . $microseconds;
php
{ "resource": "" }
q4624
DateInterval.diff
train
public static function diff(DateTime $a, DateTime $b, bool $absolute = false) : self { $microseconds = $b->microsecond() - $a->microsecond(); if ($absolute) { $microseconds = abs($microseconds); }
php
{ "resource": "" }
q4625
DateInterval.fromComponents
train
public static function fromComponents( int $years = null, int $months = null, int $weeks = null, int $days = null, int $hours = null, int $minutes = null, int $seconds = null, int $microseconds = null ) : self { if (!($years || $months || $weeks || $days || $hours || $minutes || $seconds || $microseconds)) { throw new \InvalidArgumentException('At least one component is required.'); } $years = $years ?: 0; $months = $months ?: 0; $weeks = $weeks ?: 0; $days = $days ?: 0; $hours = $hours ?: 0; $minutes = $minutes ?: 0; $seconds = $seconds ?: 0; $microseconds = $microseconds ?: 0; $specification = 'P'; if ($years) { $specification .= $years . 'Y'; } if ($months) {
php
{ "resource": "" }
q4626
DateInterval.format
train
public function format(string $format) : string { // Replace microseconds first so they become literals. // Ignore any escaped microsecond identifiers. $format = preg_replace_callback( // Starting at the start of the string or the first non % character,
php
{ "resource": "" }
q4627
DateInterval.totalMicroseconds
train
public function totalMicroseconds() : int { if (null === $this->totalMicroseconds) { $reference = DateTime::now(); $end = $reference->add($this);
php
{ "resource": "" }
q4628
DateInterval.clone
train
private static function clone(\DateInterval $interval) { $specification = $interval->format('P%yY%mM%dDT%hH%iM%sS'); $clone = new \DateInterval($specification);
php
{ "resource": "" }
q4629
PostsCategoriesController.view
train
public function view($slug = null) { //The category can be passed as query string, from a widget if ($this->request->getQuery('q')) { return $this->redirect([$this->request->getQuery('q')]); } $page = $this->request->getQuery('page', 1); //Sets the cache name $cache = sprintf('category_%s_limit_%s_page_%s', md5($slug), $this->paginate['limit'], $page); //Tries to get data from the cache list($posts, $paging) = array_values(Cache::readMany( [$cache, sprintf('%s_paging', $cache)], $this->PostsCategories->getCacheName() ));
php
{ "resource": "" }
q4630
LogsController.getPath
train
protected function getPath($filename, $serialized) { if ($serialized) {
php
{ "resource": "" }
q4631
LogsController.read
train
protected function read($filename, $serialized) { $log = $this->getPath($filename, $serialized); is_readable_or_fail($log); $log
php
{ "resource": "" }
q4632
LogsController.view
train
public function view($filename) { $serialized = false; if ($this->request->getQuery('as') === 'serialized') { $serialized =
php
{ "resource": "" }
q4633
LogsController.download
train
public function download($filename) { return $this->response->withFile($this->getP
php
{ "resource": "" }
q4634
LogsController.delete
train
public function delete($filename) { $this->request->allowMethod(['post', 'delete']); $success = (new File($this->getPath($filename, false)))->delete(); $serialized = $this->getPath($filename, true); //Deletes the serialized log copy, if it exists if (file_exists($serialized)) { $successSerialized = (new File($serialized))->delete();
php
{ "resource": "" }
q4635
PhotosController.view
train
public function view($slug = null, $id = null) { //This allows backward compatibility for URLs like `/photo/11` if (empty($slug)) { $slug = $this->Photos->findById($id) ->contain([$this->Photos->Albums->getAlias() => ['fields' => ['slug']]]) ->extract('album.slug') ->first(); return $this->redirect(compact('id', 'slug'), 301); } $photo = $this->Photos->findActiveById($id) ->select(['id', 'album_id', 'filename', 'active', 'modified'])
php
{ "resource": "" }
q4636
PhotosController.preview
train
public function preview($id = null) { $photo = $this->Photos->findPendingById($id) ->select(['id', 'album_id', 'filename']) ->contain([$this->Photos->Albums->getAlias() => ['fields' => ['id', 'title',
php
{ "resource": "" }
q4637
MultiCurrencyBank.checkCurrencies
train
protected function checkCurrencies($currencies) { foreach ((array) $currencies as $currency) { if (!$this->hasCurrency($currency)) {
php
{ "resource": "" }
q4638
MultiCurrencyBank.getRate
train
public function getRate($fromCurrency, $toCurrency = null) { if (null === $toCurrency) { $toCurrency = $this->getBaseCurrency(); }
php
{ "resource": "" }
q4639
MultiCurrencyBank.reduce
train
public function reduce(MoneyInterface $source, $toCurrency = null) { if (null === $toCurrency) {
php
{ "resource": "" }
q4640
MultiCurrencyBank.createMoney
train
public function createMoney($amount, $currency = null) { if (null === $currency) { $currency = $this->getBaseCurrency(); }
php
{ "resource": "" }
q4641
Auth.verifyCredentials
train
public function verifyCredentials($sIdentifier, $sPassword) { // Look up the user, how we do so depends on the login mode that the app is using $oUserModel = Factory::model('User', 'nails/module-auth');
php
{ "resource": "" }
q4642
Auth.logout
train
public function logout() { $oUserModel = Factory::model('User', 'nails/module-auth'); $oUserModel->clearRememberCookie(); // -------------------------------------------------------------------------- // null the remember_code so that auto-logins stop $oDb = Factory::service('Database'); $oDb->set('remember_code', null); $oDb->where('id', activeUser('id')); $oDb->update(NAILS_DB_PREFIX . 'user'); // --------------------------------------------------------------------------
php
{ "resource": "" }
q4643
Auth.mfaTokenGenerate
train
public function mfaTokenGenerate($iUserId) { $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oNow = Factory::factory('DateTime'); $oInput = Factory::service('Input'); $oDb = Factory::service('Database'); $sSalt = $oPasswordModel->salt(); $sIp = $oInput->ipAddress(); $sCreated = $oNow->format('Y-m-d H:i:s'); $sExpires = $oNow->add(new \DateInterval('PT10M'))->format('Y-m-d H:i:s'); $aToken = [ 'token' => sha1(sha1(APP_PRIVATE_KEY . $iUserId . $sCreated . $sExpires . $sIp) . $sSalt), 'salt' => md5($sSalt), ]; //
php
{ "resource": "" }
q4644
Auth.mfaTokenValidate
train
public function mfaTokenValidate($iUserId, $sSalt, $sToken, $sIp) { $oDb = Factory::service('Database'); $oDb->where('user_id', $iUserId); $oDb->where('salt', $sSalt); $oDb->where('token', $sToken); $oToken = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_token')->row(); $bReturn = true; if (!$oToken) { $this->setError(lang('auth_twofactor_token_invalid')); return false; } elseif (strtotime($oToken->expires) <= time()) { $this->setError(lang('auth_twofactor_token_expired'));
php
{ "resource": "" }
q4645
Auth.mfaTokenDelete
train
public function mfaTokenDelete($iTokenId) { $oDb = Factory::service('Database'); $oDb->where('id', $iTokenId);
php
{ "resource": "" }
q4646
Auth.mfaQuestionGet
train
public function mfaQuestionGet($iUserId) { $oDb = Factory::service('Database'); $oInput = Factory::service('Input'); $oDb->where('user_id', $iUserId); $oDb->order_by('last_requested', 'DESC'); $aQuestions = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question')->result(); if (!$aQuestions) { $this->setError('No security questions available for this user.'); return false; } // -------------------------------------------------------------------------- // Choose a question to return if (count($aQuestions) == 1) { // No choice, just return the lonely question $oOut = reset($aQuestions); } elseif (count($aQuestions) > 1) { /** * Has the most recently asked question been asked in the last 10 minutes? * If so, return that one again (to make harvesting all the user's questions * a little more time consuming). If not randomly choose one. */ $oOut = reset($aQuestions); if (strtotime($oOut->last_requested) < strtotime('-10 MINS')) {
php
{ "resource": "" }
q4647
Auth.mfaQuestionValidate
train
public function mfaQuestionValidate($iQuestionId, $iUserId, $answer) { $oDb = Factory::service('Database'); $oDb->select('answer, salt'); $oDb->where('id', $iQuestionId); $oDb->where('user_id', $iUserId); $oQuestion = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_question')->row(); if (!$oQuestion) {
php
{ "resource": "" }
q4648
Auth.mfaQuestionSet
train
public function mfaQuestionSet($iUserId, $aData, $bClearOld = true) { // Check input foreach ($aData as $oDatum) { if (empty($oDatum->question) || empty($oDatum->answer)) { $this->setError('Malformed question/answer data.'); return false; } } // Begin transaction $oDb = Factory::service('Database'); $oDb->trans_begin(); // Delete old questions? if ($bClearOld) { $oDb->where('user_id', $iUserId); $oDb->delete(NAILS_DB_PREFIX . 'user_auth_two_factor_question'); } $oPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oEncrypt = Factory::service('Encrypt'); $aQuestionData = []; $iCounter = 0; $oNow = Factory::factory('DateTime'); $sDateTime = $oNow->format('Y-m-d H:i:s'); foreach ($aData as $oDatum) { $sSalt = $oPasswordModel->salt(); $aQuestionData[$iCounter] = [ 'user_id' => $iUserId,
php
{ "resource": "" }
q4649
Auth.mfaDeviceSecretGet
train
public function mfaDeviceSecretGet($iUserId) { $oDb = Factory::service('Database'); $oEncrypt = Factory::service('Encrypt'); $oDb->where('user_id', $iUserId); $oDb->limit(1); $aResult = $oDb->get(NAILS_DB_PREFIX . 'user_auth_two_factor_device_secret')->result(); if (empty($aResult)) {
php
{ "resource": "" }
q4650
Auth.mfaDeviceSecretGenerate
train
public function mfaDeviceSecretGenerate($iUserId, $sExistingSecret = null) { // Get an identifier for the user $oUserModel = Factory::model('User', 'nails/module-auth'); $oUser = $oUserModel->getById($iUserId); if (!$oUser) { $this->setError('User does not exist.'); return false; } $oGoogleAuth = new GoogleAuthenticator(); // Generate the secret if (empty($sExistingSecret)) { $sSecret = $oGoogleAuth->generateSecret(); } else { $sSecret = $sExistingSecret; } // Get the hostname
php
{ "resource": "" }
q4651
Auth.mfaDeviceSecretValidate
train
public function mfaDeviceSecretValidate($iUserId, $sSecret, $iCode) { // Tidy up codes so that they only contain digits $sCode = preg_replace('/[^\d]/', '', $iCode); // New instance of the authenticator $oGoogleAuth = new GoogleAuthenticator(); if ($oGoogleAuth->checkCode($sSecret, $sCode)) { $oDb = Factory::service('Database'); $oEncrypt = Factory::service('Encrypt'); $oDb->set('user_id', $iUserId); $oDb->set('secret', $oEncrypt->encode($sSecret, APP_PRIVATE_KEY));
php
{ "resource": "" }
q4652
Auth.mfaDeviceCodeValidate
train
public function mfaDeviceCodeValidate($iUserId, $sCode) { // Get the user's secret $oSecret = $this->mfaDeviceSecretGet($iUserId); if (!$oSecret) { $this->setError('Invalid User'); return false; } // Has the code been used before? $oDb = Factory::service('Database'); $oDb->where('secret_id', $oSecret->id); $oDb->where('code', $sCode); if ($oDb->count_all_results(NAILS_DB_PREFIX . 'user_auth_two_factor_device_code')) { $this->setError('Code has already been used.'); return false; } // Tidy up codes so that they only contain digits $sCode = preg_replace('/[^\d]/', '',
php
{ "resource": "" }
q4653
Referrer.saveReferrer
train
private function saveReferrer(ServerRequestInterface $request) {
php
{ "resource": "" }
q4654
ViewData.setMessage
train
public function setMessage($type, $message) { if (!is_null($message)) { $this->messages[] = [ 'message' => $message,
php
{ "resource": "" }
q4655
Apache.modules
train
public function modules() { $modules = []; foreach ($this->modulesToCheck as $module) { $modules[$module] = in_array('mod_'
php
{ "resource": "" }
q4656
App.brokenLinksColumnSorting
train
public function brokenLinksColumnSorting() { add_filter('posts_fields', function ($fields, $query) { if ($query->get('orderby') !== 'broken-links') { return $fields; } global $wpdb; $fields .= ", ( SELECT COUNT(*) FROM " . self::$dbTable . " WHERE post_id = {$wpdb->posts}.ID ) AS broken_links_count"; return $fields; }, 10, 2);
php
{ "resource": "" }
q4657
App.addListTablePage
train
public function addListTablePage() { add_submenu_page( 'options-general.php', 'Broken links', 'Broken links', 'edit_posts', 'broken-links-detector', function () { \BrokenLinkDetector\App::checkInstall(); $listTable = new \BrokenLinkDetector\ListTable(); $offset = get_option('gmt_offset'); if ($offset > -1) { $offset = '+' . $offset;
php
{ "resource": "" }
q4658
App.checkSavedPost
train
public function checkSavedPost($data, $postarr) { remove_action('wp_insert_post_data', array($this,
php
{ "resource": "" }
q4659
App.deleteBrokenLinks
train
public function deleteBrokenLinks($postId) { global $wpdb; $tableName = self::$dbTable;
php
{ "resource": "" }
q4660
UsersTable.findAuth
train
public function findAuth(Query $query, array $options) { return $query->contain('Groups', function (Query $q) {
php
{ "resource": "" }
q4661
UsersTable.findBanned
train
public function findBanned(Query $query, array $options) {
php
{ "resource": "" }
q4662
UsersTable.findPending
train
public function findPending(Query $query, array $options) { return $query->where([ sprintf('%s.active', $this->getAlias()) => false,
php
{ "resource": "" }
q4663
UsersTable.getActiveList
train
public function getActiveList() { return $this->find() ->select(['id', 'first_name', 'last_name']) ->where([sprintf('%s.active', $this->getAlias()) => true]) ->order(['username' => 'ASC']) ->formatResults(function (ResultSet $results) { return $results->indexBy('id')->map(function (User $user)
php
{ "resource": "" }
q4664
UsersTable.validationDoNotRequirePresence
train
public function validationDoNotRequirePresence(UserValidator $validator) { //No field is required foreach ($validator->getIterator() as $field => $rules) {
php
{ "resource": "" }
q4665
PostsTagsWidgetsCell.getFontSizes
train
protected function getFontSizes(array $style = []) { //Maximum and minimun font sizes we want to use $maxFont = empty($style['maxFont']) ? 40 : $style['maxFont']; $minFont = empty($style['minFont']) ? 12 : $style['minFont'];
php
{ "resource": "" }
q4666
PostsTagsWidgetsCell.popular
train
public function popular( $limit = 10, $prefix = '#', $render = 'cloud', $shuffle = true, $style = ['maxFont' => 40, 'minFont' => 12] ) { $this->viewBuilder()->setTemplate(sprintf('popular_as_%s', $render)); //Returns on tags index if ($this->request->isUrl(['_name' => 'postsTags'])) { return; } //Sets default maximum and minimun font sizes we want to use $maxFont = $minFont = 0; //Sets the initial cache name $cache = sprintf('widget_tags_popular_%s', $limit); if ($style && is_array($style)) { //Updates maximum and minimun font sizes we want to use list($maxFont, $minFont) = $this->getFontSizes($style); //Updates the cache name $cache = sprintf('%s_max_%s_min_%s', $cache, $maxFont, $minFont); } $tags = $this->Tags->find() ->select(['tag', 'post_count']) ->limit($limit) ->order([ sprintf('%s.post_count', $this->Tags->getAlias()) => 'DESC', sprintf('%s.tag', $this->Tags->getAlias()) => 'ASC', ]) ->formatResults(function (ResultSet $results) use ($style, $maxFont, $minFont) { $results = $results->indexBy('slug');
php
{ "resource": "" }
q4667
ComposerListener.registerPackage
train
public static function registerPackage(Event $event) { $installedPackage = $event->getOperation()->getPackage(); if (!self::isBundle($installedPackage)) {
php
{ "resource": "" }
q4668
Redirect.toPath
train
public function toPath($path) { $uri = $this->request->getUri()->withPath($path);
php
{ "resource": "" }
q4669
PostsWidgetsCell.months
train
public function months($render = 'form') { $this->viewBuilder()->setTemplate(sprintf('months_as_%s', $render)); //Returns on posts index if ($this->request->isUrl(['_name' => 'posts'])) { return; } $query = $this->Posts->find('active'); $time = $query->func()->date_format(['created' => 'identifier', "'%Y/%m'" => 'literal']); $months = $query->select([ 'month' => $time,
php
{ "resource": "" }
q4670
DisableElementsCapableFormSettings.filterArrayStrings
train
protected function filterArrayStrings($array, $search, $replace) { $return = array(); foreach ((array)$array as $key => $value) { $key = str_replace($search, $replace, $key); $value = is_array($value) ? $this->filterArrayStrings($value, $search,
php
{ "resource": "" }
q4671
Escaper.escapeCharacterClass
train
public function escapeCharacterClass($char) { return (isset($this->inCharacterClass[$char]))
php
{ "resource": "" }
q4672
Escaper.escapeLiteral
train
public function escapeLiteral($char) { return (isset($this->inLiteral[$char])) ?
php
{ "resource": "" }
q4673
RedisService.add
train
public function add($id, $data = 1) { try { return $this->resource->hSet(static::CACHE_KEY, $id, $data);
php
{ "resource": "" }
q4674
RedisService.exists
train
public function exists($id) { try { return !!$this->resource->hExists(static::CACHE_KEY, $id);
php
{ "resource": "" }
q4675
RedisService.remove
train
public function remove($id) { try { return $this->resource->hDel(static::CACHE_KEY, $id);
php
{ "resource": "" }
q4676
MergeSuffix.hasMatchingSuffix
train
protected function hasMatchingSuffix(array $strings) { $suffix = end($strings[1]); foreach ($strings as $string) {
php
{ "resource": "" }
q4677
MergeSuffix.pop
train
protected function pop(array $strings) { $cnt = count($strings); $i = $cnt; while (--$i >= 0) { array_pop($strings[$i]); } // Remove empty elements then prepend one back at the start of the array if applicable $strings
php
{ "resource": "" }
q4678
User.getSearch
train
public function getSearch($aData = []) { if (!userHasPermission('admin:auth:accounts:browse')) { $oHttpCodes = Factory::service('HttpCodes'); throw new ApiException( 'You are not authorised to
php
{ "resource": "" }
q4679
User.getEmail
train
public function getEmail() { $oHttpCodes = Factory::service('HttpCodes'); if (!userHasPermission('admin:auth:accounts:browse')) { throw new ApiException( 'You are not authorised to browse users', $oHttpCodes::STATUS_UNAUTHORIZED ); } $oInput = Factory::service('Input'); $sEmail = $oInput->get('email'); if (!valid_email($sEmail)) { throw new ApiException( '"' . $sEmail . '" is not a valid email', $oHttpCodes::STATUS_BAD_REQUEST );
php
{ "resource": "" }
q4680
User.postRemap
train
public function postRemap() { $oUri = Factory::service('Uri'); $iItemId = (int) $oUri->segment(4); if ($iItemId && $iItemId != activeUSer('id') && !userHasPermission('admin:auth:accounts:editothers')) { return [ 'status' => 401,
php
{ "resource": "" }
q4681
User.formatObject
train
public function formatObject($oObj) { return [ 'id' => $oObj->id, 'first_name' => $oObj->first_name,
php
{ "resource": "" }
q4682
FileUploadHandler.upload
train
public function upload(string $fileKey) { if (!isset($this->uploadedFiles[$fileKey])) { throw new Exception('PitonCMS: File upload key does not exist'); } $file = $this->uploadedFiles[$fileKey]; if ($file->getError() === UPLOAD_ERR_OK) { // Get file name and extension $uploadFileName = $file->getClientFilename(); $ext = strtolower(pathinfo($uploadFileName, PATHINFO_EXTENSION)); // Create new file name and directory and ensure it is unique do { $name = $this->generateName();
php
{ "resource": "" }
q4683
FileUploadHandler.getErrorMessage
train
public function getErrorMessage() { switch ($this->error) { case UPLOAD_ERR_INI_SIZE: $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini"; break; case UPLOAD_ERR_FORM_SIZE: $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"; break; case UPLOAD_ERR_PARTIAL: $message = "The uploaded file was only partially uploaded"; break; case UPLOAD_ERR_NO_FILE: $message = "No file was uploaded"; break; case UPLOAD_ERR_NO_TMP_DIR: $message = "Missing a temporary folder"; break;
php
{ "resource": "" }
q4684
FileUploadHandler.makeFileDirectory
train
protected function makeFileDirectory($directoryPath) { $filePath = $this->publicRoot . $directoryPath; // Create the path if the directory does not exist if (!is_dir($filePath)) { try { mkdir($filePath, 0775, true); return true; } catch (Exception $e) {
php
{ "resource": "" }
q4685
Utf8.charsToCodepointsWithSurrogates
train
protected function charsToCodepointsWithSurrogates(array $chars) { $codepoints = []; foreach ($chars as $char) { $cp = $this->cp($char);
php
{ "resource": "" }
q4686
Utf8.cp
train
protected function cp($char) { $cp = ord($char[0]); if ($cp >= 0xF0) { $cp = ($cp << 18) + (ord($char[1]) << 12) + (ord($char[2]) << 6) + ord($char[3]) - 0x3C82080; } elseif ($cp >= 0xE0) { $cp
php
{ "resource": "" }
q4687
Page.getPublishedStatus
train
public function getPublishedStatus() { $today = date('Y-m-d'); if (empty($this->published_date)) { return 'draft'; } elseif ($this->published_date > $today) { return 'pending';
php
{ "resource": "" }
q4688
AttachmentAwareTrait.addAttachment
train
public function addAttachment($attachment, $group = 'contents') { if (!$attachment instanceof AttachableInterface && !$attachment instanceof ModelInterface) { return false; } $join = $this->modelFactory()->create(Join::class); $objId = $this->id(); $objType = $this->objType(); $attId
php
{ "resource": "" }
q4689
AttachmentAwareTrait.removeAttachmentJoins
train
public function removeAttachmentJoins() { $joinProto = $this->modelFactory()->get(Join::class); $loader = $this->collectionLoader(); $loader ->setModel($joinProto) ->addFilter('object_type', $this->objType()) ->addFilter('object_id', $this->id());
php
{ "resource": "" }
q4690
Pager.generateLinksCenter
train
public function generateLinksCenter(string $page = null, string $ignoredKeys = null, $linksClassName = null): string { // only one page? $totalPages = $this->totalPages; if ($totalPages == 1) { return $this->template(['<a class="current" href="#">1</a>'], $linksClassName, true); } $links = (array) $this->linksCenter; if ($links != null) { return $this->template($links, $linksClassName, true); } $linksTemplate = $this->linksTemplate; $s = $this->startKey; $query = $this->prepareQuery($ignoredKeys); $start = max(1, ($this->start / $this->stop) + 1); // add first & prev links $prev = $start - 1; if ($prev >= 1) { $links[] = sprintf('<a class="first" rel="first" href="%s%s=1">%s</a>', $query, $s, $linksTemplate['first']); $links[] = sprintf('<a class="prev" rel="prev" href="%s%s=%s">%s</a>', $query, $s, $prev, $linksTemplate['prev']); } $links[] = sprintf('<a class="current" href="#">%s %s</a>', $page
php
{ "resource": "" }
q4691
GetStartAndEndDateTrait.getStartAndEndDate
train
protected function getStartAndEndDate($date) { $year = $month = $day = null; //Sets the start date if (in_array($date, ['today', 'yesterday'])) { $start = Time::parse($date); } else { list($year, $month, $day) = array_replace([null, null, null], explode('/', $date));
php
{ "resource": "" }
q4692
User.addTeams
train
public function addTeams(ArrayCollection $teams) { foreach ($teams as
php
{ "resource": "" }
q4693
User.removeTeams
train
public function removeTeams(ArrayCollection $teams) { foreach ($teams as $team) { $team->removeUser($this);
php
{ "resource": "" }
q4694
XMLTransformer.transform
train
public static function transform($xslFileName, DOMDocument $xml) { $xsl = new DOMDocument; $xsl->load(__DIR__.'/../../xslt/'.$xslFileName.'.xsl'); $proc = new XSLTProcessor;
php
{ "resource": "" }
q4695
PostsCategoriesController.delete
train
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $category = $this->PostsCategories->get($id); //Before deleting, it checks if the category has some posts if (!$category->post_count) { $this->PostsCategories->deleteOrFail($category);
php
{ "resource": "" }
q4696
TableQuery.setOption
train
protected function setOption($name, $value, $reset = false) { $changed = !isset($this->options[$name]) || $this->options[$name] !== $value; if ($changed && $reset) {
php
{ "resource": "" }
q4697
SessionStorage.forge
train
public static function forge($name, $cookie = null) { $factory = new SessionFactory(); $cookie = $cookie ?: $_COOKIE; $session = $factory->newInstance($cookie);
php
{ "resource": "" }
q4698
SessionStorage.withStorage
train
public function withStorage($name) { $self = clone($this); $self->segment
php
{ "resource": "" }
q4699
Login.index
train
public function index() { // If you're logged in you shouldn't be accessing this method if (isLoggedIn()) { redirect($this->data['return_to']); } // -------------------------------------------------------------------------- // If there's POST data attempt to log user in $oInput = Factory::service('Input'); if ($oInput->post()) { // Validate input $oFormValidation = Factory::service('FormValidation'); // The rules vary depending on what login methods are enabled. switch (APP_NATIVE_LOGIN_USING) { case 'EMAIL': $oFormValidation->set_rules('identifier', 'Email', 'required|trim|valid_email'); break; case 'USERNAME': $oFormValidation->set_rules('identifier', 'Username', 'required|trim'); break; default: $oFormValidation->set_rules('identifier', 'Username or Email', 'trim'); break; } // Password is always required, obviously. $oFormValidation->set_rules('password', 'Password', 'required');
php
{ "resource": "" }