add existing mappings to ldap user provisioning mapping admin form table

@param drupal form array $form
@param enum $direction LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER or LDAP_USER_PROV_DIRECTION_TO_LDAP_ENTRY

@return by reference to $form array
770747
private function addServerMappingFields(&$form, $direction) {

    if ($direction == LDAP_USER_PROV_DIRECTION_NONE) {
      return;
    }

    $text = ($direction == LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER) ? 'target' : 'source';
    $user_attr_options = array('0' => t('Select') . ' ' . $text);

    if (!empty($this->synchMapping[$direction])) {
      foreach ($this->synchMapping[$direction] as $target_id => $mapping) {
        if (!isset($mapping['name']) || isset($mapping['exclude_from_mapping_ui']) && $mapping['exclude_from_mapping_ui']) {
          continue;
        }
        if (
          (isset($mapping['configurable_to_drupal']) && $mapping['configurable_to_drupal'] && $direction == LDAP_USER_PROV_DIRECTION_TO_DRUPAL_USER)
          ||
          (isset($mapping['configurable_to_ldap']) && $mapping['configurable_to_ldap']  && $direction == LDAP_USER_PROV_DIRECTION_TO_LDAP_ENTRY)
          ) {
          $user_attr_options[$target_id] = substr($mapping['name'], 0, 25);
        }
      }
    }
    $user_attr_options['user_tokens'] = '-- user tokens --';

    $row = 0;

    // 1. non configurable mapping rows
    foreach ($this->synchMapping[$direction] as $target_id => $mapping) {
      if (isset($mapping['exclude_from_mapping_ui']) && $mapping['exclude_from_mapping_ui']) {
        continue;
      }
      if ( !$this->isMappingConfigurable($mapping, 'ldap_user') && ($mapping['direction'] == $direction || $mapping['direction'] == LDAP_USER_PROV_DIRECTION_ALL)) { // is configurable by ldap_user module (not direction to ldap_user)
        $this->addSynchFormRow($form, 'nonconfigurable', $direction, $mapping, $user_attr_options, $row);
        $row++;
      }
    }

    // 2. existing configurable mappings rows
    if (!empty($this->ldapUserSynchMappings[$direction])) {
      foreach ($this->ldapUserSynchMappings[$direction] as $target_attr_token => $mapping) {  // key could be ldap attribute name or user attribute name
        if (isset($mapping['enabled']) && $mapping['enabled'] && $this->isMappingConfigurable($this->synchMapping[$direction][$target_attr_token], 'ldap_user')) {
          $this->addSynchFormRow($form, 'update', $direction, $mapping, $user_attr_options, $row);
          $row++;
        }
      }
    }

    // 3. leave 4 rows for adding more mappings
    for ($i=0; $i<4; $i++) {
      $this->addSynchFormRow($form, 'add', $direction, NULL, $user_attr_options, $row);
      $row++;
    }

  }
12918
public function define_form_specific($form) {
        // Get the current calendar in use - see MDL-18375.
        $calendartype = \core_calendar\type_factory::get_calendar_instance();

        // Create variables to store start and end.
        list($year, $month, $day) = explode('_', date('Y_m_d'));
        $currentdate = $calendartype->convert_from_gregorian($year, $month, $day);
        $currentyear = $currentdate['year'];

        $arryears = $calendartype->get_years();

        // Add elements.
        $form->addElement('select', 'param1', get_string('startyear', 'profilefield_datetime'), $arryears);
        $form->setType('param1', PARAM_INT);
        $form->setDefault('param1', $currentyear);

        $form->addElement('select', 'param2', get_string('endyear', 'profilefield_datetime'), $arryears);
        $form->setType('param2', PARAM_INT);
        $form->setDefault('param2', $currentyear);

        $form->addElement('checkbox', 'param3', get_string('wanttime', 'profilefield_datetime'));
        $form->setType('param3', PARAM_INT);

        $form->addElement('hidden', 'startday', '1');
        $form->setType('startday', PARAM_INT);
        $form->addElement('hidden', 'startmonth', '1');
        $form->setType('startmonth', PARAM_INT);
        $form->addElement('hidden', 'startyear', '1');
        $form->setType('startyear', PARAM_INT);
        $form->addElement('hidden', 'endday', '1');
        $form->setType('endday', PARAM_INT);
        $form->addElement('hidden', 'endmonth', '1');
        $form->setType('endmonth', PARAM_INT);
        $form->addElement('hidden', 'endyear', '1');
        $form->setType('endyear', PARAM_INT);
        $form->addElement('hidden', 'defaultdata', '0');
        $form->setType('defaultdata', PARAM_INT);
    }
