Verifica se o valor precisa ser único

@param Dicionario $d
@param Meta $m
@param string $groupUser
775737
private static function checkUnique(Dicionario $d, Meta $m, string $groupUser)
    {
        if ($m->getUnique()) {
            $where = "WHERE {$m->getColumn()} = '{$m->getValue()}'" . (!empty($groupUser) ? " && {$groupUser}" : "");
            $where .= (!empty($d->search(0)->getValue()) ? " && id != " . $d->search("id")->getValue() : "");
            $read = new Read();
            $read->exeRead($d->getEntity(), $where);
            if ($read->getResult())
                $m->setError("Valor já existe, informe outro");
        }
    }
1200399
function doUpdateUsergroup(Userinfo $userinfo, Userinfo &$existinguser)
	{
		$changed = false;
		//check for advanced usergroup sync
		if (!$userinfo->block && empty($userinfo->activation)) {
			if (Groups::isUpdate($this->getJname())) {
				try {
					$usergroup_updated = $this->executeUpdateUsergroup($userinfo, $existinguser);
					if ($usergroup_updated) {
						$changed = true;
					} else {
						$this->debugger->addDebug(Text::_('SKIPPED_GROUP_UPDATE') . ':' . Text::_('GROUP_VALID'));
					}
				} catch (Exception $e) {
					$this->debugger->addError(Text::_('GROUP_UPDATE_ERROR') . ' ' . $e->getMessage());
				}
			}
		}
		return $changed;
	}
295980
private static function checkType(Meta $m)
    {
        if (in_array($m->getType(), ["tinyint", "smallint", "mediumint", "int", "bigint"])) {
            if (!is_numeric($m->getValue()))
                $m->setError("número inválido");

        } elseif ($m->getType() === "decimal") {

        } elseif (in_array($m->getType(), array("double", "real", "float"))) {
            if (!is_numeric($m->getValue()))
                $m->setError("valor não é um número");

        } elseif (in_array($m->getType(), array("bit", "boolean", "serial"))) {
            if (!is_bool($m->getValue()))
                $m->setError("valor boleano inválido. (true ou false)");

        } elseif (in_array($m->getType(), array("datetime", "timestamp"))) {
            if (!preg_match('/\d{4}-\d{2}-\d{2}[T\s]+\d{2}:\d{2}/i', $m->getValue()))
                $m->setError("formato de data inválido ex válido:(2017-08-23 21:58:00)");

        } elseif ($m->getType() === "date") {
            if (!preg_match('/\d{4}-\d{2}-\d{2}/i', $m->getValue()))
                $m->setError("formato de data inválido ex válido:(2017-08-23)");

        } elseif ($m->getType() === "time") {
            if (!preg_match('/\d{2}:\d{2}/i', $m->getValue()))
                $m->setError("formato de tempo inválido ex válido:(21:58)");

        } elseif ($m->getType() === "json" && !Check::isJson($m->getValue())) {
            $m->setError("formato json inválido");
        }
    }
