Create an edit form for a class and its property
and handle the submited data on save

@param core_kernel_classes_Class    $clazz
@param core_kernel_classes_Resource $resource
@return tao_helpers_form_Form the generated form
174160
public function getClassForm(core_kernel_classes_Class $clazz)
    {
        $propMode = 'simple';
        if($this->hasSessionAttribute('property_mode')){
            $propMode = $this->getSessionAttribute('property_mode');
        }

        $options = array(
            'property_mode' => $propMode,
            'topClazz' => $this->getClass(GenerisRdf::CLASS_GENERIS_RESOURCE)
        );
        $data = $this->getRequestParameters();
        $formContainer = new tao_actions_form_Clazz($clazz, $this->extractClassData($data), $this->extractPropertyData($data), $propMode);
        $myForm = $formContainer->getForm();

        if($myForm->isSubmited()){
            if($myForm->isValid()){
                //get the data from parameters

                // get class data and save them
                if(isset($data['class'])){
                    $classValues = array();
                    foreach($data['class'] as $key => $value){
                        $classKey =  tao_helpers_Uri::decode($key);
                        $classValues[$classKey] =  tao_helpers_Uri::decode($value);
                    }

                    $this->bindProperties($clazz, $classValues);
                }

                //save all properties values
                if(isset($data['properties'])){
                    foreach($data['properties'] as $i => $propertyValues) {
                        //get index values
                        $indexes = null;
                        if(isset($propertyValues['indexes'])){
                            $indexes = $propertyValues['indexes'];
                            unset($propertyValues['indexes']);
                        }
                        if($propMode === 'simple') {
                            $this->saveSimpleProperty($propertyValues);
                        } else {
                            $this->saveAdvProperty($propertyValues);
                        }

                        //save index
                        if(!is_null($indexes)){
                            foreach($indexes as $indexValues){
                                $this->savePropertyIndex($indexValues);
                            }
                        }
                    }
                }
            }
        }
        return $myForm;
    }
563713
public function searchFormClass($resource, $modelClass=null)
    {
        if ($modelClass) {
            return $this->findClass($modelClass.'SearchForm');
        }
        return $this->findClass($this->className($resource).'SearchForm');
    }
1081458
public function toTree( core_kernel_classes_Class $clazz, array $options = array())
    {
        $returnValue = array();

    	$users = $this->getAllUsers(array('order' => GenerisRdf::PROPERTY_USER_LOGIN));
		foreach($users as $user){
			$login = (string) $user->getOnePropertyValue(new core_kernel_classes_Property(GenerisRdf::PROPERTY_USER_LOGIN));
			$returnValue[] = array(
					'data' 	=> tao_helpers_Display::textCutter($login, 16),
					'attributes' => array(
						'id' => tao_helpers_Uri::encode($user->getUri()),
						'class' => 'node-instance'
					)
				);

		}

        return (array) $returnValue;
    }
63443
public static function registerCondForm($clz, $form) {
        assert(!empty($clz) && class_exists($clz), 'CtsDataSource is invalid');
        assert($form instanceof FormTable, get_class($form) . ' is not an instance of FormTable');
        self::$forms[ $clz ] = $form;
    }
578836
public function editAction()
    {
        if(method_exists($this, 'getEditForm'))
        {
            $form = $this->getEditForm();
        }
        else
        {
            $form = $this->getForm();
        }

        $id = $this->getEvent()
                ->getRouteMatch()
                ->getParam('id', 0);

        $form->add([
            'type'       => 'Zend\Form\Element\Hidden',
            'name'       => 'id',
            'attributes' => [
                'id'    => 'id',
                'value' => $id,
            ],
            'filters'    => [
                [
                    'name' => 'Int',
                ],
            ],
            'validators' => [
                [
                    'name' => 'Digits',
                ],
            ],
        ]);

        $em            = $this->getEntityManager();
        $objRepository = $em->getRepository($this->getEntityClass());
        $entity        = $objRepository->find($id);
        $form->bind($entity);

        $redirectUrl = $this->url()->fromRoute($this->getActionRoute(), [], true);
        $prg         = $this->fileprg($form, $redirectUrl, true);

        if($prg instanceof Response)
        {
            return $prg;
        }
        elseif($prg === false)
        {
            $this->getEventManager()->trigger('getForm', $this, [
                'form'        => $form,
                'entityClass' => $this->getEntityClass(),
                'id'          => $id,
                'entity'      => $entity,
            ]);

            return [
                'entityForm' => $form,
                'entity'     => $entity,
            ];
        }

        $this->getEventManager()->trigger('getForm', $this, [
            'form'        => $form,
            'entityClass' => $this->getEntityClass(),
            'id'          => $id,
            'entity'      => $entity,
        ]);

        $savedEntity = $this->getEntityService()->save($form, $entity);

        if(!$savedEntity)
        {
            return [
                'entityForm' => $form,
                'entity'     => $entity,
            ];
        }

        $this->flashMessenger()->addSuccessMessage($this->getServiceLocator()
                        ->get('translator')
                        ->translate($this->successEditMessage));

        return $this->redirect()->toRoute($this->getActionRoute('list'), [], true);
    }