533886
function bind($userdn = NULL, $pass = NULL, $anon_bind = FALSE) {

    // Ensure that we have an active server connection.
    if (!$this->connection) {
      watchdog('ldap', "LDAP bind failure for user %user. Not connected to LDAP server.", array('%user' => $userdn));
      return LDAP_CONNECT_ERROR;
    }

    if ($anon_bind !== FALSE && $userdn === NULL && $pass === NULL && $this->bind_method == LDAP_SERVERS_BIND_METHOD_ANON) {
      $anon_bind = TRUE;
    }
    if ($anon_bind === TRUE) {
      if (@!ldap_bind($this->connection)) {
        if ($this->detailedWatchdogLog) {
          watchdog('ldap', "LDAP anonymous bind error. Error %errno: %error", array('%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
        }
        return ldap_errno($this->connection);
      }
    }
    else {
      $userdn = ($userdn != NULL) ? $userdn : $this->binddn;
      $pass = ($pass != NULL) ? $pass : $this->bindpw;

      if ($this->followrefs) {
        $rebHandler = new LdapServersRebindHandler($userdn, $pass);
        ldap_set_rebind_proc($this->connection, array($rebHandler, 'rebind_callback'));
      }

      if (drupal_strlen($pass) == 0 || drupal_strlen($userdn) == 0) {
        watchdog('ldap', "LDAP bind failure for user userdn=%userdn, pass=%pass.", array('%userdn' => $userdn, '%pass' => $pass));
        return LDAP_LOCAL_ERROR;
      }
      if (@!ldap_bind($this->connection, $userdn, $pass)) {
        if ($this->detailedWatchdogLog) {
          watchdog('ldap', "LDAP bind failure for user %user. Error %errno: %error", array('%user' => $userdn, '%errno' => ldap_errno($this->connection), '%error' => ldap_error($this->connection)));
        }
        return ldap_errno($this->connection);
      }
    }

    return LDAP_SUCCESS;
  }
621443
public function updateSearchForm($form){
		if($this->modelIsMultiSitesAware()) {
			$managedSites = Multisites::inst()->sitesManagedByMember();

			$source = Site::get()->filter('ID', Multisites::inst()->sitesManagedByMember())->map('ID', 'Title')->toArray();
			$plural = singleton($this->owner->modelClass)->plural_name();
			if(count($source)){
				$activeSite = $this->getActiveSite();
				$form->Fields()->push(DropdownField::create(
					'SiteID', 
					"Site: ", 
					$source,
					$activeSite ? $activeSite->ID : null
				));
			}
		}
	}
1346904
public function mapFormSubmissionToDto(array $submission)
    {
        $objectData = $this->objectData
                ? $this->objectData
                : $this->objectForm->process($submission);

        $dataDto = $this->dataFormMapping
                ? $this->dataFormMapping->mapFormSubmissionToDto($submission)
                : null;

        return new ObjectActionParameter(
                $objectData[IObjectAction::OBJECT_FIELD_NAME],
                $dataDto
        );
    }
721784
public function applyRules($form) {
		if (method_exists($form, 'getValidateRules')) {
			$this->rules = array_merge($this->rules, $form->getValidateRules());
		}

		return $this;
	}
905749
protected function buildForm($form = null, $object = null, array $options = [])
    {
        return $this->getFormFactory()->create($form ?: $this->resource, $object, $options);
    }
1141536
protected function addMember($form)
    {
        $member   = new Member();
        $groupIds = $this->getSettableGroupIdsFrom($form);

        $form->saveInto($member);

        $member->ProfilePageID   = $this->ID;
        $member->NeedsValidation = ($this->EmailType === 'Validation');
        $member->NeedsApproval   = $this->RequireApproval;

        try {
            $member->write();
        } catch (ValidationException $e) {
            $validationMessages = implode("; ", $e->getResult()->getMessages());
            $form->sessionMessage($validationMessages, 'bad');
            return null;
        }

        // set after member is created otherwise the member object does not exist
        $member->Groups()->setByIDList($groupIds);

        // If we require admin approval, send an email to the admin and delay
        // sending an email to the member.
        if ($this->RequireApproval) {
            $groups = $this->ApprovalGroups();
            if (!$groups ||
                $groups->count() == 0) {
                // If nothing is configured, fallback to ADMIN
                $groups = Permission::get_groups_by_permission('ADMIN');
            }

            $emails = [];
            if ($groups) {
                foreach ($groups as $group) {
                    foreach ($group->Members() as $_member) {
                        if ($_member->Email) {
                            $emails[] = $_member->Email;
                        }
                    }
                }
            }

            if ($emails) {
                $emails = array_unique($emails);

                $mail   = Email::create();
                $config  = SiteConfig::current_site_config();
                $approve = Controller::join_links(
                    Director::baseURL(),
                    'member-approval',
                    $member->ID,
                    '?token=' . $member->ValidationKey
                );

                $mail->setSubject("Registration Approval Requested for $config->Title");
                foreach ($emails as $email) {
                    if (!Email::is_valid_address($email)) {
                        // Ignore invalid email addresses or else we'll get validation errors.
                        // ie. default 'admin' account
                        continue;
                    }
                    $mail->addBCC($email);
                }
                $mail->setHTMLTemplate('Symbiote\\MemberProfiles\\Email\\MemberRequiresApprovalEmail');
                $mail->setData(array(
                    'SiteConfig'  => $config,
                    'Member'      => $member,
                    'ApproveLink' => Director::absoluteURL($approve)
                ));

                $mail->send();
            }
        } else {
            // NOTE(Jake): 2018-05-03
            //
            // Only send the confirmation email immediately after registering if they
            // don't require admin approval.
            //
            switch ($this->EmailType) {
                case 'None':
                    // Does not require anything
                break;

                case 'Confirmation':
                case 'Validation':
                    // Must activate themselves via the confirmation email
                    $email = MemberConfirmationEmail::create($this->data(), $member);
                    $email->send();
                break;
            }
        }

        $this->extend('onAddMember', $member);
        return $member;
    }
826329
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:");
	}
1200849
private function handleAll(FormInterface $form)
    {
        $config = $form->get('value')->getConfig();
        $choiceValue = $config->getOption('choice_value');
        $choices = iterator_to_array($config->getOption('grid')->getDataSource(['all' => true]));

        $this->buildForm($form, $choices);

        return array_map(function ($choice) use ($choiceValue) {
            return call_user_func($choiceValue, $choice);
        }, $choices);
    }
32338
public static function form_policydoc_add(stdClass $form) {
        global $DB;

        $form = clone($form);

        $form->policyid = $DB->insert_record('tool_policy', (object) [
            'sortorder' => 999,
        ]);

        static::distribute_policy_document_sortorder();

        return static::form_policydoc_update_new($form);
    }
424004
protected function setDisabledForm(Form $form, bool $disabled = TRUE) : void
    {
        foreach ($form->getComponents() as $component)
        {
            $component->setDisabled($disabled);
        }
    }
61442
protected function _getUpdateExpression($direction = '+')
    {
        $field = $this->_config['order'];

        return $this->_table->query()->newExpr()
            ->add(new IdentifierExpression($field))
            ->add('1')
            ->setConjunction($direction);
    }
1019977
public function setForm(Form $form)
	{
		$this->form = $form;
		$this->formControl = $form->getFormControl();

		return $this;
	}
788631
public function form()
    {
        $menuModel = config('admin.database.menu_model');
        $permissionModel = config('admin.database.permissions_model');
        $roleModel = config('admin.database.roles_model');

        $form = new Form(new $menuModel());

        $form->display('id', 'ID');

        $form->select('parent_id', trans('admin.parent_id'))->options($menuModel::selectOptions());
        $form->text('title', trans('admin.title'))->rules('required');
        $form->icon('icon', trans('admin.icon'))->default('fa-bars')->rules('required')->help($this->iconHelp());
        $form->text('uri', trans('admin.uri'));
        $form->multipleSelect('roles', trans('admin.roles'))->options($roleModel::all()->pluck('name', 'id'));
        if ($form->model()->withPermission()) {
            $form->select('permission', trans('admin.permission'))->options($permissionModel::pluck('name', 'slug'));
        }

        $form->display('created_at', trans('admin.created_at'));
        $form->display('updated_at', trans('admin.updated_at'));

        return $form;
    }
577825
private function validateForm(array $form): array
    {
        $resolver = new OptionsResolver();
        $resolver->setRequired([
            'url',
        ]);
        $resolver->setDefaults([
            'method' => 'POST',
            'encType' => 'application/x-www-form-urlencoded',
            'url_options' => [],
        ]);
        $resolver->setAllowedTypes('url', ['string']);
        $resolver->setAllowedTypes('url_options', ['array']);
        $resolver->setAllowedTypes('method', ['string']);
        $resolver->setAllowedTypes('encType', ['string']);
        $resolver->setAllowedValues('encType', ['application/x-www-form-urlencoded', 'text/plain', 'multipart/form-data']);
        $resolver->setAllowedValues('method', ['POST', 'GET']);

        $form = $resolver->resolve($form);

        if (! empty($form['url_options']))
        {
            foreach($form['url_options'] as $q=>$w)
            {
                $method = 'get' . ucfirst($w);
                $found = false;
                if (method_exists($this->getTemplateManager()->getEntity(), $method))
                {
                    $form['url'] = str_replace($q, $this->getTemplateManager()->getEntity()->$method(), $form['url']);
                    $found = true;
                }
                $method = 'is' . ucfirst($w);
                if (method_exists($this->getTemplateManager()->getEntity(), $method) && ! $found)
                {
                    $form['url'] = str_replace($q, $this->getTemplateManager()->getEntity()->$method(), $form['url']);
                    $found = true;
                }
                if (! $found)
                    trigger_error(sprintf('The form url does not have an option %s in the entity %s.', $w, get_class($this->getTemplateManager()->getEntity())), E_USER_ERROR);
            }
        }

        return $form;
    }
1068036
public function addFormSucceeded(Form $form, ArrayHash $values): void
	{
		if ($values->generatePassword) {
			$password = Random::generate($this->minPasswordLength, $this->passwordChars);
		} else {
			$password = $values->password;
		}

		$user = new User;
		$this->orm->users->attach($user);
		try {
			$user->setUsername($values->username);
		} catch (UniqueConstraintViolationException $ex) {
			$form->addError('cms.user.duplicityUsername');
			return;
		} catch (InvalidArgumentException $ex) {
			$form->addError('cms.user.invalidUsername');
			return;
		}

		try {
			$user->setEmail($values->email);
		} catch (UniqueConstraintViolationException $ex) {
			$form->addError('cms.user.duplicityEmail');
			return;
		} catch (InvalidArgumentException $ex) {
			$form->addError('cms.user.invalidUsername');
			return;
		}

		try {
			$user->setPhone($values->phone ?: null);
		} catch (InvalidArgumentException $ex) {
			$form->addError('cms.user.invalidPhone');
			return;
		}

		$user->firstName = $values->firstName;
		$user->surname = $values->surname;

		$language = $this->localeService->getById($values->language);
		$user->language = $language === null ? null : $language->name;

		$user->roles->set($values->roles);
		$user->setPassword($password);

		$this->orm->persistAndFlush($user);

		if ($this->configurator->sendNewUserPassword) {
			$this->mailer->sendNewUser($user->email, $user->username, $password);
		}

		$this->flashNotifier->success('cms.user.dataSaved');
		$this->restoreBacklink();
	}