246557
public function view_batch_markingallocation($mform) {
        global $CFG, $DB;

        require_once($CFG->dirroot . '/mod/assign/batchsetallocatedmarkerform.php');

        $o = '';

        $submitteddata = $mform->get_data();
        $users = $submitteddata->selectedusers;
        $userlist = explode(',', $users);

        $formdata = array('id' => $this->get_course_module()->id,
                          'selectedusers' => $users);

        $usershtml = '';

        $usercount = 0;
        $extrauserfields = get_extra_user_fields($this->get_context());
        $viewfullnames = has_capability('moodle/site:viewfullnames', $this->get_context());
        foreach ($userlist as $userid) {
            if ($usercount >= 5) {
                $usershtml .= get_string('moreusers', 'assign', count($userlist) - 5);
                break;
            }
            $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);

            $usershtml .= $this->get_renderer()->render(new assign_user_summary($user,
                $this->get_course()->id,
                $viewfullnames,
                $this->is_blind_marking(),
                $this->get_uniqueid_for_user($user->id),
                $extrauserfields,
                !$this->is_active_user($userid)));
            $usercount += 1;
        }

        $formparams = array(
            'userscount' => count($userlist),
            'usershtml' => $usershtml,
        );

        list($sort, $params) = users_order_by_sql('u');
        // Only enrolled users could be assigned as potential markers.
        $markers = get_enrolled_users($this->get_context(), 'mod/assign:grade', 0, 'u.*', $sort);
        $markerlist = array();
        foreach ($markers as $marker) {
            $markerlist[$marker->id] = fullname($marker);
        }

        $formparams['markers'] = $markerlist;

        $mform = new mod_assign_batch_set_allocatedmarker_form(null, $formparams);
        $mform->set_data($formdata);    // Initialises the hidden elements.
        $header = new assign_header($this->get_instance(),
            $this->get_context(),
            $this->show_intro(),
            $this->get_course_module()->id,
            get_string('setmarkingallocation', 'assign'));
        $o .= $this->get_renderer()->render($header);
        $o .= $this->get_renderer()->render(new assign_form('setworkflowstate', $mform));
        $o .= $this->view_footer();

        \mod_assign\event\batch_set_marker_allocation_viewed::create_from_assign($this)->trigger();

        return $o;
    }
811581
public static function collectByGroupRole($group_id, $role)
    {
        if (is_string($role) == true ) {

            $role = AclRole::findBySlug($role);
            if ($role == NULL) {
                return collect([]);
            }
            else {
                $role = $role->id;
            }
        }
        elseif(!is_numeric($role)) {
            throw new \InvalidArgumentException("The 'role' parameter must be an integer or a string");
        }

        // Usuário possui esta função ?
        // $user_role = AclUserRole::find([$user_id, $role]);
        // if ($user_role == NULL) {
        //     return collect([]);
        // }

        return (new static)->where('role_id', $role)->where('group_id', $group_id)->get();
    }
1238992
private static function checkValues(Meta $m)
    {
        if ($m->getType() === "json") {
            if (!empty($m->getValue()) && !empty($m->getAllow()['values'])) {
                if (in_array($m->getFormat(), ["sources", "source"])) {
                    foreach (json_decode($m->getValue(), true) as $v) {
                        if (!in_array(pathinfo($v['url'], PATHINFO_EXTENSION), $m->getAllow()['values']))
                            $m->setError("valor não é permitido");
                    }
                } else {
                    foreach (json_decode($m->getValue(), true) as $item) {
                        if (!empty($item) && !in_array($item, $m->getAllow()['values']))
                            $m->setError("valor não é permitido");
                    }
                }
            }
        } elseif (!empty($m->getAllow()['values']) && $m->getKey() !== "information" && !empty($m->getValue()) && !in_array($m->getValue(), $m->getAllow()['values'])) {
            $m->setError("valor não é permitido");
        }
    }
