_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q1300
MediaController.deleteDirectory
train
protected function deleteDirectory(Request $request) { try { $dir = $request->input('s'); Storage::deleteDirectory($dir); return $this->notifySuccess($dir . ' successfully deleted!'); } catch (\ErrorException $e) { return $this->notifyError($e->getMessage()); } }
php
{ "resource": "" }
q1301
MediaController.deleteFile
train
protected function deleteFile(Request $request) { try { $file = $request->input('s'); Storage::delete($file); return $this->notifySuccess($file . ' successfully deleted!'); } catch (\ErrorException $e) { return $this->notifyError($e->getMessage()); } }
php
{ "resource": "" }
q1302
ExtensionsController.destroy
train
public function destroy($id) { $extension = $this->repository->findOrFail($id); if ($extension->protected) { return $this->notifyError(trans('cms::extension.protected')); } if ($this->repository->uninstall($id)) { flash()->success(trans('cms::extension.deleted', compact('id'))); } else { flash()->error(trans('cms::extension.error', compact('id'))); } return back(); }
php
{ "resource": "" }
q1303
Responder.payload
train
public function payload($payload, $format = '', $container = 'data') { $class = $this->getFormatClass($format); return $this->generate($payload, new $class, $container); }
php
{ "resource": "" }
q1304
Responder.registerFormat
train
public function registerFormat($format, $class) { if ( ! class_exists($class)) { throw new \InvalidArgumentException("Responder formatter class {$class} not found."); } if ( ! is_a($class, 'Nathanmac\Utilities\Responder\Formats\FormatInterface', true)) { throw new \InvalidArgumentException('Responder formatters must implement the Nathanmac\Utilities\Responder\Formats\FormatInterface interface.'); } $this->supported_formats[$format] = $class; return $this; }
php
{ "resource": "" }
q1305
RedirectComponent.handle
train
public function handle(ComponentContext $componentContext) { $routingMatchResults = $componentContext->getParameter(RoutingComponent::class, 'matchResults'); if ($routingMatchResults !== NULL) { return; } $httpRequest = $componentContext->getHttpRequest(); $response = $this->redirectService->buildResponseIfApplicable($httpRequest); if ($response !== null) { $componentContext->replaceHttpResponse($response); $componentContext->setParameter(ComponentChain::class, 'cancel', true); } }
php
{ "resource": "" }
q1306
Menu.category
train
public function category() { $category = $this->param('category_id', 0); $categoryId = explode(':', $category)[0]; return Category::query()->findOrNew($categoryId); }
php
{ "resource": "" }
q1307
Menu.hasWidget
train
public function hasWidget($widget) { if ($widget instanceof Model) { $widget = $widget->id; } return $this->widgets()->where('widget_id', $widget)->exists(); }
php
{ "resource": "" }
q1308
WidgetPresenter.template
train
public function template() { return $this->entity->template === 'custom' ? $this->entity->custom_template : $this->entity->template; }
php
{ "resource": "" }
q1309
WidgetPresenter.class
train
public function class() { /** @var \Yajra\CMS\Repositories\Extension\Repository $repository */ $repository = app('extensions'); $extension = $repository->findOrFail($this->entity->extension_id); return $extension->param('class'); }
php
{ "resource": "" }
q1310
PermissionsController.create
train
public function create() { $permission = new Permission; $permission->resource = 'System'; $roles = Role::all(); return view('administrator.permissions.create', compact('permission', 'roles')); }
php
{ "resource": "" }
q1311
PermissionsController.store
train
public function store() { $this->validate($this->request, [ 'name' => 'required', 'resource' => 'required|alpha_num', 'slug' => 'required|unique:permissions,slug', ]); $permission = Permission::create($this->request->all()); $permission->syncRoles($this->request->get('roles', [])); return redirect()->route('administrator.permissions.index'); }
php
{ "resource": "" }
q1312
PermissionsController.storeResource
train
public function storeResource() { $this->validate($this->request, [ 'resource' => 'required|alpha_num', ]); $permissions = Permission::createResource($this->request->resource); foreach ($permissions as $permission) { $permission->syncRoles($this->request->get('roles', [])); } return redirect()->route('administrator.permissions.index'); }
php
{ "resource": "" }
q1313
PermissionsController.update
train
public function update(Permission $permission) { $this->validate($this->request, [ 'name' => 'required', 'resource' => 'required|alpha_num', 'slug' => 'required|unique:permissions,slug,' . $permission->id, ]); $permission->name = $this->request->get('name'); $permission->resource = $this->request->get('resource'); if (! $permission->system) { $permission->slug = $this->request->get('slug'); } $permission->save(); $permission->syncRoles($this->request->get('roles', [])); return redirect()->route('administrator.permissions.index'); }
php
{ "resource": "" }
q1314
PermissionsController.destroy
train
public function destroy(Permission $permission) { if (! $permission->system) { try { $permission->delete(); return $this->notifySuccess('Permission successfully deleted!'); } catch (QueryException $e) { return $this->notifyError($e->getMessage()); } } return $this->notifyError('System permission is protected and cannot be deleted!'); }
php
{ "resource": "" }
q1315
Number.fatorVencimento
train
public static function fatorVencimento(\DateTime $data) { $dataBase = new \DateTime("1997-10-07"); return (int)$data->diff($dataBase, true)->format('%r%a'); }
php
{ "resource": "" }
q1316
UsersController.index
train
public function index(UsersDataTable $dataTable) { $roles = $this->role->pluck('name', 'id'); return $dataTable->render('administrator.users.index', compact('roles')); }
php
{ "resource": "" }
q1317
UsersController.create
train
public function create() { $roles = $this->getAllowedRoles(); $selectedRoles = $this->request->old('roles'); $user = new User([ 'blocked' => 0, 'confirmed' => 1, ]); return view('administrator.users.create', compact('user', 'roles', 'selectedRoles')); }
php
{ "resource": "" }
q1318
UsersController.getAllowedRoles
train
protected function getAllowedRoles() { if ($this->request->user('administrator')->isRole('super-administrator')) { $roles = $this->role->newQuery()->get(); } else { $roles = $this->role->newQuery()->where('slug', '!=', 'super-administrator')->get(); } return $roles->pluck('name', 'id'); }
php
{ "resource": "" }
q1319
UsersController.store
train
public function store(StoreUserValidator $request) { $user = new User($request->all()); $user->password = bcrypt($request->get('password')); $user->is_activated = $request->get('is_activated', false); $user->is_blocked = $request->get('is_blocked', false); $user->is_admin = $request->get('is_admin', false); $user->save(); $user->syncRoles($request->get('roles')); event(new UserWasCreated($user)); flash()->success('User ' . $user->first_name . 'successfully created!'); return redirect()->route('administrator.users.index'); }
php
{ "resource": "" }
q1320
UsersController.edit
train
public function edit(User $user) { $roles = $this->getAllowedRoles(); $selectedRoles = $user->roles()->pluck('roles.id'); return view('administrator.users.edit', compact('user', 'roles', 'selectedRoles')); }
php
{ "resource": "" }
q1321
UsersController.destroy
train
public function destroy(User $user, $force = false) { if ($user->id <> auth('administrator')->id()) { try { if ($force) { $user->forceDelete(); } else { $user->delete(); } return $this->notifySuccess('User successfully deleted!'); } catch (QueryException $e) { return $this->notifyError($e->getMessage()); } } return $this->notifyError('You cannot delete your own record!'); }
php
{ "resource": "" }
q1322
UsersController.ban
train
public function ban(User $user) { $user->is_blocked = ! $user->is_blocked; $user->save(); if ($user->is_blocked) { return $this->notifySuccess('User ' . $user->name . ' blocked!'); } else { return $this->notifySuccess('User ' . $user->name . ' un-blocked!'); } }
php
{ "resource": "" }
q1323
UsersController.activate
train
public function activate(User $user) { $user->is_activated = ! $user->is_activated; $user->save(); if ($user->is_activated) { return $this->notifySuccess('User ' . $user->name . ' activated!'); } else { return $this->notifySuccess('User ' . $user->name . ' deactivated!'); } }
php
{ "resource": "" }
q1324
SiteSummaryExtension.updateAlerts
train
public function updateAlerts(&$alerts) { $securityWarnings = $this->owner->sourceRecords()->filter('SecurityAlerts.ID:GreaterThan', 0); if ($securityWarnings->exists()) { $alerts['SecurityAlerts'] = $securityWarnings->renderWith('SecurityAlertSummary'); } }
php
{ "resource": "" }
q1325
SearchController.show
train
public function show() { $keyword = request('q'); $articles = []; $limit = abs(request('limit', config('site.limit', 10))); $max_limit = config('site.max_limit', 100); if ($limit > $max_limit) { $limit = $max_limit; } if ($keyword) { $articles = $this->engine->search($keyword, $limit); $articles->appends('q', $keyword); $articles->appends('limit', $limit); } return view('search.show', compact('articles', 'keyword')); }
php
{ "resource": "" }
q1326
WidgetsController.create
train
public function create(Widget $widget) { $widget->extension_id = old('extension_id', Extension::WIDGET_WYSIWYG); $widget->template = old('template', 'widgets.wysiwyg.raw'); $widget->published = old('published', true); return view('administrator.widgets.create', compact('widget')); }
php
{ "resource": "" }
q1327
WidgetsController.store
train
public function store(WidgetFormRequest $request) { $widget = new Widget; $widget->fill($request->all()); $widget->published = $request->get('published', false); $widget->authenticated = $request->get('authenticated', false); $widget->show_title = $request->get('show_title', false); $widget->save(); $widget->syncPermissions($request->get('permissions', [])); $widget->syncMenuAssignment($request->get('menu', []), $request->get('assignment', Widget::ALL_PAGES)); flash()->success(trans('cms::widget.store.success')); return redirect()->route('administrator.widgets.index'); }
php
{ "resource": "" }
q1328
WidgetsController.edit
train
public function edit(Widget $widget) { $widget->type = old('type', $widget->type); $widget->template = old('template', $widget->template); return view('administrator.widgets.edit', compact('widget')); }
php
{ "resource": "" }
q1329
WidgetsController.templates
train
public function templates($type) { $data = []; $extension = $this->repository->findOrFail($type); foreach ($extension->param('templates') as $template) { $data[] = ['key' => $template['path'], 'value' => $template['description']]; } return response()->json([ 'template' => $data[0]['key'], 'selected' => $type, 'data' => $data, ], 200); }
php
{ "resource": "" }
q1330
WidgetsController.parameters
train
public function parameters($id, $widget) { $widget = Widget::withoutGlobalScope('menu_assignment')->findOrNew($widget); $extension = $this->repository->findOrFail($id); $formView = $extension->param('form'); if (view()->exists($formView)) { return view($formView, compact('widget')); } return view('widgets.partials.none'); }
php
{ "resource": "" }
q1331
CssToHTML.createStylesheetPaths
train
public function createStylesheetPaths(array $stylesheets) { $sheets = array(); foreach ($stylesheets as $key => $sheet) { if (!$this->isExternalStylesheet($sheet)) { // assetic version removal $sheet = str_replace(strrchr($sheet, 'css?'), 'css', $sheet); $sheet = $this->getBasePath() . $sheet; } $sheets[] = $sheet; } return $sheets; }
php
{ "resource": "" }
q1332
CssToHTML.getStylesheetContent
train
private function getStylesheetContent($path) { if ($this->isExternalStylesheet($path)) { $cssData = $this->getRequestHandler()->getContent($path); } else { if (file_exists($path)) { $cssData = file_get_contents($path); } else { return; } } $cssData = $this->replaceLocalUrlTags($cssData); return "<style type=\"text/css\">\n" . $cssData . '</style>'; }
php
{ "resource": "" }
q1333
SignPresenter.actionForgottenPassword
train
public function actionForgottenPassword(): void { $session = $this->getSession('cms/forgottenPassword'); if ($session->count >= self::MAX_TRY) { $this->flashNotifier->warning('cms.user.restorePasswordDisabledForHour'); $this->redirect(":{$this->module}:Sign:in"); } }
php
{ "resource": "" }
q1334
SignPresenter.signInFormSucceeded
train
public function signInFormSucceeded(Form $form, ArrayHash $values) { try { $this->user->login($values->username, $values->password); if ($values->remember) { $this->user->setExpiration('+ ' . $this->sessionExpiration, false); } else { $this->user->setExpiration('+ ' . $this->loginExpiration, true); } $this->restoreRequest($this->backlink); $this->redirect(":{$this->module}:Homepage:"); } catch (AuthenticationException $e) { if ($e->getCode() == IAuthenticator::NOT_APPROVED) { $form->addError('cms.user.accountDeactivated'); } else { $form->addError('cms.user.incorrectUsernameOrPassword'); } } }
php
{ "resource": "" }
q1335
SignPresenter.createComponentForgottenPasswordForm
train
protected function createComponentForgottenPasswordForm(): Form { $form = $this->formFactory->create(); $form->addProtection(); $form->addText('usernameOrEmail', 'cms.user.usernameOrEmail') ->setRequired(); $form->addSubmit('send', 'form.send'); $form->addLink('back', 'form.back', $this->link('in')); $form->onSuccess[] = [$this, 'forgottenPasswordFormSucceeded']; return $form; }
php
{ "resource": "" }
q1336
SignPresenter.forgottenPasswordFormSucceeded
train
public function forgottenPasswordFormSucceeded(Form $form, ArrayHash $values): void { $value = $values->usernameOrEmail; $user = $this->orm->users->getByUsername($value); if (!$user) { $user = $this->orm->users->getByEmail($value); if (!$user) { $form->addError('cms.user.incorrectUsernameOrEmail'); $session = $this->getSession('cms/forgottenPassword'); if (isset($session->count)) { $session->count++; } else { $session->setExpiration('1 hours'); $session->count = 1; } $this->actionForgottenPassword(); return; } } $hash = $this->hasher->hash(Random::generate()); $session = $this->getSession('cms/restorePassword'); $session->setExpiration('1 hours'); $session->$hash = $user->email; $this->mailer->sendRestorePassword($user->email, $hash); $this->flashNotifier->info('cms.user.mailToRestorePasswordSent'); $this->redirect(":{$this->module}:Sign:in"); }
php
{ "resource": "" }
q1337
SignPresenter.createComponentRestorePasswordForm
train
protected function createComponentRestorePasswordForm(): Form { $form = $this->formFactory->create(); $form->addProtection(); $form->addHidden('hash'); $form->addPassword('password', 'cms.user.newPassword') ->setRequired() ->addRule(Form::MIN_LENGTH, null, $this->minPasswordLength); $form->addPassword('passwordVerify', 'cms.user.passwordVerify') ->setRequired() ->addRule(Form::EQUAL, null, $form['password']); $form->addSubmit('restore', 'form.save'); $form->onSuccess[] = [$this, 'restorePasswordFormSucceeded']; return $form; }
php
{ "resource": "" }
q1338
SignPresenter.restorePasswordFormSucceeded
train
public function restorePasswordFormSucceeded(Form $form, ArrayHash $values): void { $session = $this->getSession('cms/restorePassword'); $email = $session->{$values->hash}; $session->remove(); $user = $this->orm->users->getByEmail($email); if ($user) { $user->setPassword($values->password); $this->orm->persistAndFlush($user); $this->flashNotifier->success('cms.user.passwordChanged'); } else { $this->flashNotifier->error('cms.permissions.accessDenied'); } $this->redirect(":{$this->module}:Sign:in"); }
php
{ "resource": "" }
q1339
SignPresenter.createComponentRegisterAdministratorForm
train
protected function createComponentRegisterAdministratorForm(): Form { $form = $this->formFactory->create(); $form->addProtection(); $form->addText('username', 'cms.user.username') ->setRequired(); $form->addText('firstName', 'cms.user.firstName'); $form->addText('surname', 'cms.user.surname'); $form->addText('email', 'cms.user.email') ->setRequired() ->addRule(Form::EMAIL); $form->addPassword('password', 'cms.user.newPassword') ->setRequired() ->addRule(Form::MIN_LENGTH, null, $this->minPasswordLength); $form->addPassword('passwordVerify', 'cms.user.passwordVerify') ->setRequired() ->addRule(Form::EQUAL, null, $form['password']); $form->addSubmit('create', 'form.save'); $form->onSuccess[] = [$this, 'registerAdministratorFormSucceeded']; return $form; }
php
{ "resource": "" }
q1340
SignPresenter.registerAdministratorFormSucceeded
train
public function registerAdministratorFormSucceeded(Form $form, ArrayHash $values): void { $password = $values->password; $role = $this->orm->aclRoles->getByName(AclRolesMapper::SUPERADMIN); $user = new User; $user->firstName = $values->firstName; $user->surname = $values->surname; $user->email = $values->email; $user->username = $values->username; $user->setPassword($password); $user->roles->add($role); $this->orm->persistAndFlush($user); $this->user->setExpiration('+ ' . $this->loginExpiration, true); $this->user->login($values->username, $password); $this->flashNotifier->success('cms.user.dataSaved'); $this->redirect(":{$this->module}:Homepage:"); }
php
{ "resource": "" }
q1341
Message.create
train
public function create(MessageCreateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $message = new MessageModel(); $message ->setDispatcher($dispatcher) ->setName($event->getMessageName()) ->setLocale($event->getLocale()) ->setTitle($event->getTitle()) ->setSecured($event->getSecured()) ->save() ; $event->setMessage($message); }
php
{ "resource": "" }
q1342
Message.modify
train
public function modify(MessageUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $message = MessageQuery::create()->findPk($event->getMessageId())) { $message ->setDispatcher($dispatcher) ->setName($event->getMessageName()) ->setSecured($event->getSecured()) ->setLocale($event->getLocale()) ->setTitle($event->getTitle()) ->setSubject($event->getSubject()) ->setHtmlMessage($event->getHtmlMessage()) ->setTextMessage($event->getTextMessage()) ->setHtmlLayoutFileName($event->getHtmlLayoutFileName()) ->setHtmlTemplateFileName($event->getHtmlTemplateFileName()) ->setTextLayoutFileName($event->getTextLayoutFileName()) ->setTextTemplateFileName($event->getTextTemplateFileName()) ->save(); $event->setMessage($message); } }
php
{ "resource": "" }
q1343
Message.delete
train
public function delete(MessageDeleteEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== ($message = MessageQuery::create()->findPk($event->getMessageId()))) { $message ->setDispatcher($dispatcher) ->delete() ; $event->setMessage($message); } }
php
{ "resource": "" }
q1344
ConditionAbstract.getValidators
train
public function getValidators() { $this->validators = $this->generateInputs(); $translatedInputs = []; foreach ($this->validators as $key => $validator) { $translatedOperators = []; foreach ($validator['availableOperators'] as $availableOperators) { $translatedOperators[$availableOperators] = Operators::getI18n( $this->translator, $availableOperators ); } $validator['availableOperators'] = $translatedOperators; $translatedInputs[$key] = $validator; } $validators = [ 'inputs' => $translatedInputs, 'setOperators' => $this->operators, 'setValues' => $this->values ]; return $validators; }
php
{ "resource": "" }
q1345
ConditionAbstract.getSerializableCondition
train
public function getSerializableCondition() { $serializableCondition = new SerializableCondition(); $serializableCondition->conditionServiceId = $this->getServiceId(); $serializableCondition->operators = $this->operators; $serializableCondition->values = $this->values; return $serializableCondition; }
php
{ "resource": "" }
q1346
ConditionAbstract.isCurrencyValid
train
protected function isCurrencyValid($currencyValue) { $availableCurrencies = $this->facade->getAvailableCurrencies(); /** @var Currency $currency */ $currencyFound = false; foreach ($availableCurrencies as $currency) { if ($currencyValue == $currency->getCode()) { $currencyFound = true; } } if (!$currencyFound) { throw new InvalidConditionValueException( \get_class(), 'currency' ); } return true; }
php
{ "resource": "" }
q1347
ConditionAbstract.isPriceValid
train
protected function isPriceValid($priceValue) { $floatType = new FloatType(); if (!$floatType->isValid($priceValue) || $priceValue <= 0) { throw new InvalidConditionValueException( \get_class(), 'price' ); } return true; }
php
{ "resource": "" }
q1348
ConditionAbstract.drawBackOfficeInputOperators
train
protected function drawBackOfficeInputOperators($inputKey) { $html = ''; $inputs = $this->getValidators(); if (isset($inputs['inputs'][$inputKey])) { $html = $this->facade->getParser()->render( 'coupon/condition-fragments/condition-selector.html', [ 'operators' => $inputs['inputs'][$inputKey]['availableOperators'], 'value' => isset($this->operators[$inputKey]) ? $this->operators[$inputKey] : '', 'inputKey' => $inputKey ] ); } return $html; }
php
{ "resource": "" }
q1349
ConditionAbstract.drawBackOfficeBaseInputsText
train
protected function drawBackOfficeBaseInputsText($label, $inputKey) { $operatorSelectHtml = $this->drawBackOfficeInputOperators($inputKey); $currentValue = ''; if (isset($this->values) && isset($this->values[$inputKey])) { $currentValue = $this->values[$inputKey]; } return $this->facade->getParser()->render( 'coupon/conditions-fragments/base-input-text.html', [ 'label' => $label, 'inputKey' => $inputKey, 'currentValue' => $currentValue, 'operatorSelectHtml' => $operatorSelectHtml ] ); }
php
{ "resource": "" }
q1350
ConditionAbstract.drawBackOfficeInputQuantityValues
train
protected function drawBackOfficeInputQuantityValues($inputKey, $max = 10, $min = 0) { return $this->facade->getParser()->render( 'coupon/condition-fragments/quantity-selector.html', [ 'min' => $min, 'max' => $max, 'value' => isset($this->values[$inputKey]) ? $this->values[$inputKey] : '', 'inputKey' => $inputKey ] ); }
php
{ "resource": "" }
q1351
ConditionAbstract.drawBackOfficeCurrencyInput
train
protected function drawBackOfficeCurrencyInput($inputKey) { $currencies = CurrencyQuery::create()->find(); $cleanedCurrencies = []; /** @var Currency $currency */ foreach ($currencies as $currency) { $cleanedCurrencies[$currency->getCode()] = $currency->getSymbol(); } return $this->facade->getParser()->render( 'coupon/condition-fragments/currency-selector.html', [ 'currencies' => $cleanedCurrencies, 'value' => isset($this->values[$inputKey]) ? $this->values[$inputKey] : '', 'inputKey' => $inputKey ] ); }
php
{ "resource": "" }
q1352
Notice.setClass
train
private function setClass( $name, $args ) { // Build the class string dynamically. $class = __NAMESPACE__ . '\\Notice\\' . ucfirst( $name ); // Create a new instance or add our filters. return $this->class = class_exists( $class ) ? new $class( $args ) : Filter::add( $this ); }
php
{ "resource": "" }
q1353
Notice.show
train
public static function show( $message, $id, $class = "notice notice-warning" ) { $nonce = wp_nonce_field( 'boldgrid_set_key', 'set_key_auth', true, false ); if( self::isDismissed( $id ) ) { return; } printf( '<div class="%1$s boldgrid-notice is-dismissible" data-notice-id="%2$s">%3$s%4$s</div>', $class, $id, $message, $nonce ); /* * Enqueue js required to allow for notices to be dismissed permanently. * * When notices (such as the "keyPrompt" notice) are shown by creating a new instance of * this class, the js is enqueued by the Filter::add call in the constructor. We do however * allow notices to be shown via this static method, and so we need to enqueue the js now. */ self::enqueue(); }
php
{ "resource": "" }
q1354
Notice.add
train
public function add( $name = null ) { $name = $name ? $name : $this->getName(); $path = __DIR__; $name = ucfirst( $name ); include "{$path}/Views/{$name}.php"; }
php
{ "resource": "" }
q1355
Notice.dismiss
train
public function dismiss() { // Validate nonce. if ( isset( $_POST['set_key_auth'] ) && check_ajax_referer( 'boldgrid_set_key', 'set_key_auth', false ) ) { $id = sanitize_key( $_POST['notice'] ); // Mark the notice as dismissed, if not already done so. $dismissal = array( 'id' => $id, 'timestamp' => time(), ); if ( ! Notice::isDismissed( $id ) ) { add_user_meta( get_current_user_id(), 'boldgrid_dismissed_admin_notices', $dismissal ); } } }
php
{ "resource": "" }
q1356
Notice.undismiss
train
public function undismiss() { // Validate nonce. if ( isset( $_POST['set_key_auth'] ) && ! empty( $_POST['notice'] ) && check_ajax_referer( 'boldgrid_set_key', 'set_key_auth', false ) ) { $id = sanitize_key( $_POST['notice'] ); // Get all of the notices this user has dismissed. $dismissals = get_user_meta( get_current_user_id(), 'boldgrid_dismissed_admin_notices' ); // Loop through all of the dismissed notices. If we find the dismissal, then remove it. foreach ( $dismissals as $dismissal ) { if ( $id === $dismissal['id'] ) { delete_user_meta( get_current_user_id(), 'boldgrid_dismissed_admin_notices', $dismissal ); break; } } } }
php
{ "resource": "" }
q1357
Notice.isDismissed
train
public static function isDismissed( $id ) { $dismissed = false; $id = sanitize_key( $id ); // Get all of the notices this user has dismissed. $dismissals = get_user_meta( get_current_user_id(), 'boldgrid_dismissed_admin_notices' ); // Loop through all of the dismissed notices. If we find our $id, then mark bool and break. foreach ( $dismissals as $dismissal ) { if ( $id === $dismissal['id'] ) { $dismissed = true; break; } } return $dismissed; }
php
{ "resource": "" }
q1358
CheckPermission.exec
train
public function exec() { if (version_compare(phpversion(), '5.5', '<')) { $this->validationMessages['php_version']['text'] = $this->getI18nPhpVersionText('5.5', phpversion(), false); $this->validationMessages['php_version']['status'] = false; $this->validationMessages['php_version']['hint'] = $this->getI18nPhpVersionHint(); } foreach ($this->directoriesToBeWritable as $directory) { $fullDirectory = THELIA_ROOT . $directory; $this->validationMessages[$directory]['text'] = $this->getI18nDirectoryText($fullDirectory, true); if (is_writable($fullDirectory) === false) { if (!$this->makeDirectoryWritable($fullDirectory)) { $this->isValid = false; $this->validationMessages[$directory]['status'] = false; $this->validationMessages[$directory]['text'] = $this->getI18nDirectoryText($fullDirectory, false); } } } foreach ($this->minServerConfigurationNecessary as $key => $value) { $this->validationMessages[$key]['text'] = $this->getI18nConfigText($key, $this->formatBytes($value), ini_get($key), true); if (!$this->verifyServerMemoryValues($key, $value)) { $this->isValid = false; $this->validationMessages[$key]['status'] = false; $this->validationMessages[$key]['text'] = $this->getI18nConfigText($key, $this->formatBytes($value), ini_get($key), false); ; } } foreach ($this->extensions as $extension) { $this->validationMessages[$extension]['text'] = $this->getI18nExtensionText($extension, true); if (false === extension_loaded($extension)) { $this->isValid = false; $this->validationMessages[$extension]['status'] = false; $this->validationMessages[$extension]['text'] = $this->getI18nExtensionText($extension, false); } } return $this->isValid; }
php
{ "resource": "" }
q1359
CheckPermission.getI18nDirectoryText
train
protected function getI18nDirectoryText($directory, $isValid) { if ($this->translator !== null) { if ($isValid) { $sentence = 'The directory %directory% is writable'; } else { $sentence = 'The directory %directory% is not writable'; } $translatedText = $this->translator->trans( $sentence, array( '%directory%' => $directory ) ); } else { $translatedText = sprintf('The directory %s should be writable', $directory); } return $translatedText; }
php
{ "resource": "" }
q1360
CheckPermission.getI18nConfigText
train
protected function getI18nConfigText($key, $expectedValue, $currentValue, $isValid) { if ($isValid) { $sentence = 'The PHP "%key%" configuration value (currently %currentValue%) is correct (%expectedValue% required).'; } else { $sentence = 'The PHP "%key%" configuration value (currently %currentValue%) is below minimal requirements to run Thelia2 (%expectedValue% required).'; } $translatedText = $this->translator->trans( $sentence, array( '%key%' => $key, '%expectedValue%' => $expectedValue, '%currentValue%' => $currentValue, ), 'install-wizard' ); return $translatedText; }
php
{ "resource": "" }
q1361
CheckPermission.getI18nPhpVersionText
train
protected function getI18nPhpVersionText($expectedValue, $currentValue, $isValid) { if ($this->translator !== null) { if ($isValid) { $sentence = 'PHP version %currentValue% matches the minimum required (PHP %expectedValue%).'; } else { $sentence = 'The installer detected PHP version %currentValue%, but Thelia 2 requires PHP %expectedValue% or newer.'; } $translatedText = $this->translator->trans( $sentence, array( '%expectedValue%' => $expectedValue, '%currentValue%' => $currentValue, ) ); } else { $translatedText = sprintf('Thelia requires PHP %s or newer (%s currently).', $expectedValue, $currentValue); } return $translatedText; }
php
{ "resource": "" }
q1362
CheckPermission.verifyServerMemoryValues
train
protected function verifyServerMemoryValues($key, $necessaryValueInBytes) { $serverValueInBytes = $this->returnBytes(ini_get($key)); if ($serverValueInBytes == -1) { return true; } return ($serverValueInBytes >= $necessaryValueInBytes); }
php
{ "resource": "" }
q1363
CheckPermission.returnBytes
train
protected function returnBytes($val) { $val = trim($val); $last = strtolower($val[strlen($val)-1]); // Do not add breaks in the switch below switch ($last) { // The 'G' modifier is available since PHP 5.1.0 case 'g': $val = (int)$val*1024; // no break case 'm': $val = (int)$val*1024; // no break case 'k': $val = (int)$val*1024; } return $val; }
php
{ "resource": "" }
q1364
MelisCmsRightsService.isActionButtonActive
train
public function isActionButtonActive($actionwanted) { $active = 0; $pathArrayConfig = ''; switch ($actionwanted) { case 'save' : $pathArrayConfig = 'meliscms_page_action_save'; break; case 'delete' : $pathArrayConfig = 'meliscms_page_action_delete'; break; case 'publish' : $pathArrayConfig = 'meliscms_page_action_publishunpublish'; break; case 'unpublish' : $pathArrayConfig = 'meliscms_page_action_publishunpublish'; break; } $melisAppConfig = $this->getServiceLocator()->get('MelisCoreConfig'); $melisKeys = $melisAppConfig->getMelisKeys(); $melisCoreAuth = $this->getServiceLocator()->get('MelisCoreAuth'); $xmlRights = $melisCoreAuth->getAuthRights(); $melisCoreRights = $this->getServiceLocator()->get('MelisCoreRights'); if (!empty($melisKeys[$pathArrayConfig])) { $isAccessible = $melisCoreRights->isAccessible($xmlRights, MelisCoreRightsService::MELISCORE_PREFIX_INTERFACE, $melisKeys[$pathArrayConfig]); if ($isAccessible) $active = 1; } return $active; }
php
{ "resource": "" }
q1365
RedisThrottler.trackMeter
train
protected function trackMeter($meterId, $buckets, $rates) { // create a key for this bucket's start time $trackKey = sprintf('track:%s', $buckets[0]); // track the meter key to this bucket with the number of times it was called $this->redis->hset($trackKey, $meterId, $rates[0]); // ensure this meter expires $expireAt = $buckets[0] + ($this->config['bucket_size'] * $this->config['num_buckets']); $this->redis->expireat($trackKey, $expireAt); }
php
{ "resource": "" }
q1366
Tax.afterTax
train
public static function afterTax($amount, Taxable $taxable) { return static::beforeTax( $taxable->getAmountWithoutTax(static::asMoney($amount)), $taxable ); }
php
{ "resource": "" }
q1367
Tax.getAmountWithTax
train
public function getAmountWithTax(): string { if (! $this->hasTax()) { return $this->getMoney()->getAmount(); } return $this->getTax()->getAmountWithTax($this->getMoney()); }
php
{ "resource": "" }
q1368
Tax.allocateWithTax
train
public function allocateWithTax(array $ratios): array { $method = $this->hasTax() ? 'afterTax' : 'withoutTax'; $results = []; $allocates = static::asMoney($this->getAmountWithTax())->allocate($ratios); foreach ($allocates as $allocate) { $results[] = static::{$method}($allocate->getAmount(), $this->getTax()); } return $results; }
php
{ "resource": "" }
q1369
Tax.allocateWithTaxTo
train
public function allocateWithTaxTo(int $n): array { $method = $this->hasTax() ? 'afterTax' : 'withoutTax'; $results = []; $allocates = static::asMoney($this->getAmountWithTax())->allocateTo($n); foreach ($allocates as $allocate) { $results[] = static::{$method}($allocate->getAmount(), $this->getTax()); } return $results; }
php
{ "resource": "" }
q1370
Lang.getDefaultLanguage
train
public static function getDefaultLanguage() { if (null === self::$defaultLanguage) { self::$defaultLanguage = LangQuery::create()->findOneByByDefault(1); if (null === self::$defaultLanguage) { throw new \RuntimeException("No default language is defined. Please define one."); } } return self::$defaultLanguage; }
php
{ "resource": "" }
q1371
MetaModelTags.convertValuesToIds
train
private function convertValuesToIds($varValue): array { $aliasColumn = $this->getAliasColumn(); $alias = []; foreach ($varValue as $valueId => $value) { if (array_key_exists($aliasColumn, $value)) { $alias[$valueId] = $value[$aliasColumn]; continue; } if (array_key_exists(self::TAGS_RAW, $value) && array_key_exists($aliasColumn, $value[self::TAGS_RAW])) { $alias[$valueId] = $value[self::TAGS_RAW][$aliasColumn]; } } return $alias; }
php
{ "resource": "" }
q1372
MetaModelTags.calculateFilterOptionsCount
train
protected function calculateFilterOptionsCount($items, &$amountArray, $idList) { $builder = $this ->getConnection() ->createQueryBuilder() ->select('value_id') ->addSelect('COUNT(item_id) AS amount') ->from('tl_metamodel_tag_relation') ->where('att_id=:attId') ->setParameter('attId', $this->get('id')) ->groupBy('value_id'); if (0 < $items->getCount()) { $ids = []; foreach ($items as $item) { $ids[] = $item->get('id'); } $builder ->andWhere('value_id IN (:valueIds)') ->setParameter('valueIds', $ids, Connection::PARAM_STR_ARRAY); if ($idList && \is_array($idList)) { $builder ->andWhere('item_id IN (:itemIds)') ->setParameter('itemIds', $idList, Connection::PARAM_STR_ARRAY); } } $counts = $builder->execute(); foreach ($counts->fetchAll(\PDO::FETCH_ASSOC) as $count) { $amountArray[$count['value_id']] = $count['amount']; } }
php
{ "resource": "" }
q1373
PositionManagementTrait.getNextPosition
train
public function getNextPosition() { $query = $this->createQuery() ->orderByPosition(Criteria::DESC) ->limit(1); $this->addCriteriaToPositionQuery($query); $last = $query->findOne(); return $last != null ? $last->getPosition() + 1 : 1; }
php
{ "resource": "" }
q1374
PositionManagementTrait.movePositionUpOrDown
train
protected function movePositionUpOrDown($up = true) { // The current position of the object $myPosition = $this->getPosition(); // Find object to exchange position with $search = $this->createQuery(); $this->addCriteriaToPositionQuery($search); // Up or down ? if ($up === true) { // Find the object immediately before me $search->filterByPosition(array('max' => $myPosition-1))->orderByPosition(Criteria::DESC); } else { // Find the object immediately after me $search->filterByPosition(array('min' => $myPosition+1))->orderByPosition(Criteria::ASC); } $result = $search->findOne(); // If we found the proper object, exchange their positions if ($result) { $cnx = Propel::getWriteConnection($this->getDatabaseName()); $cnx->beginTransaction(); try { $this ->setPosition($result->getPosition()) ->save($cnx) ; // For BC if (method_exists($result, 'setDispatcher') && method_exists($this, 'getDispatcher')) { $result->setDispatcher($this->getDispatcher()); } $result->setPosition($myPosition)->save($cnx); $cnx->commit(); } catch (\Exception $e) { $cnx->rollback(); } } }
php
{ "resource": "" }
q1375
PositionManagementTrait.changeAbsolutePosition
train
public function changeAbsolutePosition($newPosition) { // The current position $current_position = $this->getPosition(); if ($newPosition != null && $newPosition > 0 && $newPosition != $current_position) { // Find categories to offset $search = $this->createQuery(); $this->addCriteriaToPositionQuery($search); if ($newPosition > $current_position) { // The new position is after the current position -> we will offset + 1 all categories located between us and the new position $search->filterByPosition(array('min' => 1+$current_position, 'max' => $newPosition)); $delta = -1; } else { // The new position is brefore the current position -> we will offset - 1 all categories located between us and the new position $search->filterByPosition(array('min' => $newPosition, 'max' => $current_position - 1)); $delta = 1; } $results = $search->find(); $cnx = Propel::getWriteConnection($this->getDatabaseName()); $cnx->beginTransaction(); try { foreach ($results as $result) { $objNewPosition = $result->getPosition() + $delta; // For BC if (method_exists($result, 'setDispatcher') && method_exists($this, 'getDispatcher')) { $result->setDispatcher($this->getDispatcher()); } $result->setPosition($objNewPosition)->save($cnx); } $this ->setPosition($newPosition) ->save($cnx) ; $cnx->commit(); } catch (\Exception $e) { $cnx->rollback(); } } }
php
{ "resource": "" }
q1376
SchemaLocator.findForActiveModules
train
public function findForActiveModules() { $fs = new Filesystem(); $codes = $this->queryActiveModuleCodes(); foreach ($codes as $key => $code) { // test if the module exists on the file system if (!$fs->exists(THELIA_MODULE_DIR . $code)) { unset($codes[$key]); } } // reset keys $codes = array_values($codes); return $this->findForModules($codes); }
php
{ "resource": "" }
q1377
SchemaLocator.addModulesDependencies
train
protected function addModulesDependencies(array $modules = []) { if (empty($modules)) { return []; } // Thelia is always a dependency if (!\in_array('Thelia', $modules)) { $modules[] = 'Thelia'; } foreach ($modules as $module) { // Thelia is not a real module, do not try to get its dependencies if ($module === 'Thelia') { continue; } $moduleValidator = new ModuleValidator("{$this->theliaModuleDir}/{$module}"); $dependencies = $moduleValidator->getCurrentModuleDependencies(true); foreach ($dependencies as $dependency) { if (!\in_array($dependency['code'], $modules)) { $modules[] = $dependency['code']; } } } return $modules; }
php
{ "resource": "" }
q1378
SchemaLocator.addExternalSchemaDocuments
train
protected function addExternalSchemaDocuments(array $schemaDocuments) { $fs = new Filesystem(); $externalSchemaDocuments = []; foreach ($schemaDocuments as $schemaDocument) { /** @var \DOMElement $externalSchemaElement */ foreach ($schemaDocument->getElementsByTagName('external-schema') as $externalSchemaElement) { if (!$externalSchemaElement->hasAttribute('filename')) { continue; } $externalSchemaPath = $externalSchemaElement->getAttribute('filename'); if (!$fs->exists($externalSchemaPath)) { continue; } $externalSchemaDocument = new \DOMDocument(); if (!$externalSchemaDocument->load($externalSchemaPath)) { continue; } $externalSchemaDocuments[] = $externalSchemaDocument; } } return $this->mergeDOMDocumentsArrays([$schemaDocuments, $externalSchemaDocuments]); }
php
{ "resource": "" }
q1379
NotifyMeManager.reconnect
train
public function reconnect($name = null) { $name = $name ?: $this->default; $this->disconnect($name); return $this->connection($name); }
php
{ "resource": "" }
q1380
BaseAdminController.adminLogAppend
train
public function adminLogAppend($resource, $action, $message, $resourceId = null) { AdminLog::append( $resource, $action, $message, $this->getRequest(), $this->getSecurityContext()->getAdminUser(), true, $resourceId ); }
php
{ "resource": "" }
q1381
BaseAdminController.processTemplateAction
train
public function processTemplateAction($template) { try { if (! empty($template)) { // If we have a view in the URL, render this view return $this->render($template); } elseif (null != $view = $this->getRequest()->get('view')) { return $this->render($view); } } catch (\Exception $ex) { return $this->errorPage($ex->getMessage()); } return $this->pageNotFound(); }
php
{ "resource": "" }
q1382
BaseAdminController.errorPage
train
protected function errorPage($message, $status = 500) { if ($message instanceof \Exception) { $strMessage = $this->getTranslator()->trans( "Sorry, an error occured: %msg", [ '%msg' => $message->getMessage() ] ); Tlog::getInstance()->addError($strMessage.": ".$message->getTraceAsString()); $message = $strMessage; } else { Tlog::getInstance()->addError($message); } return $this->render( 'general_error', array( "error_message" => $message ), $status ); }
php
{ "resource": "" }
q1383
BaseAdminController.checkAuth
train
protected function checkAuth($resources, $modules, $accesses) { $resources = \is_array($resources) ? $resources : array($resources); $modules = \is_array($modules) ? $modules : array($modules); $accesses = \is_array($accesses) ? $accesses : array($accesses); if ($this->getSecurityContext()->isGranted(array("ADMIN"), $resources, $modules, $accesses)) { // Okay ! return null; } // Log the problem $this->adminLogAppend(implode(",", $resources), implode(",", $accesses), "User is not granted for resources %s with accesses %s", implode(", ", $resources), implode(", ", $accesses)); return $this->errorPage($this->getTranslator()->trans("Sorry, you're not allowed to perform this action"), 403); }
php
{ "resource": "" }
q1384
BaseAdminController.setupFormErrorContext
train
protected function setupFormErrorContext($action, $error_message, BaseForm $form = null, \Exception $exception = null) { if ($error_message !== false) { // Log the error message Tlog::getInstance()->error( $this->getTranslator()->trans( "Error during %action process : %error. Exception was %exc", array( '%action' => $action, '%error' => $error_message, '%exc' => $exception != null ? $exception->getMessage() : 'no exception' ) ) ); if ($form != null) { // Mark the form as errored $form->setErrorMessage($error_message); // Pass it to the parser context $this->getParserContext()->addForm($form); } // Pass the error message to the parser. $this->getParserContext()->setGeneralError($error_message); } }
php
{ "resource": "" }
q1385
BaseAdminController.getCurrentEditionCurrency
train
protected function getCurrentEditionCurrency() { // Return the new language if a change is required. if (null !== $edit_currency_id = $this->getRequest()->get('edit_currency_id', null)) { if (null !== $edit_currency = CurrencyQuery::create()->findOneById($edit_currency_id)) { return $edit_currency; } } // Otherwise return the lang stored in session. return $this->getSession()->getAdminEditionCurrency(); }
php
{ "resource": "" }
q1386
BaseAdminController.getCurrentEditionLang
train
protected function getCurrentEditionLang() { // Return the new language if a change is required. if (null !== $edit_language_id = $this->getRequest()->get('edit_language_id', null)) { if (null !== $edit_language = LangQuery::create()->findOneById($edit_language_id)) { return $edit_language; } } // Otherwise return the lang stored in session. return $this->getSession()->getAdminEditionLang(); }
php
{ "resource": "" }
q1387
BaseAdminController.getUrlLanguage
train
protected function getUrlLanguage($locale = null) { // Check if the functionality is activated if (!ConfigQuery::isMultiDomainActivated()) { return null; } // If we don't have a locale value, use the locale value in the session if (!$locale) { $locale = $this->getCurrentEditionLocale(); } return LangQuery::create()->findOneByLocale($locale)->getUrl(); }
php
{ "resource": "" }
q1388
BaseAdminController.getListOrderFromSession
train
protected function getListOrderFromSession($objectName, $requestParameterName, $defaultListOrder, $updateSession = true) { $orderSessionIdentifier = sprintf("admin.%s.currentListOrder", $objectName); // Find the current order $order = $this->getRequest()->get( $requestParameterName, $this->getSession()->get($orderSessionIdentifier, $defaultListOrder) ); if ($updateSession) { $this->getSession()->set($orderSessionIdentifier, $order); } return $order; }
php
{ "resource": "" }
q1389
ParameterTrait.appendParameter
train
public function appendParameter($parameter) { if (is_callable($parameter)) { $parameter = $parameter($this); } if (!($parameter instanceof ParameterNode)) { throw new \InvalidArgumentException(); } $this->parameters->appendItem($parameter); return $this; }
php
{ "resource": "" }
q1390
ParameterTrait.insertParameter
train
public function insertParameter(ParameterNode $parameter, $index) { $this->parameters->insertItem($parameter, $index); return $this; }
php
{ "resource": "" }
q1391
ParameterTrait.getParameter
train
public function getParameter($key) { if (is_string($key)) { return $this->getParameterByName($key); } elseif (is_integer($key)) { return $this->getParameterAtIndex($key); } else { throw new \InvalidArgumentException("Illegal parameter index {$key}."); } }
php
{ "resource": "" }
q1392
ParameterTrait.getParameterByName
train
public function getParameterByName($name) { $name = ltrim($name, '$'); /** @var ParameterNode $parameter */ foreach ($this->getParameters()->reverse() as $parameter) { if ($parameter->getName() === $name) { return $parameter; } } throw new \UnexpectedValueException("Parameter {$name} does not exist."); }
php
{ "resource": "" }
q1393
URL.getBaseUrl
train
public function getBaseUrl($scheme_only = false) { if (null === $this->baseUrlScheme) { $scheme = "http"; $port = 80; if ($host = $this->requestContext->getHost()) { $scheme = $this->requestContext->getScheme(); $port = ''; if ('http' === $scheme && 80 != $this->requestContext->getHttpPort()) { $port = ':'.$this->requestContext->getHttpPort(); } elseif ('https' === $scheme && 443 != $this->requestContext->getHttpsPort()) { $port = ':'.$this->requestContext->getHttpsPort(); } } $this->baseUrlScheme = "$scheme://$host"."$port"; } return $scheme_only ? $this->baseUrlScheme : $this->baseUrlScheme . $this->requestContext->getBaseUrl(); }
php
{ "resource": "" }
q1394
URL.adminViewUrl
train
public function adminViewUrl($viewName, array $parameters = array()) { $path = sprintf("%s/admin/%s", $this->getIndexPage(), $viewName); return $this->absoluteUrl($path, $parameters); }
php
{ "resource": "" }
q1395
URL.viewUrl
train
public function viewUrl($viewName, array $parameters = array()) { $path = sprintf("?view=%s", $viewName); return $this->absoluteUrl($path, $parameters); }
php
{ "resource": "" }
q1396
URL.retrieve
train
public function retrieve($view, $viewId, $viewLocale) { if (ConfigQuery::isRewritingEnable()) { $this->retriever->loadViewUrl($view, $viewLocale, $viewId); } else { $allParametersWithoutView = array(); $allParametersWithoutView['lang'] = $viewLocale; if (null !== $viewId) { $allParametersWithoutView[$view . '_id'] = $viewId; } $this->retriever->rewrittenUrl = null; $this->retriever->url = URL::getInstance()->viewUrl($view, $allParametersWithoutView); } return $this->retriever; }
php
{ "resource": "" }
q1397
URL.retrieveCurrent
train
public function retrieveCurrent(Request $request) { if (ConfigQuery::isRewritingEnable()) { $view = $request->attributes->get('_view', null); $viewLocale = $this->getViewLocale($request); $viewId = $view === null ? null : $request->query->get($view . '_id', null); $allOtherParameters = $request->query->all(); if ($view !== null) { unset($allOtherParameters['view']); if ($viewId !== null) { unset($allOtherParameters[$view . '_id']); } } if ($viewLocale !== null) { unset($allOtherParameters['lang']); unset($allOtherParameters['locale']); } $this->retriever->loadSpecificUrl($view, $viewLocale, $viewId, $allOtherParameters); } else { $allParametersWithoutView = $request->query->all(); $view = $request->attributes->get('_view'); if (isset($allOtherParameters['view'])) { unset($allOtherParameters['view']); } $this->retriever->rewrittenUrl = null; $this->retriever->url = URL::getInstance()->viewUrl($view, $allParametersWithoutView); } return $this->retriever; }
php
{ "resource": "" }
q1398
URL.getViewLocale
train
private function getViewLocale(Request $request) { $viewLocale = $request->query->get('lang', null); if (null === $viewLocale) { // fallback for old parameter $viewLocale = $request->query->get('locale', null); } return $viewLocale; }
php
{ "resource": "" }
q1399
OrderPostage.loadFromPostage
train
public static function loadFromPostage($postage) { if ($postage instanceof OrderPostage) { $orderPostage = $postage; } else { $orderPostage = new OrderPostage($postage); } return $orderPostage; }
php
{ "resource": "" }