1161075
public function getExportForm(core_kernel_classes_Resource $resource) {
        if ($resource instanceof core_kernel_classes_Class) {
            $formData= array('class' => $resource);
        } else {
            $formData= array('instance' => $resource);
        }
    	$form = new ExportForm($formData);
    	return $form->getForm();
    }
444407
private PropertyEditor loadPropertyEditor(Class<?> clz) {
        PropertyEditor editor = null;
        try {
            editor = (PropertyEditor) clz.newInstance();
        } catch (InstantiationException e) {
            Logger.getLogger(PropertyEditorRegistry.class.getName()).log(Level.SEVERE, null, e);
        } catch (IllegalAccessException e) {
            Logger.getLogger(PropertyEditorRegistry.class.getName()).log(Level.SEVERE, null, e);
        }
        return editor;
    }
1140165
public function initForm()
    {
        
        $name = isset($this->options['name']) ? $this->options['name'] : 'form_'.(count(self::$forms)+1); 
		unset($this->options['name']);
		
        $this->form = tao_helpers_form_FormFactory::getForm($name, $this->options);
    	
		//add create action in toolbar
		$action = tao_helpers_form_FormFactory::getElement('save', 'Free');
		$value =  '<a href="#" class="form-submitter btn-success small"><span class="icon-save"></span> ' .__('Create').'</a>';

		$action->setValue($value);
		
		$this->form->setActions(array($action), 'top');
		$this->form->setActions(array($action), 'bottom');
        
    }
823661
public function formAction($name = null)
    {
        $tmpServer = $this->ldap->get($name);
        $tmpPassword = (isset($tmpServer['password'])) ? $tmpServer['password'] : null;
        $form = $this->formFactory->create(LdapType::class, $tmpServer);
        if ('POST' === $this->request->getMethod() && $form->handleRequest($this->request) && $form->isValid()) {
            $data = $form->getData();

            if ($this->ldap->exists($name, $data)) {
                $form->addError(new FormError($this->translator->trans('ldap_already_exists', [], 'ldap')));
            } else {
                $user = isset($data['user']) ? $data['user'] : null;
                $data['password'] = (isset($data['password']) && null !== $data['password']) ?
                    $data['password'] :
                    $tmpPassword;
                $password = $data['password'];
                if (!$this->ldap->connect($data, $user, $password)) {
                    $form->addError(new FormError($this->translator->trans('ldap_cant_connect', [], 'ldap')));
                } else {
                    $this->ldap->saveConfig($data);
                    $this->ldap->deleteIfReplace($name, $data);

                    return new Response('true');
                }
            }
        }

        return ['form' => $form->createView(), 'name' => $name];
    }
1270739
public static File getClassJar(Class clazz) {
		File file = null;

		try {
			file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI());
		} catch (URISyntaxException e) {}

		return file;
	}
376617
public function deleteClass(\core_kernel_classes_Class $clazz)
    {
        $returnValue = (bool) false;
        
        if ($clazz->isSubClassOf($this->getRootClass()) && ! $clazz->equals($this->getRootClass())) {
            $returnValue = true;
            
            $instances = $clazz->getInstances();
            foreach ($instances as $instance) {
                $this->deleteResource($instance);
            }
            
            $subclasses = $clazz->getSubClasses(false);
            foreach ($subclasses as $subclass) {
                $returnValue = $returnValue && $this->deleteClass($subclass);
            }
            foreach ($clazz->getProperties() as $classProperty) {
                $returnValue = $returnValue && $this->deleteClassProperty($classProperty);
            }
            $returnValue = $returnValue && $clazz->delete();
        } else {
            \common_Logger::w('Tried to delete class ' . $clazz->getUri() . ' as if it were a subclass of ' . $this->getRootClass()->getUri());
        }
        
        return (bool) $returnValue;
    }
918077
public function edit()
    {
        $this->defaultData();
        $userService = $this->getServiceLocator()->get(tao_models_classes_UserService::class);
        $user = $this->getUserResource();

        $types = $user->getTypes();
        $myFormContainer = new tao_actions_form_Users(reset($types), $user);
        $myForm = $myFormContainer->getForm();

        if ($myForm->isSubmited()) {
            if ($myForm->isValid()) {
                $values = $myForm->getValues();
                if (!empty($values['password2']) && !empty($values['password3'])) {
                    $plainPassword =  $values['password2'];
                    $values[GenerisRdf::PROPERTY_USER_PASSWORD] = core_kernel_users_Service::getPasswordHash()->encrypt($values['password2']);
                }

                unset($values['password2']);
                unset($values['password3']);

                if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_UILG]))) {
                    unset($values[GenerisRdf::PROPERTY_USER_UILG]);
                }
                if (!preg_match("/[A-Z]{2,4}$/", trim($values[GenerisRdf::PROPERTY_USER_DEFLG]))) {
                    unset($values[GenerisRdf::PROPERTY_USER_DEFLG]);
                }

                $userService->checkCurrentUserAccess($values[GenerisRdf::PROPERTY_USER_ROLES]);

                // leave roles which are not in the allowed list for current user
                $oldRoles = $userService->getUserRoles($user);
                $allowedRoles = $userService->getPermittedRoles($userService->getCurrentUser(), $oldRoles, false);
                $staticRoles = array_diff($oldRoles, $allowedRoles);
                $values[GenerisRdf::PROPERTY_USER_ROLES] = array_merge($values[GenerisRdf::PROPERTY_USER_ROLES], $staticRoles);

                $binder = new tao_models_classes_dataBinding_GenerisFormDataBinder($user);

                if ($binder->bind($values)) {
                    $data = [];
                    if (isset($plainPassword)){
                        $data = ['hashForKey' => UserHashForEncryption::hash($plainPassword)];
                    }
                    $this->getEventManager()->trigger(new UserUpdatedEvent(
                        $user,
                        array_merge($values, $data))
                    );
                    $this->setData('message', __('User saved'));
                }
            }
        }

        $this->setData('formTitle', __('Edit a user'));
        $this->setData('myForm', $myForm->render());
        $this->setView('user/form.tpl');
    }