1163379
def create_grupo_usuario(self):
        """"""
        return GrupoUsuario(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
1206280
public static function addUserToGroup($user_id, $group_id)
	{
		// Get the user's existing entries
		$entries = self::all()
			->whereEquals('user_id', $user_id)
			->rows();

		$existing = array();
		foreach ($entries as $entry)
		{
			$existing[] = $entry->get('group_id');
		}

		$group_id = (is_array($group_id) ? $group_id : array($group_id));

		$blank = self::blank();

		// Loop through groups to be added
		foreach ($group_id as $group)
		{
			$group = intval($group);

			// Is the group already an existing entry?
			if (in_array($group, $existing))
			{
				// Skip.
				continue;
			}

			$query = $blank->getQuery()
				->insert($blank->getTableName())
				->values(array(
					'user_id'  => $user_id,
					'group_id' => $group
				));

			if (!$query->execute())
			{
				return false;
			}
		}

		return true;
	}
77019
public function remove_user_from_group($user, $groupid) {
        global $DB;
        require_capability('moodle/course:managegroups', $this->context);
        $group = $this->get_group($groupid);
        if (!groups_remove_member_allowed($group, $user)) {
            return false;
        }
        if (!$group) {
            return false;
        }
        return groups_remove_member($group, $user);
    }
719829
public function delete_custom_group(){
    global $wpdb;

    //checking the nonce
    check_admin_referer('delete_custom_group');

    if( isset($_GET['custom_group_id']) ){
      $id = (int)$_GET['custom_group_id'];
      if( is_int($id) ){
        $group = $this->get_group($id);
        $sql = $wpdb->prepare( "DELETE FROM ".MF_TABLE_CUSTOM_GROUPS." WHERE id = %d",$id );
        $wpdb->query($sql);

        $sql_fields = $wpdb->prepare( "DELETE FROM ".MF_TABLE_CUSTOM_FIELDS." WHERE custom_group_id = %d",$id );
        $wpdb->query($sql_fields);

        //ToDo: poner mensaje de que se borro correctamente
        $this->mf_redirect('mf_custom_fields','fields_list',array('message' => 'success','post_type' => $group['post_type']));

      }
    }
  }
270733
protected function saveUserMultipleValue($value, int $user_id)
    {
        $previous = get_user_meta($user_id, $this->getName(), false);

        if (is_null($value) || empty($value)) {
            delete_user_meta($user_id, $this->getName());
        } elseif (empty($previous) && is_array($value)) {
            array_walk($value, function ($val) use ($user_id) {
                add_user_meta($user_id, $this->getName(), $val, false);
            });
        } else {
            delete_user_meta($user_id, $this->getName());

            array_walk($value, function ($val) use ($user_id) {
                add_user_meta($user_id, $this->getName(), $val, false);
            });
        }
    }
1274165
private function prepareInputs(Dicionario $d, $fields = null, string $ngmodel = "dados."): array
    {
        $listaInput = [];
        $template = new Template("form");

        $max = 0;
        foreach ($d->getDicionario() as $m) {
            if ($max < $m->getIndice())
                $max = $m->getIndice();
        }
        $max++;

        for ($c = 1; $c < $max; $c++) {
            if ($meta = $d->search("indice", $c)) {
                //pula algumas colunas pré-definidas
                if (!empty($d->search(0)) && !($d->getEntity() !== "usuarios" || (!empty($d->search(0)) && !empty($_SESSION['userlogin']) && $_SESSION['userlogin']['id'] != $d->search(0))) && in_array($meta->getColumn(), ["status", "setor"]))
                    continue;

                //esconde input
                if($meta->getForm() === false || ($fields && !in_array($meta->getColumn(), $fields) && !in_array($meta->getId(), $fields))) {
                    $meta->setForm(['input' => 'hiddenField', 'cols' => '12', 'atributos' => '', 'template' => '', 'coll' => '', 'colm' => '', 'class' => '', 'style' => '', 'defaults' => '', 'fields' => '']);
                    if(empty($d->search(0)->getValue()) && isset($this->defaults[$meta->getId()]) && $this->defaults[$meta->getId()] !== "")
                        $meta->setValue($this->defaults[$meta->getId()], false);
                }

                $input = $this->getBaseInput($d, $meta, $ngmodel);

                if ($meta->getKey() === "extend") {
                    $listaInput[] = $this->getExtentContent($meta, $input);
                } else {
                    if ($allow = $this->checkCheckBoxData($meta, $d))
                        $input['allow'] = $allow;

                    if ($list = $this->checkListData($meta, $d))
                        $input = array_merge($input, $list);

                    $listaInput[] = (!in_array($input['form']['input'], ["hidden", "hiddenField"]) ? "<div class='col margin-bottom relative {$input['s']} {$input['m']} {$input['l']}'>" : "") .
                        $template->getShow($input['form']['input'], $input) .
                        (!in_array($input['form']['input'], ["hidden", "hiddenField"]) ? '</div>' : '');
                }
            }
        }

        //id
        $meta = $d->search(0);
        $input = $this->getBaseInput($d, $meta, $ngmodel);
        $listaInput[] = $template->getShow($input['form']['input'], $input);

        return $listaInput;
    }
147278
public function factoryUser($user,$password,$name,$group,$role,$status,$email=null,$iduser=null,$extra=[]) {
        $this->user=$user;
        $this->password=$password;
        $this->fullName=$name;
        $this->group=$group;
        $this->role=$role;
        $this->status=$status;
        $this->email=$email;
        $this->iduser=$iduser;
        $this->extraFields=$extra;
    }
556280
protected static function checkDefaultSet(Meta $m)
    {
        if ($m->getValue() === "")
            $m->setValue(null, false);

        if ($m->getValue() === null) {
            if ($m->getDefault() === false)
                $m->setError("Preencha este Campo");
            elseif (!empty($m->getDefault()))
                $m->setValue($m->getDefault(), false);
        }
    }
1135887
private static function checkRegular(Meta $m)
    {
        if (!empty($m->getAllow()['regex']) && is_string($m->getValue()) && !preg_match($m->getAllow()['regex'], $m->getValue()))
            $m->setError("formato não permitido.");
    }
312597
public function isWritable(int $user, int $group): bool
    {
        if ($this->user === $user) {
            $check = 0200;
        } elseif ($this->group === $group) {
            $check = 0020;
        } else {
            $check = 0002;
        }

        return (bool) ($this->permissions & $check);
    }
14752
public function updateMemberGroups($data, Member $member)
    {
        if (isset($data['memberof'])) {
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : [$data['memberof']];
            foreach ($ldapGroups as $groupDN) {
                foreach (LDAPGroupMapping::get() as $mapping) {
                    if (!$mapping->DN) {
                        $this->getLogger()->debug(
                            sprintf(
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
                                $mapping->ID
                            )
                        );
                        continue;
                    }

                    // the user is a direct member of group with a mapping, add them to the SS group.
                    if ($mapping->DN == $groupDN) {
                        $group = $mapping->Group();
                        if ($group && $group->exists()) {
                            $group->Members()->add($member, [
                                'IsImportedFromLDAP' => '1'
                            ]);
                            $mappedGroupIDs[] = $mapping->GroupID;
                        }
                    }

                    // the user *might* be a member of a nested group provided the scope of the mapping
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
                    // to see if they are a member of one of those. If they are, add them to the SS group
                    if ($mapping->Scope == 'Subtree') {
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
                        if (!$childGroups) {
                            continue;
                        }

                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
                            if ($childGroupDN == $groupDN) {
                                $group = $mapping->Group();
                                if ($group && $group->exists()) {
                                    $group->Members()->add($member, [
                                        'IsImportedFromLDAP' => '1'
                                    ]);
                                    $mappedGroupIDs[] = $mapping->GroupID;
                                }
                            }
                        }
                    }
                }
            }
        }

        // Lookup the previous mappings and see if there is any mappings no longer present.
        $unmappedGroups = $member->Groups()->alterDataQuery(function (DataQuery $query) {
            // join with the Group_Members table because we only want those group members assigned by this module.
            $query->leftJoin("Group_Members", '"Group_Members"."GroupID" = "Group"."ID"');
            $query->where('"Group_Members"."IsImportedFromLDAP" = 1');
        });

        // Don't remove associations which have just been added and we know are already correct!
        if (!empty($mappedGroupIDs)) {
            $unmappedGroups = $unmappedGroups->filter("GroupID:NOT", $mappedGroupIDs);
        }

        // Remove the member from any previously mapped groups, where the mapping
        // has since been removed in the LDAP data source
        if ($unmappedGroups->count()) {
            foreach ($unmappedGroups as $group) {
                $group->Members()->remove($member);
            }
        }
    }