_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q259400 | UserController.putActivate | test | public function putActivate($userId)
{
try {
$user = Sentry::getUserProvider()->findById($userId);
$activationCode = $user->getActivationCode();
$user->attemptActivation($activationCode);
} catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
return Response::json(array('deletedUser' => false, 'message' => trans('syntara::users.messages.not-found'), 'messageType' => 'danger'));
} catch (\Cartalyst\Sentry\Users\UserAlreadyActivatedException $e) {
return Response::json(array('deletedUser' => false, 'message' => trans('syntara::users.messages.activate-already'), 'messageType' => 'danger'));
}
return Response::json(array('deletedUser' => true, 'message' => trans('syntara::users.messages.activate-success'), 'messageType' => 'success'));
} | php | {
"resource": ""
} |
q259401 | UserController.getShow | test | public function getShow($userId)
{
try {
$user = Sentry::getUserProvider()->findById($userId);
$throttle = Sentry::getThrottleProvider()->findByUserId($userId);
$groups = Sentry::getGroupProvider()->findAll();
// get user permissions
$permissions = PermissionProvider::findAll();
$userPermissions = array();
foreach($user->getPermissions() as $permissionValue => $key) {
try {
$p = PermissionProvider::findByValue($permissionValue);
foreach($permissions as $key => $permission) {
if($p->getId() === $permission->getId()) {
$userPermissions[] = $permission;
unset($permissions[$key]);
}
}
} catch(\MrJuliuss\Syntara\Models\Permissions\PermissionNotFoundException $e){}
}
// ajax request : reload only content container
if(Request::ajax()) {
$html = View::make(Config::get('syntara::views.user-informations'), array('user' => $user, 'throttle' => $throttle))->render();
return Response::json(array('html' => $html));
}
$this->layout = View::make(Config::get('syntara::views.user-profile'), array(
'user' => $user,
'throttle' => $throttle,
'groups' => $groups,
'ownPermissions' => $userPermissions,
'permissions' => $permissions
));
$this->layout->title = $user->username;
$this->layout->breadcrumb = array(
array(
'title' => trans('syntara::breadcrumbs.users'),
'link' => URL::route('listUsers'),
'icon' => 'glyphicon-user'
),
array(
'title' => $user->username,
'link' => URL::current(),
'icon' => ''
)
);
} catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
$this->layout = View::make(Config::get('syntara::views.error'), array('message' => trans('syntara::users.messages.not-found')));
}
} | php | {
"resource": ""
} |
q259402 | GroupController.getIndex | test | public function getIndex()
{
$emptyGroup = Sentry::getGroupProvider()->createModel();
// Ajax search
$groupId = Input::get('groupIdSearch');
if(!empty($groupId)) {
$emptyGroup = $emptyGroup->where('id', $groupId);
}
$groupname = Input::get('groupnameSearch');
if(!empty($groupname)) {
$emptyGroup = $emptyGroup->where('name', 'LIKE', '%'.$groupname.'%');
}
$groups = $emptyGroup->paginate(Config::get('syntara::config.item-perge-page'));
// ajax: reload only the content container
if(Request::ajax()) {
$html = View::make(Config::get('syntara::views.groups-list'), array('groups' => $groups))->render();
return Response::json(array('html' => $html));
}
$this->layout = View::make(Config::get('syntara::views.groups-index'), array('groups' => $groups));
$this->layout->title = trans('syntara::groups.titles.list');
$this->layout->breadcrumb = Config::get('syntara::breadcrumbs.groups');
} | php | {
"resource": ""
} |
q259403 | GroupController.putShow | test | public function putShow($groupId)
{
$groupname = Input::get('groupname');
$permissions = array();
$errors = $this->_validateGroup(Input::get('permission'), $groupname, $permissions);
if(!empty($errors)) {
return Response::json(array('groupUpdated' => false, 'errorMessages' => $errors));
} else {
try {
$group = Sentry::getGroupProvider()->findById($groupId);
$group->name = $groupname;
$group->permissions = $permissions;
$permissions = (empty($permissions)) ? '' : json_encode($permissions);
// delete permissions in db
DB::table('groups')
->where('id', $groupId)
->update(array('permissions' => $permissions));
if($group->save()) {
return Response::json(array('groupUpdated' => true, 'message' => trans('syntara::groups.messages.success'), 'messageType' => 'success'));
} else {
return Response::json(array('groupUpdated' => false, 'message' => trans('syntara::groups.messages.try'), 'messageType' => 'danger'));
}
} catch (\Cartalyst\Sentry\Groups\NameRequiredException $e) {} catch (\Cartalyst\Sentry\Groups\GroupExistsException $e) {
return Response::json(array('groupUpdated' => false, 'message' => trans('syntara::groups.messages.exists'), 'messageType' => 'danger'));
}
}
} | php | {
"resource": ""
} |
q259404 | GroupController.deleteUserFromGroup | test | public function deleteUserFromGroup($groupId, $userId)
{
try {
$user = Sentry::getUserProvider()->findById($userId);
$group = Sentry::getGroupProvider()->findById($groupId);
$user->removeGroup($group);
return Response::json(array('userDeleted' => true, 'message' => trans('syntara::groups.messages.user-removed-success'), 'messageType' => 'success'));
} catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
return Response::json(array('userDeleted' => false, 'message' => trans('syntara::users.messages.not-found'), 'messageType' => 'danger'));
} catch(\Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
return Response::json(array('userDeleted' => false, 'message' => trans('syntara::groups.messages.not-found'), 'messageType' => 'danger'));
}
} | php | {
"resource": ""
} |
q259405 | GroupController.addUserInGroup | test | public function addUserInGroup()
{
try {
$user = Sentry::getUserProvider()->findById(Input::get('userId'));
$group = Sentry::getGroupProvider()->findById(Input::get('groupId'));
$user->addGroup($group);
return Response::json(array('userAdded' => true, 'message' => trans('syntara::groups.messages.user-add-success'), 'messageType' => 'success'));
} catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
return Response::json(array('userAdded' => false, 'message' => trans('syntara::users.messages.not-found'), 'messageType' => 'danger'));
} catch(\Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
return Response::json(array('userAdded' => false, 'message' => trans('syntara::groups.messages.not-found'), 'messageType' => 'danger'));
}
} | php | {
"resource": ""
} |
q259406 | GroupController._validateGroup | test | protected function _validateGroup($permissionsValues, $groupname, &$permissions)
{
$errors = array();
// validate permissions
if(!empty($permissionsValues)) {
foreach($permissionsValues as $key => $permission) {
$permissions[$key] = 1;
}
}
// validate group name
$validator = new GroupValidator(Input::all());
$gnErrors = array();
if(!$validator->passes()) {
$gnErrors = $validator->getErrors();
}
return $gnErrors;
} | php | {
"resource": ""
} |
q259407 | SyntaraServiceProvider.loadIncludes | test | private function loadIncludes()
{
// Add file names without the `php` extension to this list as needed.
$filesToLoad = array(
'composers',
'filters',
'routes',
);
// Run through $filesToLoad array.
foreach ($filesToLoad as $file) {
// Add needed database structure and file extension.
$file = __DIR__ . '/../../' . $file . '.php';
// If file exists, include.
if (is_file($file)) include $file;
}
} | php | {
"resource": ""
} |
q259408 | SyntaraServiceProvider.registerHelpers | test | public function registerHelpers()
{
// register breadcrumbs
$this->app['breadcrumbs'] = $this->app->share(function () {
return new \MrJuliuss\Syntara\Helpers\Breadcrumbs();
});
// shortcut so developers don't need to add an Alias in app/config/app.php
$this->app->booting(function () {
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Breadcrumbs', 'MrJuliuss\Syntara\Facades\Breadcrumbs');
});
} | php | {
"resource": ""
} |
q259409 | DashboardController.getIndex | test | public function getIndex()
{
$this->layout = View::make(Config::get('syntara::views.dashboard-index'));
$this->layout->title = trans('syntara::all.titles.index');
$this->layout->breadcrumb = Config::get('syntara::breadcrumbs.dashboard');
} | php | {
"resource": ""
} |
q259410 | DashboardController.postLogin | test | public function postLogin()
{
try {
$validator = new UserValidator(Input::all(), 'login');
$loginAttribute = Config::get('cartalyst/sentry::users.login_attribute');
if(!$validator->passes()) {
return Response::json(array('logged' => false, 'errorMessages' => $validator->getErrors()));
}
$credentials = array(
$loginAttribute => Input::get($loginAttribute),
'password' => Input::get('pass'),
);
// authenticate user
Sentry::authenticate($credentials, (bool)Input::get('remember'));
} catch(\Cartalyst\Sentry\Throttling\UserBannedException $e) {
return Response::json(array('logged' => false, 'errorMessage' => trans('syntara::all.messages.banned'), 'errorType' => 'danger'));
} catch (\RuntimeException $e) {
return Response::json(array('logged' => false, 'errorMessage' => trans('syntara::all.messages.login-failed'), 'errorType' => 'danger'));
}
return Response::json(array('logged' => true));
} | php | {
"resource": ""
} |
q259411 | PermissionController.getIndex | test | public function getIndex()
{
$permissions = PermissionProvider::createModel();
$permissionId = Input::get('permissionIdSearch');
if(!empty($permissionId)) {
$permissions = $permissions->where('id', $permissionId);
}
$permissionName = Input::get('permissionNameSearch');
if(!empty($permissionName)) {
$permissions = $permissions->where('name', 'LIKE', '%'.$permissionName.'%');
}
$permissionValue = Input::get('permissionValueSearch');
if(!empty($permissionValue)) {
$permissions = $permissions->where('value', 'LIKE', '%'.$permissionValue.'%');
}
$permissions = $permissions->paginate(Config::get('syntara::config.item-perge-page'));
// ajax request : reload only content container
if(Request::ajax()) {
$html = View::make(Config::get('syntara::views.permissions-list'), array('permissions' => $permissions))->render();
return Response::json(array('html' => $html));
}
$this->layout = View::make(Config::get('syntara::views.permissions-index'), array('permissions' => $permissions));
$this->layout->title = trans('syntara::permissions.titles.list');
$this->layout->breadcrumb = Config::get('syntara::breadcrumbs.permissions');
} | php | {
"resource": ""
} |
q259412 | PermissionController.postCreate | test | public function postCreate()
{
try {
$validator = new PermissionValidator(Input::all());
if(!$validator->passes()) {
return Response::json(array('permissionCreated' => false, 'errorMessages' => $validator->getErrors()));
}
// create permission
$permission = PermissionProvider::createPermission(Input::all());
} catch (\MrJuliuss\Syntara\Models\Permissions\NameRequiredException $e) {} catch (\MrJuliuss\Syntara\Models\Permissions\ValueRequiredException $e) {} catch (\MrJuliuss\Syntara\Models\Permissions\PermissionExistsException $e) {
return json_encode(array('permissionCreated' => false, 'message' => trans('syntara::permissions.messages.exists'), 'messageType' => 'danger'));
}
return json_encode(array('permissionCreated' => true, 'redirectUrl' => URL::route('listPermissions')));
} | php | {
"resource": ""
} |
q259413 | PermissionController.delete | test | public function delete($permissionId)
{
try {
$permission = PermissionProvider::findById($permissionId);
$permission->delete();
} catch (\MrJuliuss\Syntara\Models\Permissions\PermissionNotFoundException $e) {
return Response::json(array('deletePermission' => false, 'message' => trans('syntara::permissions.messages.not-found'), 'messageType' => 'danger'));
}
return Response::json(array('deletePermission' => true, 'message' => trans('syntara::permissions.messages.remove-success'), 'messageType' => 'success'));
} | php | {
"resource": ""
} |
q259414 | PdfView.paginate | test | private function paginate() {
$canvas = $this->pdf->get_canvas();
$c = array_merge($this->_pagination, $this->config['paginate']);
$canvas->page_text($c['x'], $c['y'], $c['text'], $c['font'], $c['size'], $c['color']);
} | php | {
"resource": ""
} |
q259415 | Permissions.authenticate | test | public function authenticate($username, $password)
{
$response = $this->post('Permissions.Authenticate', array(
'login' => $username,
'password' => $password,
));
return $this->returnResponse($response);
} | php | {
"resource": ""
} |
q259416 | Wsse.getNonce | test | protected function getNonce()
{
return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
mt_rand(0, 65535), mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 4095),
bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)
);
} | php | {
"resource": ""
} |
q259417 | OptionParser.__isset | test | public function __isset($flag)
{
try {
$this->checkFlag($flag);
} catch (\Exception $e) {
return false;
}
$ruleIndex = $this->_flags[$flag];
return isset($this->_options[$ruleIndex]);
} | php | {
"resource": ""
} |
q259418 | OptionParser.getRule | test | public function getRule($flag)
{
try {
$this->checkFlag($flag);
} catch (Exception $e) {
return null;
}
$ruleIndex = $this->_flags[$flag];
return $this->_rules[$ruleIndex];
} | php | {
"resource": ""
} |
q259419 | OptionParser.expectsParameter | test | public function expectsParameter($flag)
{
$rule = $this->getRule($flag);
return $rule && $rule['required'] !== self::PARAM_NOTREQUIRED;
} | php | {
"resource": ""
} |
q259420 | OptionParser.isRequired | test | public function isRequired($flag)
{
$rule = $this->getRule($flag);
return $rule && $rule['required'] === self::PARAM_REQUIRED;
} | php | {
"resource": ""
} |
q259421 | OptionParser.isOptional | test | public function isOptional($flag)
{
$rule = $this->getRule($flag);
return $rule && $rule['required'] === self::PARAM_OPTIONAL;
} | php | {
"resource": ""
} |
q259422 | OptionParser.parse | test | public function parse(array &$argv=null)
{
$this->_options = array();
if ($argv === null) {
if (isset($_SERVER['argv'])) {
$argv = $_SERVER['argv'];
} else {
$argv = array();
}
}
$this->_programName = array_shift($argv);
for ($i = 0; $i < count($argv); $i++) {
if (preg_match('/^(--?)([a-z][a-z\-]*)(?:=(.+)?)?$/i', $argv[$i], $matches)) {
if (isset($matches[3])) {
# put parameter back on stack of arguments
array_splice($argv, $i, 1, $matches[3]);
$paramGiven = true;
} else {
# throw away the flag
array_splice($argv, $i, 1);
$paramGiven = false;
}
$flag = $matches[2];
if ($this->_config & self::CONF_IGNORECASE) {
$flag = strtolower($flag);
}
if ($matches[1] == '--') {
# long flag
$this->parseOption($flag, $argv, $i, $paramGiven);
} else {
# short flag
foreach (str_split($flag) as $shortFlag) {
$this->parseOption($shortFlag, $argv, $i, $paramGiven);
}
}
# decrement the index for the flag that was taken
$i--;
} elseif ($argv[$i] == '--') {
if ($this->_config & self::CONF_DASHDASH) {
# stop processing arguments
break;
}
}
}
return $argv;
} | php | {
"resource": ""
} |
q259423 | OptionParser.isParam | test | protected function isParam($string)
{
if ($this->_config & self::CONF_DASHDASH && $string == '--') {
return false;
}
return !$this->isFlag($string);
} | php | {
"resource": ""
} |
q259424 | SoapClient.orderParameters | test | protected function orderParameters($parameters, $template)
{
foreach ($parameters as $key => $value) {
// if a parameter appears to be a nested type
if (is_array($value) && !empty($value) && !isset($value[0])) {
$parameters[$key] = $this->orderParameters($parameters[$key], $template[$key]);
}
}
$defaults = array();
foreach ($template as $key => $type) {
$defaults[$key] = null;
}
$parameters = array_merge(
$defaults,
$parameters
);
// ensure there are no extra parameters
$parameters = array_intersect_key($parameters, $template);
return $parameters;
} | php | {
"resource": ""
} |
q259425 | Client.authenticate | test | public function authenticate()
{
$auth = $this->getHttpClient()->getAuthService();
$args = func_get_args(); // php 5.2 requires this be on a separate line
call_user_func_array(array($auth, 'authenticate'), $args);
return $this;
} | php | {
"resource": ""
} |
q259426 | Client.getReportApi | test | public function getReportApi($options = array())
{
if(!isset($this->apis['report']))
{
$this->apis['report'] = new Api\Report($this, $options);
}
return $this->apis['report'];
} | php | {
"resource": ""
} |
q259427 | Client.getPermissionsApi | test | public function getPermissionsApi($options = array())
{
if(!isset($this->apis['permissions']))
{
$this->apis['permissions'] = new Api\Permissions($this, $options);
}
return $this->apis['permissions'];
} | php | {
"resource": ""
} |
q259428 | Client.getCompanyApi | test | public function getCompanyApi($options = array())
{
if(!isset($this->apis['company']))
{
$this->apis['company'] = new Api\Company($this, $options);
}
return $this->apis['company'];
} | php | {
"resource": ""
} |
q259429 | Client.getOAuthApi | test | public function getOAuthApi($options = array())
{
if(!isset($this->apis['oauth']))
{
$this->apis['oauth'] = new Api\OAuth($this, $options);
}
return $this->apis['oauth'];
} | php | {
"resource": ""
} |
q259430 | HttpClient.request | test | public function request($path, array $parameters = array(), $httpMethod = 'GET', array $options = array())
{
$options = array_merge($this->options, $options);
// create full url
$url = strtr($options['url'], array(
':api_version' => $this->options['api_version'],
':protocol' => $this->options['protocol'],
':endpoint' => $this->options['endpoint'],
':path' => $path
));
// get encoded response
$response = $this->doRequest($url, $parameters, $httpMethod, $options);
$this->lastResponse = $response; // for debugging (see getLastResponse)
// decode response
$response = $this->decodeResponse($response, $options);
return $response;
} | php | {
"resource": ""
} |
q259431 | Report.getElements | test | public function getElements($reportSuiteID, $returnAsIdArray = false)
{
$response = $this->post('Report.GetElements', array('reportSuiteID' => $reportSuiteID));
if ($returnAsIdArray) {
$filtered = array();
foreach ($response as $element) {
$filtered[$element['id']] = $element['name'];
}
return array_unique($filtered);
}
return $this->returnResponse($response);
} | php | {
"resource": ""
} |
q259432 | Report.getMetrics | test | public function getMetrics($reportSuiteID, $returnAsIdArray = false)
{
$response = $this->post('Report.GetMetrics', array('reportSuiteID' => $reportSuiteID));
if ($returnAsIdArray) {
$filtered = array();
foreach ($response as $metric) {
$filtered[$metric['id']] = $metric['name'];
}
return array_unique($filtered);
}
return $this->returnResponse($response);
} | php | {
"resource": ""
} |
q259433 | Report.retryWhileNotReady | test | protected function retryWhileNotReady($reportId)
{
$attempts = 0;
do {
$report = $this->post('Report.Get', array(
'reportID' => $reportId,
));
$sleep = $this->getSleepSeconds(++$attempts, 50);
if ($sleep !== false) {
sleep($sleep);
}
} while (isset($report['error']) && $report['error'] == 'report_not_ready');
if (isset($report['report'])) {
$report = $report['report'];
} else {
throw new ReportError($report['error_description'], null);
}
return $report;
} | php | {
"resource": ""
} |
q259434 | Report.getSleepSeconds | test | protected function getSleepSeconds($attempts, $maxAttempts = null)
{
if ($maxAttempts && $attempts >= $maxAttempts) {
return false;
}
// very complex.
return $attempts * $attempts;
} | php | {
"resource": ""
} |
q259435 | PixabayClient.parseOptions | test | private function parseOptions(array $options, $resetOptions = false)
{
foreach ($this->optionsList as $option) {
if (isset($options[$option])) {
$this->options[$option] = $options[$option];
} elseif ($resetOptions && isset($this->options[$option])) {
unset($this->options[$option]);
}
}
} | php | {
"resource": ""
} |
q259436 | PixabayClient.get | test | public function get(array $options = [], $returnObject = false, $resetOptions = false, $segment = self::SEGMENT_IMAGES)
{
$this->parseOptions($options, $resetOptions);
$response = $this->client->request('GET', self::API_ROOT . $segment, ['query' => $this->options]);
$data = $response->getBody()->getContents();
return json_decode($data, $returnObject);
} | php | {
"resource": ""
} |
q259437 | PixabayClient.getImages | test | public function getImages(array $options = [], $returnObject = false, $resetOptions = false)
{
return $this->get($options, $returnObject, $resetOptions, self::SEGMENT_IMAGES);
} | php | {
"resource": ""
} |
q259438 | PixabayClient.getVideos | test | public function getVideos(array $options = [], $returnObject = false, $resetOptions = false)
{
return $this->get($options, $returnObject, $resetOptions, self::SEGMENT_VIDEOS);
} | php | {
"resource": ""
} |
q259439 | AbstractOutput.stdout | test | public static function stdout($string)
{
$args = func_get_args();
array_shift($args);
if (empty($args)) {
return Console::stdout($string);
}
$string = Console::ansiFormat($string, $args);
return Console::stdout($string);
} | php | {
"resource": ""
} |
q259440 | Schema.getTable | test | public function getTable(TableSchema $table, $indent = 0)
{
$definition =
$this->getCreateTable($table->name, $indent)
. $this->getColumns($table->columns, $indent + 1)
. $this->getTableOptions($table, $indent)
;
return $definition;
} | php | {
"resource": ""
} |
q259441 | Schema.getDropTable | test | public function getDropTable(TableSchema $table, $indent = 0)
{
// Do not run this sql: "drop table `tableName`", it will drop the table that has exists before running "./yii migrate"
$textIndent = $this->textIndent($indent);
$tableName = static::removePrefix($table->name, $this->db->tablePrefix);
$definition = <<<DEFINITION
{$textIndent}foreach (\$this->runSuccess as \$keyName => \$value) {
{$textIndent} if ('createTable' === \$keyName) {
{$textIndent} \$this->dropTable('{{%$tableName}}');
{$textIndent} } elseif ('addTableComment' === \$keyName) {
{$textIndent} \$this->dropCommentFromTable('{{%$tableName}}');
{$textIndent} } else {
{$textIndent} throw new \yii\db\Exception('only support "dropTable" and "dropCommentFromTable"');
{$textIndent} }
{$textIndent}}
DEFINITION;
return $definition;
} | php | {
"resource": ""
} |
q259442 | Schema.getDropTableData | test | public function getDropTableData(TableSchema $table, $indent = 0)
{
// Do not use "truncate tableName", it will delete all data of table, include data before you run "./yii migrate" commond
$definition = $this->textIndent($indent);
$definition .= "\$this->_transaction->rollBack();";
$definition .= self::ENTER;
return $definition;
} | php | {
"resource": ""
} |
q259443 | Schema.getKey | test | public function getKey(TableSchema $table, $indent = 0)
{
$definition = '';
$textIndent = $this->textIndent($indent);
$tablePrefix = $this->db->tablePrefix;
$tableName = static::removePrefix($table->name, $tablePrefix);
$data = $this->db->createCommand('SHOW KEYS FROM ' . $table->name)->queryAll();
if (empty($data)) {
return '';
}
// 获取索引数据,包括主键
$keyData = [];
foreach ($data as $value) {
$keyName = static::removePrefix($value['Key_name'], $tablePrefix);
if (empty($keyData[$keyName])) {
$keyData[$keyName] = [];
}
array_push($keyData[$keyName], [
'table' => $value['Table'],
'is_unique' => $value['Non_unique'] ? 0 : 1,
'column_name' => $value['Column_name'],
'allow_null' => $value['Null'],
'comment' => $value['Comment'],
'index_comment' => $value['Index_comment'],
]);
}
foreach ($keyData as $keyName => $value) {
$columns = implode(',', array_column($value,'column_name'));
$definition .= $textIndent;
$definition .= "\$this->runSuccess['$keyName'] = "; // record which key add successfully
// primary key
if ('PRIMARY' === $keyName) {
$definition .= "\$this->addPrimaryKey(null, '{{%$tableName}}', '$columns');" . self::ENTER;
foreach ($keyData['PRIMARY'] as $column) {
$column = $column['column_name']; // table column name
// auto_increment
if ($table->columns[$column]->autoIncrement) {
$columnType = $table->columns[$column]->type;
$property = $table->columns[$column]->unsigned ? 'unsigned' : '';
$auto_increment = $this->getAutoIncrementNumber($table->name);
$definition .= $textIndent;
$definition .= "\$this->runSuccess['addAutoIncrement'] = ";
$definition .= "\$this->addAutoIncrement('{{%$tableName}}', '$column', '$columnType', '$property', $auto_increment);" . self::ENTER;
}
}
} else {
// other keys except primary key
$isUnique = $value[0]['is_unique'];
$definition .= "\$this->createIndex('$keyName', '{{%$tableName}}', '$columns', {$isUnique});" . self::ENTER;
}
}
return $definition;
} | php | {
"resource": ""
} |
q259444 | Schema.getDropKey | test | public function getDropKey(TableSchema $table, $indent = 0)
{
$textIndent = $this->textIndent($indent);
$tableName = static::removePrefix($table->name, $this->db->tablePrefix);
$definition = <<<DEFINITION
{$textIndent}foreach (\$this->runSuccess as \$keyName => \$value) {
{$textIndent} if ('addAutoIncrement' === \$keyName) {
{$textIndent} continue;
{$textIndent} } elseif ('PRIMARY' === \$keyName) {
{$textIndent} // must be remove auto_increment before drop primary key
{$textIndent} if (isset(\$this->runSuccess['addAutoIncrement'])) {
{$textIndent} \$value = \$this->runSuccess['addAutoIncrement'];
{$textIndent} \$this->dropAutoIncrement("{\$value['table_name']}", \$value['column_name'], \$value['column_type'], \$value['property']);
{$textIndent} }
{$textIndent} \$this->dropPrimaryKey(null, '{{%{$tableName}}}');
{$textIndent} } elseif (!empty(\$keyName)) {
{$textIndent} \$this->dropIndex("`\$keyName`", '{{%{$tableName}}}');
{$textIndent} }
{$textIndent}}
DEFINITION;
return $definition . self::ENTER;
} | php | {
"resource": ""
} |
q259445 | Schema.getFK | test | public function getFK(TableSchema $table, $indent = 0)
{
if (empty($table->foreignKeys)) {
return '';
}
$string = $this->db->createCommand("SHOW CREATE TABLE {$table->name}")->queryAll();
$onParams = $this->FKOnParams($string[0]['Create Table']);
$textIndent = $this->textIndent($indent);
$definition = $textIndent;
$definition .= '$tablePrefix = \Yii::$app->getDb()->tablePrefix;' . self::ENTER;
$tableName = static::removePrefix($table->name, $this->db->tablePrefix);
foreach ($table->foreignKeys as $fkName => $fk) {
$refTable = '';
$refColumns = '';
$columns = '';
$delete = isset($onParams[$fkName]['ON DELETE']) ? "'{$onParams[$fkName]['ON DELETE']}'" : 'null';
$update = isset($onParams[$fkName]['ON UPDATE']) ? "'{$onParams[$fkName]['ON UPDATE']}'" : 'null';
$fkName = static::removePrefix($fkName, $this->db->tablePrefix);
foreach ($fk as $k => $v) {
if (0 === $k) {
$refTable = $v;
} else {
$columns = $k;
$refColumns = $v;
}
}
$definition .= $textIndent;
$definition .= "\$this->runSuccess[\$tablePrefix.'{$fkName}'] = ";
$definition .= sprintf(
"\$this->addForeignKey(\$tablePrefix.'%s', '{{%%%s}}', '%s', '{{%%%s}}', '%s', %s, %s);" . self::ENTER,
$fkName, // 外健名称
$tableName, // 表名
$columns, // 列名
static::removePrefix($refTable, $this->db->tablePrefix), // 对应外健的表名
$refColumns, // 对应外健的列名
$delete, // ON DELETE
$update // ON UPDATE
);
}
return $definition;
} | php | {
"resource": ""
} |
q259446 | Schema.getDropFK | test | public function getDropFK(TableSchema $table, $indent = 0)
{
if (empty($table->foreignKeys)) {
return '';
}
$textIndent = $this->textIndent($indent);
$tableName = static::removePrefix($table->name, $this->db->tablePrefix);
$definition = <<<DEFINITION
{$textIndent}foreach (\$this->runSuccess as \$keyName => \$value) {
{$textIndent} \$this->dropForeignKey(\$keyName, '{{%$tableName}}');
{$textIndent}}
DEFINITION;
return $definition . self::ENTER;
} | php | {
"resource": ""
} |
q259447 | Schema.getColumns | test | public function getColumns(array $columns, $indent = 0)
{
$definition = '';
$textIndent = $this->textIndent($indent);
foreach ($columns as $column) {
$tmp = sprintf("'%s' => \$this->%s%s," . self::ENTER,
$column->name, static::getSchemaType($column), static::other($column));
if (null !== $column->enumValues) {
$tmp = static::replaceEnumColumn($tmp);
}
$definition .= $textIndent . $tmp; // 处理缩进问题
}
return $definition;
} | php | {
"resource": ""
} |
q259448 | Schema.getPrimaryKey | test | public function getPrimaryKey(array $pk, array $columns, $indent = 0)
{
if (empty($pk)) {
return '';
}
// Composite primary keys
if (2 <= count($pk)) {
$compositePk = implode(', ', $pk);
return $this->textIndent($indent) . "'PRIMARY KEY ($compositePk)'," . self::ENTER;
}
// Primary key not an auto-increment
$flag = false;
foreach ($columns as $column) {
if ($column->autoIncrement) {
$flag = true;
}
}
if (false === $flag) {
return $this->textIndent($indent) . sprintf("'PRIMARY KEY (%s)'," . self::ENTER, $pk[0]);
}
return '';
} | php | {
"resource": ""
} |
q259449 | Schema.getTableComment | test | public function getTableComment(TableSchema $table, $indent = 0)
{
if (null === $this->_tableStatus) {
try {
// 不知 “SHOW TABLE STATUS” sql语句在其他数据库中是否会执行成功,所以用try catch捕获异常
$this->_tableStatus = $this->db->createCommand('SHOW TABLE STATUS')->queryAll();
} catch (\Exception $e) {
return '';
}
}
$textIndent = $this->textIndent($indent);
$definition = $textIndent . '$this->runSuccess[\'addTableComment\'] = ';
$tableName = static::removePrefix($table->name, $this->db->tablePrefix);
foreach ($this->_tableStatus as $value) {
if ($table->name === $value['Name'] && ! empty($value['Comment'])) {
$comment = addslashes($value['Comment']);
return $definition . "\$this->addCommentOnTable('{{%$tableName}}', '{$comment}');";
}
}
return '';
} | php | {
"resource": ""
} |
q259450 | Schema.getSchemaType | test | public static function getSchemaType(ColumnSchema $column)
{
// boolean
if ('tinyint(1)' === $column->dbType) {
return 'boolean()';
}
// enum
if (null !== $column->enumValues) {
// https://github.com/yiisoft/yii2/issues/9797
$enumValues = array_map('addslashes', $column->enumValues);
return "enum(['".implode('\', \'', $enumValues)."'])";
}
switch ($column->type) {
case 'smallint':
$type = 'smallInteger';
break;
case 'int':
$type = 'integer';
break;
case 'bigint':
$type = 'bigInteger';
break;
default:
$type = $column->type;
break;
}
// others
if (null === $column->size) {
return "$type()";
} else {
return "{$type}({$column->size})";
}
} | php | {
"resource": ""
} |
q259451 | Schema.other | test | public static function other(ColumnSchema $column)
{
$definition = '';
// unsigned
if ($column->unsigned) {
$definition .= '->unsigned()';
}
// null
if ($column->allowNull) {
$definition .= '->null()';
} else {
$definition .= '->notNull()';
}
// default value
if ($column->defaultValue instanceof Expression) {
$definition .= "->defaultExpression('$column->defaultValue')";
} elseif (is_int($column->defaultValue)) {
$definition .= "->defaultValue($column->defaultValue)";
} elseif (is_bool($column->defaultValue)) {
$definition .= '->defaultValue('.var_export($column->defaultValue, true).')';
} elseif (is_string($column->defaultValue)) {
$definition .= "->defaultValue('".addslashes($column->defaultValue)."')";
}
// comment
if (null !== $column->comment && '' !== $column->comment) {
$definition .= "->comment('".addslashes($column->comment)."')";
}
// append
return $definition;
} | php | {
"resource": ""
} |
q259452 | DumpController.actionList | test | public function actionList()
{
$tableList = $this->schema->getTableList($this->db, $this->sparactor) . "\n";
return $this->output->stdout($tableList, 0, Console::FG_YELLOW);
} | php | {
"resource": ""
} |
q259453 | DumpController.actionGenerate | test | public function actionGenerate()
{
$this->output->startPrintf('Process');
$tableOptions = $this->getOptions($this->table);
$filterOptions = $this->getOptions($this->filter);
$info = Yii::t('dump', 'Generate Migration File');
foreach ($this->db->getSchema()->getTableSchemas() as $table) {
// filter some table -filter=... -table=...
if ($this->filterTable($table->name, $filterOptions, $tableOptions)) {
continue;
}
switch ($this->type) {
case '0':
$this->generateFile($table, 'table', $info, 2);
break;
case '1':
$this->generateFile($table, 'tableData', $info, 2);
break;
case '2':
$this->generateFile($table, 'key', $info, 2);
break;
case '3':
$this->generateFile($table, 'FK', $info, 2);
break;
default:
$this->generateFile($table, 'table', $info, 2);
$this->generateFile($table, 'tableData', $info, 2);
$this->generateFile($table, 'key', $info, 2);
$this->generateFile($table, 'FK', $info, 2);
break;
}
}
$this->output->conclusion($this->generations, $this->filters);
$this->output->endPrintf('Process');
return 0;
} | php | {
"resource": ""
} |
q259454 | DumpController.actionCreate | test | public function actionCreate()
{
$this->output->startPrintf('Process');
$tableOptions = $this->getOptions($this->table);
$filterOptions = $this->getOptions($this->filter);
$createTableInfo = Yii::t('dump', 'Create Table');
$insertDataInfo = Yii::t('dump', 'Insert Data Of Table');
$addKeyInfo = Yii::t('dump', 'Add Key Of Table');
$addFKInfo = Yii::t('dump', 'Add Foreign Key Of Table');
foreach ($this->db->getSchema()->getTableSchemas() as $table) {
// filter some table -filter=... -table=...
if ($this->filterTable($table->name, $filterOptions, $tableOptions)) {
continue;
}
switch ($this->type) {
case '0':
$this->printf($table, 'table', $createTableInfo);
break;
case '1':
$this->printf($table, 'tableData', $insertDataInfo);
break;
case '2':
$this->printf($table, 'key', $addKeyInfo);
break;
case '3':
$this->printf($table, 'FK', $addFKInfo); // foreign key
break;
default:
$this->printf($table, 'table', $createTableInfo);
$this->printf($table, 'tableData', $insertDataInfo);
$this->printf($table, 'key', $addKeyInfo);
$this->printf($table, 'FK', $addFKInfo); // foreign key
break;
}
}
$this->output->conclusion($this->generations, $this->filters);
$this->output->endPrintf('Process');
return 0;
} | php | {
"resource": ""
} |
q259455 | DumpController.actionDrop | test | public function actionDrop()
{
$this->output->startPrintf('Process');
$tableOptions = $this->getOptions($this->table);
$filterOptions = $this->getOptions($this->filter);
$dropTableInfo = Yii::t('dump', 'Drop Table');
$dropDataInfo = Yii::t('dump', 'Drop Data Of Table');
$dropKeyInfo = Yii::t('dump', 'Drop Key Of Table');
$dropFKInfo = Yii::t('dump', 'Drop Foreign Key Of Table');
foreach ($this->db->getSchema()->getTableSchemas() as $table) {
// filter some table -filter=... -table=...
if ($this->filterTable($table->name, $filterOptions, $tableOptions)) {
continue;
}
switch ($this->type) {
case '0':
$this->printf($table, 'dropTable', $dropTableInfo);
break;
case '1':
$this->printf($table, 'dropTableData', $dropDataInfo);
break;
case '2':
$this->printf($table, 'dropKey', $dropKeyInfo);
break;
case '3':
$this->printf($table, 'dropFK', $dropFKInfo); // foreign key
break;
default:
$this->printf($table, 'dropTable', $dropTableInfo);
$this->printf($table, 'dropTableData', $dropDataInfo);
$this->printf($table, 'dropKey', $dropKeyInfo);
$this->printf($table, 'dropFK', $dropFKInfo); // foreign key
break;
}
}
$this->output->conclusion($this->generations, $this->filters);
$this->output->endPrintf('Process');
return 0;
} | php | {
"resource": ""
} |
q259456 | DumpController.generateFile | test | public function generateFile(TableSchema $table, $functionName, $tip = null, $indent = 0)
{
$params = $this->getParams($table, $functionName, $indent);
if (
empty($params['safeUp']) ||
empty($params['safeDown']) ||
empty($params['className'])
) {
return false;
}
$template = Yii::getAlias($this->templateFile);
$outputFile = Yii::getAlias($this->generateFilePath) . DIRECTORY_SEPARATOR . $params['className'] . '.php';
if (! empty($tip)) {
$this->output->startPrintf($tip); // record start time
$this->output->stdout($outputFile . "\n");
$rst = $this->output->generateFile($params, $template, $outputFile);
$this->output->endPrintf($tip); // record end time
} else {
$this->output->stdout($outputFile);
$rst = $this->output->generateFile($params, $template, $outputFile);
}
return $rst;
} | php | {
"resource": ""
} |
q259457 | DumpController.printf | test | public function printf(TableSchema $table, $functionName, $tip = null, $indent = 0)
{
$params = [];
$params[] = &$table;
$params[] = $indent;
$functionName = ucfirst($functionName);
$functionName = 'get' . $functionName;
if ('getTableData' === $functionName) {
if ($limit = $this->checkLimit($table->name)) {
array_pop($params);
$params[] = $limit;
$params[] = $indent;
} else {
return 0;
}
}
if (! $data = call_user_func_array([$this->schema, $functionName], $params)) {
return 0;
}
if (! empty($tip)) {
$tip .= ': ' . $this->schema->removePrefix($table->name, $this->db->tablePrefix);
$this->output->startPrintf($tip); // record start time
$this->output->stdout($data);
$this->output->endPrintf($tip); // record end time
} else {
$this->output->stdout($data);
}
return 0;
} | php | {
"resource": ""
} |
q259458 | DumpController.getParams | test | public function getParams(TableSchema $table, $functionName, $indent = 0)
{
$params = [];
$params[] = &$table;
$params[] = $indent;
$ucFunctionName = ucfirst($functionName);
$get = 'get' . $ucFunctionName;
$drop = 'getDrop' . $ucFunctionName;
$order = $this->changeOrderOfApplyingFile($functionName);
if ('getTableData' === $get) {
if ($limit = $this->checkLimit($table->name)) {
array_pop($params);
$params[] = $limit;
$params[] = $indent;
} else {
return [];
}
}
$safeUp = call_user_func_array([$this->schema, $get], $params);
if (3 === count($params)) {
unset($params[1]); // unser $this->limit
}
$safeDown = call_user_func_array([$this->schema, $drop], $params);
$tableName = $this->schema->removePrefix($table->name, $this->db->tablePrefix);
return [
'safeUp' => $safeUp ? "\n" . $safeUp . "\n" : '',
'safeDown' => $safeDown ? "\n" . $safeDown . "\n" : '',
'className' => static::getClassName($order . '_' . $functionName . '_' . $tableName, $this->filePrefix),
];
} | php | {
"resource": ""
} |
q259459 | Output.startPrintf | test | public function startPrintf($string)
{
if (empty($string)) {
return '';
}
$this->startTime[$string] = microtime(true);
$this->stdout('/*** Begin '. $string . " ***/" . self::ENTER, 0, Console::FG_YELLOW);
return 0;
} | php | {
"resource": ""
} |
q259460 | Output.endPrintf | test | public function endPrintf($string)
{
if (empty($string)) {
return '';
}
$this->endTime[$string] = microtime(true);
$time = $this->endTime[$string] - $this->startTime[$string];
$this->stdout(
'/*** End ' . $string . ' ... done (time: ' . sprintf("%.3f", $time) . "s) ***/" . self::ENTER . self::ENTER,
0,
Console::FG_GREEN
);
return 0;
} | php | {
"resource": ""
} |
q259461 | Output.conclusion | test | public function conclusion($handleTable, $filterTable)
{
$enter = self::ENTER;
$handleNumber = count($handleTable);
$filterNumber = count($filterTable);
$handleTableString = implode($handleTable, ', ');
$filterTableString = implode($filterTable, ', ');
$tables = Yii::t('dump', 'Tables');
$handle = Yii::t('dump', 'Handle');
$filter = Yii::t('dump', 'Filter');
$header = <<<HEADER
/**********************************/
/************ Conclusion **********/
/**********************************/
HEADER;
$footer = <<<FOOTER
/************ Conclusion *********/$enter
FOOTER;
$handle = <<<HANDLE
/*** $handle $handleNumber $tables: */
>>> $handleTableString$enter
HANDLE;
$filter = <<<FILTER
/*** $filter $filterNumber $tables: */
>>> $filterTableString
FILTER;
$this->stdout($header, 0, Console::FG_YELLOW);
$this->stdout($handle, Console::BOLD, Console::FG_YELLOW);
$this->stdout($filter, Console::BOLD, Console::FG_YELLOW);
$this->stdout($footer, 0, Console::FG_GREEN);
} | php | {
"resource": ""
} |
q259462 | Webservices._Fetch | test | private function _Fetch() {
$this->_setWebservicesUrl();
$response = @file_get_contents($this->getWebservicesUrl());
$this->response = $response;
} | php | {
"resource": ""
} |
q259463 | Webservices._Populate | test | private function _Populate() {
$this->data = json_decode($this->response);
// getStatus() FALSE upon receiving status ERR or a non-zero error
// else set as TRUE
if (is_array($this->data->data)) {
$this->status = TRUE;
} else {
if (isset($this->data->status) && isset($this->data->error)) {
if (($this->data->status == 'ERR') || ((int) $this->data->error > 0)) {
$this->status = FALSE;
} else {
$this->status = TRUE;
}
} else {
$this->status = FALSE;
}
}
if (isset($this->data->error)) {
$this->error = ((int) $this->data->error > 0 ? (int) $this->data->error : 0);
} else {
$this->error = 0;
}
if (isset($this->data->error_string)) {
$this->error_string = $this->data->error_string;
} else {
$this->error_string = '';
}
} | php | {
"resource": ""
} |
q259464 | Webservices._setWebservicesUrl | test | private function _setWebservicesUrl() {
$ws_url = $this->url . '&format=json';
if ($this->token) {
$ws_url .= '&h=' . $this->token;
}
if ($this->username) {
$ws_url .= '&u=' . $this->username;
}
if ($this->password) {
$ws_url .= '&p=' . $this->password;
}
if ($this->operation) {
$ws_url .= '&op=' . $this->operation;
}
if ($this->from) {
$ws_url .= '&from=' . urlencode($this->from);
}
if ($this->to) {
$ws_url .= '&to=' . urlencode($this->to);
}
if ($this->footer) {
$ws_url .= '&footer=' . urlencode($this->footer);
}
if ($this->nofooter) {
$ws_url .= '&nofooter=' . $this->nofooter;
}
if ($this->msg) {
$ws_url .= '&msg=' . urlencode($this->msg);
}
if ($this->schedule) {
$ws_url .= '&schedule=' . $this->schedule;
}
if ($this->type) {
$ws_url .= '&type=' . $this->type;
}
if ($this->unicode) {
$ws_url .= '&unicode=' . $this->unicode;
}
if ($this->queue) {
$ws_url .= '&queue=' . $this->queue;
}
if ($this->src) {
$ws_url .= '&src=' . urlencode($this->src);
}
if ($this->dst) {
$ws_url .= '&dst=' . urlencode($this->dst);
}
if ($this->datetime) {
$ws_url .= '&dt=' . $this->datetime;
}
if ($this->smslog_id) {
$ws_url .= '&smslog_id=' . $this->smslog_id;
}
if ($this->last_smslog_id) {
$ws_url .= '&last=' . $this->last_smslog_id;
}
if ($this->count) {
$ws_url .= '&c=' . $this->count;
}
if ($this->keyword) {
$ws_url .= '&kwd=' . urlencode($this->keyword);
}
$this->webservices_url = $ws_url;
} | php | {
"resource": ""
} |
q259465 | LDAPService.getGroups | test | public function getGroups($cached = true, $attributes = [], $indexBy = 'dn')
{
$searchLocations = $this->config()->groups_search_locations ?: [null];
$cache = self::get_cache();
$results = $cache->load('groups' . md5(implode('', array_merge($searchLocations, $attributes))));
if (!$results || !$cached) {
$results = [];
foreach ($searchLocations as $searchLocation) {
$records = $this->gateway->getGroups($searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
if (!$records) {
continue;
}
foreach ($records as $record) {
$results[$record[$indexBy]] = $record;
}
}
$cache->save($results);
}
return $results;
} | php | {
"resource": ""
} |
q259466 | LDAPService.getGroupByDN | test | public function getGroupByDN($dn, $attributes = [])
{
$searchLocations = $this->config()->groups_search_locations ?: [null];
foreach ($searchLocations as $searchLocation) {
$records = $this->gateway->getGroupByDN($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
if ($records) {
return $records[0];
}
}
} | php | {
"resource": ""
} |
q259467 | LDAPService.getUsers | test | public function getUsers($attributes = [])
{
$searchLocations = $this->config()->users_search_locations ?: [null];
$results = [];
foreach ($searchLocations as $searchLocation) {
$records = $this->gateway->getUsers($searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
if (!$records) {
continue;
}
foreach ($records as $record) {
$results[$record['objectguid']] = $record;
}
}
return $results;
} | php | {
"resource": ""
} |
q259468 | LDAPService.getUserByGUID | test | public function getUserByGUID($guid, $attributes = [])
{
$searchLocations = $this->config()->users_search_locations ?: [null];
foreach ($searchLocations as $searchLocation) {
$records = $this->gateway->getUserByGUID($guid, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
if ($records) {
return $records[0];
}
}
} | php | {
"resource": ""
} |
q259469 | LDAPService.getUserByDN | test | public function getUserByDN($dn, $attributes = [])
{
$searchLocations = $this->config()->users_search_locations ?: [null];
foreach ($searchLocations as $searchLocation) {
$records = $this->gateway->getUserByDN($dn, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
if ($records) {
return $records[0];
}
}
} | php | {
"resource": ""
} |
q259470 | LDAPService.getUserByEmail | test | public function getUserByEmail($email, $attributes = [])
{
$searchLocations = $this->config()->users_search_locations ?: [null];
foreach ($searchLocations as $searchLocation) {
$records = $this->gateway->getUserByEmail($email, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
if ($records) {
return $records[0];
}
}
} | php | {
"resource": ""
} |
q259471 | LDAPService.getUserByUsername | test | public function getUserByUsername($username, $attributes = [])
{
$searchLocations = $this->config()->users_search_locations ?: [null];
foreach ($searchLocations as $searchLocation) {
$records = $this->gateway->getUserByUsername($username, $searchLocation, Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes);
if ($records) {
return $records[0];
}
}
} | php | {
"resource": ""
} |
q259472 | LDAPService.getUsernameByEmail | test | public function getUsernameByEmail($email)
{
$data = $this->getUserByEmail($email);
if (empty($data)) {
return null;
}
return $this->gateway->getCanonicalUsername($data);
} | php | {
"resource": ""
} |
q259473 | LDAPService.getLDAPGroupMembers | test | public function getLDAPGroupMembers($dn)
{
$groupObj = Group::get()->filter('DN', $dn)->first();
$groupData = $this->getGroupByGUID($groupObj->GUID);
$members = !empty($groupData['member']) ? $groupData['member'] : [];
// If a user belongs to a single group, this comes through as a string.
// Normalise to a array so it's consistent.
if ($members && is_string($members)) {
$members = [$members];
}
return $members;
} | php | {
"resource": ""
} |
q259474 | LDAPService.updateGroupFromLDAP | test | public function updateGroupFromLDAP(Group $group, $data)
{
if (!$this->enabled()) {
return false;
}
// Synchronise specific guaranteed fields.
$group->Code = $data['samaccountname'];
$group->Title = $data['samaccountname'];
if (!empty($data['description'])) {
$group->Description = $data['description'];
}
$group->DN = $data['dn'];
$group->LastSynced = (string)SS_Datetime::now();
$group->write();
// Mappings on this group are automatically maintained to contain just the group's DN.
// First, scan through existing mappings and remove ones that are not matching (in case the group moved).
$hasCorrectMapping = false;
foreach ($group->LDAPGroupMappings() as $mapping) {
if ($mapping->DN === $data['dn']) {
// This is the correct mapping we want to retain.
$hasCorrectMapping = true;
} else {
$mapping->delete();
}
}
// Second, if the main mapping was not found, add it in.
if (!$hasCorrectMapping) {
$mapping = new LDAPGroupMapping();
$mapping->DN = $data['dn'];
$mapping->write();
$group->LDAPGroupMappings()->add($mapping);
}
} | php | {
"resource": ""
} |
q259475 | LDAPService.createLDAPUser | test | public function createLDAPUser(Member $member)
{
if (!$this->enabled()) {
return;
}
if (empty($member->Username)) {
throw new ValidationException('Member missing Username. Cannot create LDAP user');
}
if (!$this->config()->new_users_dn) {
throw new Exception('LDAPService::new_users_dn must be configured to create LDAP users');
}
// Normalise username to lowercase to ensure we don't have duplicates of different cases
$member->Username = strtolower($member->Username);
// Create user in LDAP using available information.
$dn = sprintf('CN=%s,%s', $member->Username, $this->config()->new_users_dn);
try {
$this->add($dn, [
'objectclass' => 'user',
'cn' => $member->Username,
'accountexpires' => '9223372036854775807',
'useraccountcontrol' => '66048',
'userprincipalname' => sprintf(
'%s@%s',
$member->Username,
$this->gateway->config()->options['accountDomainName']
),
]);
} catch (\Exception $e) {
throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
}
$user = $this->getUserByUsername($member->Username);
if (empty($user['objectguid'])) {
throw new ValidationException('LDAP synchronisation failure: user missing GUID');
}
// Creation was successful, mark the user as LDAP managed by setting the GUID.
$member->GUID = $user['objectguid'];
} | php | {
"resource": ""
} |
q259476 | LDAPService.createLDAPGroup | test | public function createLDAPGroup(Group $group) {
if (!$this->enabled()) {
return;
}
if (empty($group->Title)) {
throw new ValidationException('Group missing Title. Cannot create LDAP group');
}
if (!$this->config()->new_groups_dn) {
throw new Exception('LDAPService::new_groups_dn must be configured to create LDAP groups');
}
// LDAP isn't really meant to distinguish between a Title and Code. Squash them.
$group->Code = $group->Title;
$dn = sprintf('CN=%s,%s', $group->Title, $this->config()->new_groups_dn);
try {
$this->add($dn, [
'objectclass' => 'group',
'cn' => $group->Title,
'name' => $group->Title,
'samaccountname' => $group->Title,
'description' => $group->Description,
'distinguishedname' => $dn
]);
} catch (\Exception $e) {
throw new \ValidationException('LDAP group creation failure: ' . $e->getMessage());
}
$data = $this->getGroupByDN($dn);
if (empty($data['objectguid'])) {
throw new \ValidationException(
new \ValidationResult(
false,
'LDAP group creation failure: group might have been created in LDAP. GUID is missing.'
)
);
}
// Creation was successful, mark the group as LDAP managed by setting the GUID.
$group->GUID = $data['objectguid'];
$group->DN = $data['dn'];
} | php | {
"resource": ""
} |
q259477 | LDAPService.updateLDAPFromMember | test | public function updateLDAPFromMember(Member $member)
{
if (!$this->enabled()) {
return;
}
if (!$member->GUID) {
throw new ValidationException('Member missing GUID. Cannot update LDAP user');
}
$data = $this->getUserByGUID($member->GUID);
if (empty($data['objectguid'])) {
throw new ValidationException('LDAP synchronisation failure: user missing GUID');
}
if (empty($member->Username)) {
throw new ValidationException('Member missing Username. Cannot update LDAP user');
}
$dn = $data['distinguishedname'];
// Normalise username to lowercase to ensure we don't have duplicates of different cases
$member->Username = strtolower($member->Username);
try {
// If the common name (cn) has changed, we need to ensure they've been moved
// to the new DN, to avoid any clashes between user objects.
if ($data['cn'] != $member->Username) {
$newDn = sprintf('CN=%s,%s', $member->Username, preg_replace('/^CN=(.+?),/', '', $dn));
$this->move($dn, $newDn);
$dn = $newDn;
}
} catch (\Exception $e) {
throw new ValidationException('LDAP move failure: '.$e->getMessage());
}
try {
$attributes = [
'displayname' => sprintf('%s %s', $member->FirstName, $member->Surname),
'name' => sprintf('%s %s', $member->FirstName, $member->Surname),
'userprincipalname' => sprintf(
'%s@%s',
$member->Username,
$this->gateway->config()->options['accountDomainName']
),
];
foreach ($member->config()->ldap_field_mappings as $attribute => $field) {
$relationClass = $member->getRelationClass($field);
if ($relationClass) {
// todo no support for writing back relations yet.
} else {
$attributes[$attribute] = $member->$field;
}
}
$this->update($dn, $attributes);
} catch (\Exception $e) {
throw new ValidationException('LDAP synchronisation failure: '.$e->getMessage());
}
} | php | {
"resource": ""
} |
q259478 | LDAPService.updateLDAPGroupsForMember | test | public function updateLDAPGroupsForMember(Member $member)
{
if (!$this->enabled()) {
return;
}
if (!$member->GUID) {
throw new ValidationException('Member missing GUID. Cannot update LDAP user');
}
$addGroups = [];
$removeGroups = [];
$user = $this->getUserByGUID($member->GUID);
if (empty($user['objectguid'])) {
throw new ValidationException('LDAP update failure: user missing GUID');
}
// If a user belongs to a single group, this comes through as a string.
// Normalise to a array so it's consistent.
$existingGroups = !empty($user['memberof']) ? $user['memberof'] : [];
if ($existingGroups && is_string($existingGroups)) {
$existingGroups = [$existingGroups];
}
foreach ($member->Groups() as $group) {
if (!$group->GUID) {
continue;
}
// mark this group as something we need to ensure the user belongs to in LDAP.
$addGroups[] = $group->DN;
}
// Which existing LDAP groups are not in the add groups? We'll check these groups to
// see if the user should be removed from any of them.
$remainingGroups = array_diff($existingGroups, $addGroups);
foreach ($remainingGroups as $groupDn) {
// We only want to be removing groups we have a local Group mapped to. Removing
// membership for anything else would be bad!
$group = Group::get()->filter('DN', $groupDn)->first();
if (!$group || !$group->exists()) {
continue;
}
// this group should be removed from the user's memberof attribute, as it's been removed.
$removeGroups[] = $groupDn;
}
// go through the groups we want the user to be in and ensure they're in them.
foreach ($addGroups as $groupDn) {
$this->addLDAPUserToGroup($user['distinguishedname'], $groupDn);
}
// go through the groups we _don't_ want the user to be in and ensure they're taken out of them.
foreach ($removeGroups as $groupDn) {
$members = $this->getLDAPGroupMembers($groupDn);
// remove the user from the members data.
if (in_array($user['distinguishedname'], $members)) {
foreach ($members as $i => $dn) {
if ($dn == $user['distinguishedname']) {
unset($members[$i]);
}
}
}
try {
$this->update($groupDn, ['member' => $members]);
} catch (\Exception $e) {
throw new ValidationException('LDAP group membership remove failure: '.$e->getMessage());
}
}
} | php | {
"resource": ""
} |
q259479 | LDAPService.setPassword | test | public function setPassword(Member $member, $password, $oldPassword = null)
{
$validationResult = ValidationResult::create(true);
$this->extend('onBeforeSetPassword', $member, $password, $validationResult);
if (!$member->GUID) {
SS_Log::log(sprintf('Cannot update Member ID %s, GUID not set', $member->ID), SS_Log::WARN);
$validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
return $validationResult;
}
$userData = $this->getUserByGUID($member->GUID);
if (empty($userData['distinguishedname'])) {
$validationResult->error(_t('LDAPAuthenticator.NOUSER', 'Your account hasn\'t been setup properly, please contact an administrator.'));
return $validationResult;
}
try {
if (!empty($oldPassword)) {
$this->gateway->changePassword($userData['distinguishedname'], $password, $oldPassword);
} else if ($this->config()->password_history_workaround) {
$this->passwordHistoryWorkaround($userData['distinguishedname'], $password);
} else {
$this->gateway->resetPassword($userData['distinguishedname'], $password);
}
$this->extend('onAfterSetPassword', $member, $password, $validationResult);
} catch (Exception $e) {
$validationResult->error($e->getMessage());
}
return $validationResult;
} | php | {
"resource": ""
} |
q259480 | LDAPService.deleteLDAPMember | test | public function deleteLDAPMember(Member $member) {
if (!$this->enabled()) {
return;
}
if (!$member->GUID) {
throw new ValidationException('Member missing GUID. Cannot delete LDAP user');
}
$data = $this->getUserByGUID($member->GUID);
if (empty($data['distinguishedname'])) {
throw new ValidationException('LDAP delete failure: could not find distinguishedname attribute');
}
try {
$this->delete($data['distinguishedname']);
} catch (\Exception $e) {
throw new ValidationException('LDAP delete user failed: '.$e->getMessage());
}
} | php | {
"resource": ""
} |
q259481 | WriteHandler.update | test | public function update($compare, $keys, $values, $limit = 1, $begin = 0)
{
$sk = $this->keys;
if (is_array($keys)) {
foreach ($sk as &$value) {
if (!isset($keys[$value])) {
break;
}
$value = $keys[$value];
}
array_slice($sk, 0, count($keys));
} else {
$sk = array($keys);
}
$sv = $this->fields;
foreach ($sv as &$value) {
if (!isset($values[$value])) {
break;
}
$value = $values[$value];
}
array_slice($sv, 0, count($values));
$this->io->update($this->indexId, $compare, $sk, $sv, $limit, $begin);
$ret = $this->io->registerCallback(array($this, 'updateCallback'));
if ($ret instanceof ErrorMessage) {
throw $ret;
}
return $ret;
} | php | {
"resource": ""
} |
q259482 | ReadSocket.connect | test | public function connect($server = 'localhost', $port = 9998)
{
$addr = "tcp://$server:$port";
$this->socket = stream_socket_client($addr, $errc, $errs, STREAM_CLIENT_CONNECT);
if (!$this->socket) {
throw new IOException("Connection to $server:$port failed");
}
} | php | {
"resource": ""
} |
q259483 | ReadSocket.disconnect | test | public function disconnect()
{
if ($this->socket !== NULL) {
@fclose($this->socket);
}
$this->socket = NULL;
$this->indexes = array();
$this->currentIndex = 1;
} | php | {
"resource": ""
} |
q259484 | ReadSocket.recvStr | test | protected function recvStr($read = true)
{
$str = @fgets($this->socket);
if (!$str) {
$this->disconnect();
throw new IOException('Cannot read from socket');
}
return substr($str, 0, -1);
} | php | {
"resource": ""
} |
q259485 | ReadSocket.sendStr | test | protected function sendStr($string)
{
if (!$this->isConnected()) {
throw new IOException('No active connection');
}
$string = (string)$string;
while ($string) {
$bytes = @fwrite($this->socket, $string);
if ($bytes === false) {
$this->disconnect();
throw new IOException('Cannot write to socket');
}
if ($bytes === 0) {
return;
}
$string = substr($string, $bytes);
}
} | php | {
"resource": ""
} |
q259486 | ReadSocket.encodeString | test | protected function encodeString($string)
{
if (is_null($string)) {
return self::NULL;
} else {
return strtr($string, self::$encodeMap);
}
} | php | {
"resource": ""
} |
q259487 | ReadSocket.decodeString | test | protected function decodeString($encoded)
{
if ($encoded === self::NULL) {
return NULL;
} else {
return strtr($encoded, self::$decodeMap);
}
} | php | {
"resource": ""
} |
q259488 | ReadSocket.readResponse | test | public function readResponse()
{
$response = $this->recvStr();
$vals = explode(self::SEP, $response);
if ($vals[0] != 0) {
//error occured
return new ErrorMessage(isset($vals[2]) ? $vals[2] : '', $vals[0]);
} else {
array_shift($vals); // skip error code
$numCols = intval(array_shift($vals));
$vals = array_map(array($this, 'decodeString'), $vals);
$result = array_chunk($vals, $numCols);
return $result;
}
} | php | {
"resource": ""
} |
q259489 | ReadSocket.authenticate | test | public function authenticate($authkey)
{
$this->sendStr(implode(self::SEP, array('A',
$this->encodeString($authkey)
)) . self:: EOL
);
$ret = $this->readResponse();
if (! $ret instanceof ErrorMessage) {
return TRUE;
} else {
throw $ret;
}
} | php | {
"resource": ""
} |
q259490 | LDAPLoginForm.consistentResponseTime | test | protected function consistentResponseTime($startTime)
{
if (!Config::inst()->get('LDAPLoginForm', 'consistent_password_times')) {
return;
}
$timeTaken = microtime(true) - $startTime;
if ($timeTaken < self::RESPONSE_TIME) {
$sleepTime = self::RESPONSE_TIME - $timeTaken;
// usleep takes microseconds, so we times our sleep period by 1mil (1mil ms = 1s)
usleep($sleepTime * 1000000);
}
} | php | {
"resource": ""
} |
q259491 | LDAPMemberExtension.onBeforeWrite | test | public function onBeforeWrite()
{
if ($this->owner->LDAPMemberExtension_NoSync) {
return;
}
$service = Injector::inst()->get('LDAPService');
if (
!$service->enabled() ||
!$this->owner->config()->create_users_in_ldap ||
!$this->owner->Username ||
$this->owner->GUID
) {
return;
}
$service->createLDAPUser($this->owner);
} | php | {
"resource": ""
} |
q259492 | LDAPMemberExtension.writeWithoutSync | test | public function writeWithoutSync() {
$this->owner->LDAPMemberExtension_NoSync = true;
try {
$this->owner->write();
} catch (Exception $e) {
$this->owner->LDAPMemberExtension_NoSync = false;
throw $e;
}
$this->owner->LDAPMemberExtension_NoSync = false;
} | php | {
"resource": ""
} |
q259493 | SAMLLoginForm.getMessageFromSession | test | protected function getMessageFromSession()
{
// The "MemberLoginForm.force_message session" is set in Security#permissionFailure()
// and displays messages like "You don't have access to this page"
// if force isn't set, it will just display "You're logged in as {name}"
if (($member = Member::currentUser()) && !Session::get('MemberLoginForm.force_message')) {
$this->message = _t(
'Member.LOGGEDINAS',
"You're logged in as {name}.",
['name' => $member->{$this->loggedInAsField}]
);
}
Session::set('MemberLoginForm.force_message', false);
parent::getMessageFromSession();
return $this->message;
} | php | {
"resource": ""
} |
q259494 | LDAPSecurityController.LostPasswordForm | test | public function LostPasswordForm()
{
$email = new EmailField('Email', _t('Member.EMAIL', 'Email'));
$action = new FormAction('forgotPassword', _t('Security.BUTTONSEND', 'Send me the password reset link'));
return LDAPLoginForm::create($this,
'LostPasswordForm',
new FieldList([$email]),
new FieldList([$action]),
false
);
} | php | {
"resource": ""
} |
q259495 | LDAPSecurityController.passwordsent | test | public function passwordsent($request)
{
$controller = $this->getResponseController(_t('Security.LOSTPASSWORDHEADER', 'Lost Password'));
// if the controller calls Director::redirect(), this will break early
if (($response = $controller->getResponse()) && $response->isFinished()) {
return $response;
}
$username = Convert::raw2xml(rawurldecode($request->param('ID')));
$customisedController = $controller->customise([
'Title' => _t('LDAPSecurity.PASSWORDSENTHEADER', "Password reset link sent to '{username}'",
['username' => $username]),
'Content' =>
"<p>"
. _t('LDAPSecurity.PASSWORDSENTTEXT',
"Thank you! A reset link has been sent to '{username}', provided an account exists.",
['username' => $username])
. "</p>",
'Username' => $username
]);
return $customisedController->renderWith($this->getTemplatesFor('passwordsent'));
} | php | {
"resource": ""
} |
q259496 | LDAPGateway.search | test | protected function search($filter, $baseDn = null, $scope = Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes = [], $sort = '')
{
$records = $this->ldap->search($filter, $baseDn, $scope, $attributes, $sort);
$results = [];
foreach ($records as $record) {
foreach ($record as $attribute => $value) {
// if the value is an array with a single value, e.g. 'samaccountname' => array(0 => 'myusername')
// then make sure it's just set in the results as 'samaccountname' => 'myusername' so that it
// can be used directly by ArrayData
if (is_array($value) && count($value) == 1) {
$value = $value[0];
}
// ObjectGUID and ObjectSID attributes are in binary, we need to convert those to strings
if ($attribute == 'objectguid') {
$value = LDAPUtil::bin_to_str_guid($value);
}
if ($attribute == 'objectsid') {
$value = LDAPUtil::bin_to_str_sid($value);
}
$record[$attribute] = $value;
}
$results[] = $record;
}
return $results;
} | php | {
"resource": ""
} |
q259497 | LDAPGateway.getGroupByGUID | test | public function getGroupByGUID($guid, $baseDn = null, $scope = Zend\Ldap\Ldap::SEARCH_SCOPE_SUB, $attributes = [])
{
return $this->search(
sprintf('(&(objectClass=group)(objectGUID=%s))', LDAPUtil::str_to_hex_guid($guid, true)),
$baseDn,
$scope,
$attributes
);
} | php | {
"resource": ""
} |
q259498 | LDAPGateway.changePassword | test | public function changePassword($dn, $password, $oldPassword)
{
if (!function_exists('ldap_modify_batch')) {
// Password change is unsupported - missing PHP API method.
$this->resetPassword($dn, $password);
return;
}
$modifications = [
[
"attrib" => "unicodePwd",
"modtype" => LDAP_MODIFY_BATCH_REMOVE,
"values" => [iconv('UTF-8', 'UTF-16LE', sprintf('"%s"', $oldPassword))],
],
[
"attrib" => "unicodePwd",
"modtype" => LDAP_MODIFY_BATCH_ADD,
"values" => [iconv('UTF-8', 'UTF-16LE', sprintf('"%s"', $password))],
],
];
// Batch attribute operations are not supported by Zend_Ldap, use raw resource.
$ldapConn = $this->ldap->getResource();
\Zend\Stdlib\ErrorHandler::start(E_WARNING);
$succeeded = ldap_modify_batch($ldapConn, $dn, $modifications);
\Zend\Stdlib\ErrorHandler::stop();
if (!$succeeded) {
throw new Exception($this->getLastPasswordError());
}
} | php | {
"resource": ""
} |
q259499 | LDAPGateway.resetPassword | test | public function resetPassword($dn, $password)
{
try {
$this->update(
$dn,
['unicodePwd' => iconv('UTF-8', 'UTF-16LE', sprintf('"%s"', $password))]
);
} catch(\Zend\Ldap\Exception\LdapException $e) {
throw new Exception($this->getLastPasswordError());
}
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.