1362210
public function editGroup()
	{
        $this->defaultData();

		$clazz = $this->getCurrentClass();
		$group = $this->getCurrentInstance();

		$formContainer = new SignedFormInstance($clazz, $group);
		$myForm = $formContainer->getForm();
		if($myForm->isSubmited()){
			if($myForm->isValid()){
			    $this->validateInstanceRoot($group->getUri());

				$binder = new tao_models_classes_dataBinding_GenerisFormDataBinder($group);
				$group = $binder->bind($myForm->getValues());

		        $this->setData("selectNode", tao_helpers_Uri::encode($group->getUri()));
				$this->setData('message', __('Group saved'));
				$this->setData('reload', true);
			}
		}

		$memberProperty = $this->getProperty(GroupsService::PROPERTY_MEMBERS_URI);
		$memberForm = tao_helpers_form_GenerisTreeForm::buildReverseTree($group, $memberProperty);
		$memberForm->setData('title',	__('Select group test takers'));
		$this->setData('memberForm', $memberForm->render());

		if ($this->getServiceLocator()->get(common_ext_ExtensionsManager::SERVICE_ID)->isEnabled('taoDeliveryRdf')) {
		    $this->setData('deliveryForm', DeliveryWidget::renderDeliveryTree($group));
		}
        $updatedAt = $this->getServiceLocator()->get(ResourceWatcher::SERVICE_ID)->getUpdatedAt($group);
		$this->setData('updatedAt', $updatedAt);
		$this->setData('formTitle', __('Edit group'));
		$this->setData('myForm', $myForm->render());
		$this->setView('form_group.tpl');
	}
566386
public function addCreateUrlGeneratorMethod(Clazz $class)
    {
        $class->addImport(new Import('Puli\Discovery\Api\Discovery'));
        $class->addImport(new Import('Puli\Manager\Api\Server\ServerCollection'));
        $class->addImport(new Import('Puli\UrlGenerator\Api\UrlGenerator'));
        $class->addImport(new Import('Puli\UrlGenerator\DiscoveryUrlGenerator'));
        $class->addImport(new Import('RuntimeException'));

        $method = new Method('createUrlGenerator');
        $method->setDescription('Creates the URL generator.');

        $arg = new Argument('discovery');
        $arg->setTypeHint('Discovery');
        $arg->setType('Discovery');
        $arg->setDescription('The discovery to read from.');
        $method->addArgument($arg);

        $method->setReturnValue(new ReturnValue('$generator', 'UrlGenerator', 'The created URL generator.'));

        $method->addBody(
<<<EOF
if (!interface_exists('Puli\UrlGenerator\Api\UrlGenerator')) {
    throw new RuntimeException('Please install puli/url-generator to create UrlGenerator instances.');
}

EOF
        );

        $urlFormatsString = '';

        foreach ($this->servers as $server) {
            $urlFormatsString .= sprintf(
                "\n    %s => %s,",
                var_export($server->getName(), true),
                var_export($server->getUrlFormat(), true)
            );
        }

        if ($urlFormatsString) {
            $urlFormatsString .= "\n";
        }

        $method->addBody("\$generator = new DiscoveryUrlGenerator(\$discovery, array($urlFormatsString));");

        $class->addMethod($method);
    }
155255
public void setEditorHandler(I_CmsEditorHandler clazz) {

        m_editorHandler = clazz;
        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(
                Messages.get().getBundle().key(
                    Messages.INIT_EDITOR_HANDLER_CLASS_1,
                    m_editorHandler.getClass().getName()));
        }
    }
1278317
public void setEditorAction(I_CmsEditorActionHandler clazz) {

        m_editorAction = clazz;
        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(
                Messages.get().getBundle().key(
                    Messages.INIT_EDITOR_ACTION_CLASS_1,
                    m_editorAction.getClass().getName()));
        }
    }
767278
public HTMLForm addClass(String clazz) {
        String currentClass = this.getProperty("class");
        if (currentClass != null) {
            currentClass += " " + clazz;
        } else {
            currentClass = clazz;
        }
        this.setProperty("class", currentClass);

        return this;
    }