Beispiel #1
0
 static function modify($uid, $gid, $field, $data)
 {
     if (!$uid || $gid || !$data) {
         return false;
     }
     $model = new UserGroupModel();
     $result = $model->modify($uid, $gid, $field, $data);
     return $result;
 }
 protected function toObject($rowset)
 {
     $this->loadClass("UserInfoModel", "model");
     $UserInfoModel = new UserInfoModel();
     $UserInfoModel->setUserName($rowset->username);
     $UserInfoModel->setPassword($rowset->password);
     $this->loadClass("UserGroupModel", "model");
     $UserGroupModel = new UserGroupModel();
     $UserGroupModel->setId($rowset->level);
     $UserGroupModel->setIsLoaded(false);
     $UserInfoModel->setUserGroup($UserGroupModel);
     return $UserInfoModel;
 }
 public function setRoodId()
 {
     if ($this->User->isAdmin) {
         return;
     }
     $arrRoot = array();
     if (is_array($this->User->finanzen_archiv) && $this->User->inherit != 'group') {
         $arrRoot = array_merge($arrRoot, $this->User->finanzen_archiv);
     }
     if ($this->User->inherit != 'custom') {
         foreach ($this->User->groups as $intGroup) {
             print $intGroup;
             $objGroup = \UserGroupModel::findByPk($intGroup);
             if ($objGroup) {
                 //@FIXME Group nicht von Haste abgeleitet!!!!!
                 $objFinanzenArchiv = $objGroup->getRelated('finanzen_archiv');
                 var_dump($objFinanzenArchiv);
                 if ($objFinanzenArchiv) {
                     while ($objFinanzenArchiv->next()) {
                         $arrRoot[] = $objFinanzenArchiv->id;
                         var_dump($objFinanzenArchiv);
                     }
                 }
             }
         }
     }
     var_dump($arrRoot);
     $GLOBALS['TL_DCA']['tl_finanzen_archiv']['list']['sorting']['root'] = array_unique($arrRoot);
     if (!$this->User->isAdmin) {
         unset($GLOBALS['TL_DCA']['tl_finanzen_archiv']['list']['global_operations']['all']);
         unset($GLOBALS['TL_DCA']['tl_finanzen_archiv']['list']['operations']['editheader']);
         unset($GLOBALS['TL_DCA']['tl_finanzen_archiv']['list']['operations']['delete']);
         $GLOBALS['TL_DCA']['tl_finanzen_archiv']['config']['closed'] = true;
     }
 }
 /**
  * Saves a user group.
  *
  * @param UserGroupModel $group
  *
  * @return bool
  */
 public function saveGroup(UserGroupModel $group)
 {
     $groupRecord = $this->_getGroupRecordById($group->id);
     $groupRecord->name = $group->name;
     $groupRecord->handle = $group->handle;
     if ($groupRecord->save()) {
         // Now that we have a group ID, save it on the model
         if (!$group->id) {
             $group->id = $groupRecord->id;
         }
         return true;
     } else {
         $group->addErrors($groupRecord->getErrors());
         return false;
     }
 }
 protected function build()
 {
     $this->select[] = 'user_account_information.*';
     $this->groupNeeded = false;
     if ($this->requestAccessSite) {
         $this->joins[] = " LEFT JOIN user_in_site_information ON user_in_site_information.user_account_id = user_account_information.id ";
         $this->joins[] = " JOIN site_access_request ON site_access_request.user_account_id = user_account_information.id AND " . " site_access_request.granted_by IS NULL AND site_access_request.rejected_by IS NULL AND site_access_request.site_id = :site_id";
         $this->where[] = " (  user_in_site_information.user_account_id IS NULL OR " . "(user_in_site_information.is_editor != '1' AND  user_in_site_information.is_administrator != '1' " . " AND  user_in_site_information.is_owner != '1' ))";
         $this->params['site_id'] = $this->requestAccessSite->getId();
         $this->groupNeeded = true;
     }
     if ($this->editNotOwnCuratedList) {
         $this->joins[] = " JOIN user_in_curated_list_information ON user_in_curated_list_information.user_account_id = user_account_information.id " . "AND user_in_curated_list_information.curated_list_id = :curated_list_id ";
         $this->params['curated_list_id'] = $this->editNotOwnCuratedList->getId();
         $this->where[] = " user_in_curated_list_information.is_owner = '0' AND user_in_curated_list_information.is_editor = '1' ";
     }
     if ($this->watchesSite) {
         $this->joins[] = " JOIN user_watches_site_information ON " . "user_watches_site_information.user_account_id = user_account_information.id  AND " . "user_watches_site_information.site_id = :site_id AND " . "user_watches_site_information.is_watching = '1'";
         $this->params['site_id'] = $this->watchesSite->getId();
     }
     if ($this->watchesGroup) {
         $this->joins[] = " JOIN user_watches_group_information ON " . "user_watches_group_information.user_account_id = user_account_information.id  AND " . "user_watches_group_information.group_id = :group_id AND " . "user_watches_group_information.is_watching = '1'";
         $this->params['group_id'] = $this->watchesGroup->getId();
     }
     if ($this->watchesArea) {
         $this->joins[] = " JOIN user_watches_area_information ON " . "user_watches_area_information.user_account_id = user_account_information.id  AND " . "user_watches_area_information.area_id = :area_id AND " . "user_watches_area_information.is_watching = '1'";
         $this->params['area_id'] = $this->watchesArea->getId();
     }
     if ($this->inUserGroup) {
         $this->joins[] = " JOIN user_in_user_group ON user_in_user_group.user_account_id = user_account_information.id " . "AND user_in_user_group.user_group_id = :user_group_id AND user_in_user_group.removed_at IS NULL  ";
         $this->params['user_group_id'] = $this->inUserGroup->getId();
     }
     if ($this->userHasNoEditorPermissionsInSite) {
         $this->joins[] = " JOIN user_has_no_editor_permissions_in_site ON user_has_no_editor_permissions_in_site.user_account_id = user_account_information.id " . "AND user_has_no_editor_permissions_in_site.site_id = :no_edit_permissions_in_site_id AND user_has_no_editor_permissions_in_site.removed_at IS NULL  ";
         $this->params['no_edit_permissions_in_site_id'] = $this->userHasNoEditorPermissionsInSite->getId();
     }
     if ($this->isOpenBySysAdminsOnly) {
         $this->where[] = " user_account_information.is_closed_by_sys_admin = '0' ";
     }
 }
 private function bindData()
 {
     $UserInfoModel = new UserInfoModel();
     $UserInfoModel->setUserName($this->getParam("username"));
     $UserInfoModel->setPassword($this->getParam("password"));
     $this->loadClass("UserGroupModel", "model");
     $UserGroupModel = new UserGroupModel();
     $UserGroupModel->setId($this->getParam("level"));
     $UserInfoModel->setUserGroup($UserGroupModel);
     return $UserInfoModel;
 }
Beispiel #7
0
	/**
	 * @param \UserModel|null $user
	 *
	 * @return \Form
	 */
	public static function GetForm($user = null){
		$form = new \Form();
		if($user === null) $user = new \UserModel();

		$type               = ($user->exists()) ? 'edit' : 'registration';
		$usermanager        = \Core\user()->checkAccess('p:/user/users/manage');
		$groupmanager       = \Core\user()->checkAccess('p:/user/groups/manage');
		$allowemailchanging = \ConfigHandler::Get('/user/email/allowchanging');

		if($type == 'registration'){
			$form->set('callsmethod', 'Core\\User\\Helper::RegisterHandler');
		}
		else{
			$form->set('callsmethod', 'Core\\User\\Helper::UpdateHandler');
		}

		$form->addElement('system', ['name' => 'user', 'value' => $user]);

		// Because the user system may not use a traditional Model for the backend, (think LDAP),
		// I cannot simply do a setModel() call here.

		// Only enable email changes if the current user is an admin or it's new.
		// (Unless the admin allows it via the site config)
		if($type != 'registration' && ( $usermanager || $allowemailchanging)){
			$form->addElement('text', array('name' => 'email', 'title' => 'Email', 'required' => true, 'value' => $user->get('email')));
		}

		// Tack on the active option if the current user is an admin.
		if($usermanager){
			$form->addElement(
				'checkbox',
				array(
					'name' => 'active',
					'title' => 'Active',
					'checked' => ($user->get('active') == 1),
				)
			);

			$form->addElement(
				'checkbox',
				array(
					'name' => 'admin',
					'title' => 'System Admin',
					'checked' => $user->get('admin'),
					'description' => 'The system admin, (or root user), has complete control over the site and all systems.',
				)
			);
		}
		
		if($usermanager){
			$elements = array_keys($user->getKeySchemas());
		}
		elseif($type == 'registration'){
			$elements = explode('|', \ConfigHandler::Get('/user/register/form_elements'));
		}
		else{
			$elements = explode('|', \ConfigHandler::Get('/user/edit/form_elements'));
		}
		
		// If avatars are disabled globally, remove that from the list if it's set.
		if(!\ConfigHandler::Get('/user/enableavatar') && in_array('avatar', $elements)){
			array_splice($elements, array_search('avatar', $elements), 1);
		}
		
		foreach($elements as $k){
			if($k){
				// Skip blank elements that can be caused by string|param|foo| or empty strings.
				$el = $user->getColumn($k)->getAsFormElement();
				if($el){
					$form->addElement($el);	
				}
			}
		}

		// Tack on the group registration if the current user is an admin.
		if($groupmanager){
			// Find all the groups currently on the site.

			$where = new DatasetWhereClause();
			$where->addWhere('context = ');
			if(\Core::IsComponentAvailable('multisite') && \MultiSiteHelper::IsEnabled()){
				$where->addWhereSub('OR', ['site = ' . \MultiSiteHelper::GetCurrentSiteID(), 'site = -1']);
			}

			$groups = \UserGroupModel::Find($where, null, 'name');

			if(sizeof($groups)){
				$groupopts = array();
				foreach($groups as $g){
					$groupopts[$g->get('id')] = $g->get('name');
				}

				$form->addElement(
					'checkboxes',
					array(
						'name' => 'groups[]',
						'title' => 'Group Membership',
						'options' => $groupopts,
						'value' => $user->getGroups()
					)
				);
			}

			$where = new DatasetWhereClause();
			$where->addWhere('context != ');
			if(\Core::IsComponentAvailable('multisite') && \MultiSiteHelper::IsEnabled()){
				$w = new DatasetWhereClause();
				$w->setSeparator('or');
				$w->addWhere('site = ' . \MultiSiteHelper::GetCurrentSiteID());
				$w->addWhere('site = -1');
				$where->addWhere($w);
			}
			$contextgroups = \UserGroupModel::Count($where);

			if($contextgroups > 0){
				// If this is a non-global context.
				// Good enough to stop here!
				$form->addElement(
					new \FormGroup(
						[
							'name' => 'context-groups',
							'id'   => 'context-groups',
							'title' => 'Context Group Membership',
						]
					)
				);

				// So that these elements will be registered on the form object...
				$form->addElement('hidden', ['name' => 'contextgroup[]', 'persistent' => false]);
				$form->addElement('hidden', ['name' => 'contextgroupcontext[]', 'persistent' => false]);
			}

		}

		// If the config is enabled and the current user is guest...
		if($type == 'registration' && \ConfigHandler::Get('/user/register/requirecaptcha') && !\Core\user()->exists()){
			$form->addElement('captcha');
		}

		$form->addElement(
			'submit',
			[
				'value' => (($type == 'registration') ? 'Register' : 'Update'),
				'name' => 'submit',
			]
		);

		return $form;
	}
 /**
  * Check permissions to edit table tl_photoalbums2_archive
  */
 public function checkPermission()
 {
     if ($this->User->isAdmin) {
         return;
     }
     // Set root IDs
     if (!is_array($this->User->photoalbums2s) || empty($this->User->photoalbums2s)) {
         $root = array(0);
     } else {
         $root = $this->User->photoalbums2s;
     }
     $GLOBALS['TL_DCA']['tl_photoalbums2_archive']['list']['sorting']['root'] = $root;
     // Check permissions to add archives
     if (!$this->User->hasAccess('create', 'photoalbums2p')) {
         $GLOBALS['TL_DCA']['tl_photoalbums2_archive']['config']['closed'] = true;
     }
     // Check current action
     switch ($this->Input->get('act')) {
         case 'create':
         case 'select':
             // Allow
             break;
         case 'edit':
             // Dynamically add the record to the user profile
             if (!in_array($this->Input->get('id'), $root)) {
                 $arrNew = $this->Session->get('new_records');
                 if (is_array($arrNew['tl_photoalbums2_archive']) && in_array($this->Input->get('id'), $arrNew['tl_photoalbums2_archive'])) {
                     // Add permissions on user level
                     if ($this->User->inherit == 'custom' || !$this->User->groups[0]) {
                         $objUser = \UserModel::findByPk($this->User->id);
                         $arrPhotoalbums2p = deserialize($objUser->photoalbums2p);
                         if (is_array($arrPhotoalbums2p) && in_array('create', $arrPhotoalbums2p)) {
                             $arrPhotoalbums2s = deserialize($objUser->photoalbums2s);
                             $arrPhotoalbums2s[] = $this->Input->get('id');
                             $objUser->photoalbums2s = serialize($arrPhotoalbums2s);
                             $objUser->save();
                         }
                     } elseif ($this->User->groups[0] > 0) {
                         $objGroup = \UserGroupModel::findByPk($this->User->groups[0]);
                         $arrPhotoalbums2p = deserialize($objGroup->photoalbums2p);
                         if (is_array($arrPhotoalbums2p) && in_array('create', $arrPhotoalbums2p)) {
                             $arrPhotoalbums2s = deserialize($objGroup->photoalbums2s);
                             $arrPhotoalbums2s[] = $this->Input->get('id');
                             $objGroup->photoalbums2s = serialize($arrPhotoalbums2s);
                             $objGroup->save();
                         }
                     }
                     // Add new element to the user object
                     $root[] = $this->Input->get('id');
                     $this->User->photoalbums2s = $root;
                 }
             }
             // No break;
         // No break;
         case 'copy':
         case 'delete':
         case 'show':
             if (!in_array($this->Input->get('id'), $root) || $this->Input->get('act') == 'delete' && !$this->User->hasAccess('delete', 'photoalbums2p')) {
                 $this->log('Not enough permissions to ' . $this->Input->get('act') . ' photoalbums2 archive ID "' . $this->Input->get('id') . '"', 'tl_photoalbums2_archive checkPermission', TL_ERROR);
                 $this->redirect('contao/main.php?act=error');
             }
             break;
         case 'editAll':
         case 'deleteAll':
         case 'overrideAll':
             $session = $this->Session->getData();
             if ($this->Input->get('act') == 'deleteAll' && !$this->User->hasAccess('delete', 'photoalbums2p')) {
                 $session['CURRENT']['IDS'] = array();
             } else {
                 $session['CURRENT']['IDS'] = array_intersect($session['CURRENT']['IDS'], $root);
             }
             $this->Session->setData($session);
             break;
         default:
             if (strlen($this->Input->get('act'))) {
                 $this->log('Not enough permissions to ' . $this->Input->get('act') . ' photoalbums2 archives', 'tl_photoalbums2_archive checkPermission', TL_ERROR);
                 $this->redirect('contao/main.php?act=error');
             }
             break;
     }
 }
	/**
	 * Set the site permissions to a given Form object.
	 *
	 * Used by the create and update pages.
	 *
	 * @param Form $form
	 * @param UserGroupModel $model
	 */
	private function _setPermissionsToForm(Form $form, UserGroupModel $model){
		// I want to split up the permission set into a set of groups, based on the first key.
		$groups = [];
		foreach(Core::GetPermissions() as $key => $data){
			if($key{0} == '/'){
				$group = substr($key, 1, strpos($key, '/', 1)-1);
			}
			else{
				$group = 'general';
			}

			if(!isset($groups[$group])){
				$groups[$group] = [];
			}

			// NEW i18n support for config options!
			$i18nKey = \Core\i18n\I18NLoader::KeyifyString($key);
			//$opts['description'] = t('MESSAGE_PERM__' . $i18nKey);
			$groups[$group][$key] = t('STRING_PERMISSION_' . $i18nKey);
		}

		// Now, I can add these groups to the form.
		foreach($groups as $gkey => $options){
			// Make the title a little more friendly.
			$gtitle = ucwords($gkey) . ' Permissions to Assign';

			$form->addElement(
				'checkboxes',
				array(
					'group' => 'Permissions',
					'id' => 'permissions-' . $gkey,
					'name' => 'permissions',
					'title' => $gtitle,
					'options' => $options,
					'value' => $model->getPermissions(),
				)
			);
		}
	}
	/**
	 * Import the given data into the destination Model.
	 *
	 * @param array   $data            Indexed array of records to import/merge from the external source.
	 * @param array   $options         Any options required for the import, such as merge, key, etc.
	 * @param boolean $output_realtime Set to true to output the log in real time as the import happens.
	 *
	 * @throws Exception
	 *
	 * @return \Core\ModelImportLogger
	 */
	public static function Import($data, $options, $output_realtime = false) {
		$log = new \Core\ModelImportLogger('User Group Importer', $output_realtime);

		$merge = isset($options['merge']) ? $options['merge'] : true;
		$pk    = isset($options['key']) ? $options['key'] : null;

		if(!$pk) {
			throw new Exception(
				'Import requires a "key" field on options containing the primary key to compare against locally.'
			);
		}

		foreach($data as $dat) {

			if($pk == 'name' || $pk == 'id' || $pk == 'ldap_dn') {
				// These are the only two fields on the User object itself.
				$group = UserGroupModel::Find([$pk . ' = ' . $dat[ $pk ]], 1);
			}
			else {
				$group = UserGroupModel::Find(['name = ' . $dat['name']], 1);
			}

			$status_type = $group ? 'Updated' : 'Created';

			if($group && !$merge) {
				$log->duplicate('Skipped group ' . $group->getLabel() . ', already exists and merge not requested');
				// Skip to the next record.
				continue;
			}

			if(!$group) {
				// All incoming groups must have a name!
				if(!isset($dat['name'])) {
					$log->error('Unable to import groups without a name!');
					// Skip to the next record.
					continue;
				}

				// New user!
				$group = new UserGroupModel();
			}
			// No else needed, else is there IS a valid $user object and it's setup ready to go.


			// Handle all the properties for this user!
			foreach($dat as $key => $val){
				// Default Behaviour,
				// save the key into whatever field it was set to go to.
				$group->set($key, $val);
			}

			try {
				$status = $group->save();
			}
			catch(Exception $e) {
				$log->error($e->getMessage());
				// Skip to the next.
				continue;
			}

			if($status) {
				$log->success($status_type . ' group ' . $group->getLabel() . ' successfully!');
			}
			else {
				$log->skip('Skipped group ' . $group->getLabel() . ', no changes detected.');
			}
		}

		$log->finalize();

		return $log;
	}
Beispiel #11
0
<?php
/**
 * Upgrade file for 2.5.7 to 2.6.0.
 *
 * This is meant to run through every registered user group on the site and
 * migrate their permissions to the new expanded version.
 *
 * @package Core
 */


$groups = UserGroupModel::Find();
foreach($groups as $g){
	/** @var $g UserGroupModel */
	$perms = $g->getPermissions();

	$key = array_search('user_manage', $perms);

	if($key !== false){
		// It has the legacy key, update it!
		unset($perms[$key]);
		$perms = array_merge($perms, ['/user/users/manage', '/user/groups/manage', '/user/permissions/manage']);
		$g->setPermissions($perms);
		$g->save();
	}

	$key = array_search('user_activity_list', $perms);

	if($key !== false){
		// It has the legacy key, update it!
		unset($perms[$key]);
	/**
	 * Standard render function for this form element
	 *
	 * @return string
	 */
	public function render() {
		static $renderedcount = 0;

		$renderedcount++;
		$this->_targetname = '_formaccessstring' . $renderedcount . \Core\random_hex(8);

		$v               = trim($this->get('value'));
		$checked         = 'advanced';
		$advanced_groups = array();
		$type            = 'whitelist';

		if ($v == '*') {
			$checked = 'basic_anyone';
		} elseif ($v == '!*') {
			$checked = 'basic_admin';
		}
		elseif (!$v) {
			// Blank value
			$checked = 'advanced';
		}
		elseif ($v == 'g:anonymous') {
			$checked = 'basic_anonymous';
		}
		elseif ($v == 'g:authenticated') {
			$checked = 'basic_authenticated';
		}
		elseif ($v == 'none') {
			// Allow for a blank value.
			$checked = null;
			$type    = null;
		}
		else {
			// Determine the sub groups checked.
			$checked = 'advanced';
			$parts   = array_map('trim', explode(';', $v));
			foreach ($parts as $p) {
				if ($p == '*') {
					// If a wildcard is present, mark the groups as ones to blacklist.
					$type = 'blacklist';
					continue;
				}
				list($t, $tv) = explode(':', $p);
				// Trim off the '!' in front of it, it'll be picked up by the presence of the '*' at the end.
				if ($tv{0} == '!') $tv = substr($tv, 1);
				$advanced_groups[] = $tv;
			}
		}

		$groups = array();

		// Tack on the system groups.
		$anongroup = new UserGroupModel();
		$anongroup->setFromArray(
			array(
				'id'   => 'anonymous',
				'name' => 'Anonymous Users'
			)
		);

		$authgroup = new UserGroupModel();
		$authgroup->setFromArray(
			array(
				'id'   => 'authenticated',
				'name' => 'Authenticated Users'
			)
		);
		$groups[] = $anongroup;
		$groups[] = $authgroup;

		// Find all the groups currently on the site.
		$groups = array_merge($groups, UserGroupModel::Find(null, null, 'name'));
		foreach ($groups as $k => $v) {
			if (in_array($v->get('id'), $advanced_groups)) $v['checked'] = true;
		}


		$tpl = \Core\Templates\Template::Factory($this->getTemplateName());
		$tpl->assign('element', $this);
		$tpl->assign('groups', $groups);
		$tpl->assign('dynname', $this->_targetname);
		$tpl->assign('main_checked', $checked);
		$tpl->assign('advanced_type', $type);

		return $tpl->fetch();
	}
 private function bindData()
 {
     $UserGroupModel = new UserGroupModel();
     $UserGroupModel->setName($this->getParam("name"));
     return $UserGroupModel;
 }
	/**
	 * There has been a file selected; check that file for headers and what not to display something useful to the user.
	 */
	private function _import2(){
		$view = $this->getView();
		$request = $this->getPageRequest();

		$filename = \Core\Session::Get('user-import/file');
		$file = \Core\Filestore\Factory::File($filename);
		$contents = $file->getContentsObject();

		if(!$contents instanceof \Core\Filestore\Contents\ContentCSV){
			\Core\set_message($file->getBaseFilename() . ' does not appear to be a valid CSV file!', 'error');
			\Core\Session::UnsetKey('user-import/file');
			\Core\reload();
		}

		$hasheader = $contents->hasHeader();
		$data = $contents->parse();
		$total = sizeof($data);

		// Since I don't want to display the entire dataset in the preview...
		if($hasheader){
			$header = $contents->getHeader();
		}
		else{
			$header = array();
			$i=0;
			foreach($data[0] as $k => $v){
				$header[$i] = 'Column ' . ($i+1);
				$i++;
			}
		}
		$colcount = sizeof($header);

		if($total > 11){
			$preview = array_splice($data, 0, 10);
		}
		else{
			$preview = $data;
		}

		$form = new Form();
		$form->set('callsmethod', 'User\\ImportHelper::FormHandler2');
		$form->addElement('system', ['name' => 'key', 'value' => \Core\Session::Get('user-import/key')]);
		$form->addElement(
			'checkbox',
			[
				'name' => 'has_header',
				'title' => 'Has Header',
				'value' => 1,
				'checked' => $hasheader,
				'description' => 'If this CSV has a header record on line 1, (as illustrated below), check this to ignore that line.'
			]
		);

		$form->addElement(
			'checkbox',
			[
				'name' => 'merge_duplicates',
				'title' => 'Merge Duplicate Records',
				'value' => 1,
				'checked' => true,
				'description' => 'Merge duplicate records that may be found in the import.'
			]
		);

		// Only display the user groups if the current user has access to manage user groups.
		$usergroups = UserGroupModel::Find(['context = ']);
		if(sizeof($usergroups) && \Core\user()->checkAccess('p:/user/groups/manage')){
			$usergroupopts = array();
			foreach($usergroups as $ug){
				$usergroupopts[$ug->get('id')] = $ug->get('name');
			}
			$form->addElement(
				'checkboxes',
				[
					'name' => 'groups[]',
					'title' => 'User Groups to Assign',
					'options' => $usergroupopts,
					'description' => 'Check which groups to set the imported users to.  If merge duplicate records is selected, any found users will be set to the checked groups, (and consequently unset from any unchecked groups).',
				]
			);
		}
		else{
			$form->addElement('hidden', ['name' => 'groups[]', 'value' => '']);
		}

		// Get the map-to options.
		$maptos = ['' => '-- Do Not Map --', 'email' => 'Email', 'password' => 'Password'];

		$configs = UserConfigModel::Find([], null, 'weight asc, name desc');
		foreach($configs as $c){
			$maptos[ $c->get('key') ] = $c->get('name');
		}

		$maptoselects = [];
		foreach($header as $key => $title){
			$value = '';
			if(isset($maptos[$key])) $value = $key;
			if(array_search($title, $maptos)) $value = array_search($title, $maptos);

			$form->addElement(
				'select',
				[
					'name' => 'mapto[' . $key . ']',
					'title' => $title,
					'options' => $maptos,
					'value' => $value
				]
			);
		}


		$view->templatename = 'pages/user/import2.tpl';
		$view->assign('has_header', $hasheader);
		$view->assign('header', $header);
		$view->assign('preview', $preview);
		$view->assign('form', $form);
		$view->assign('total', $total);
		$view->assign('col_count', $colcount);
	}
Beispiel #15
0
	/**
	 * Import the given data into the destination Model.
	 *
	 * @param array   $data            Indexed array of records to import/merge from the external source.
	 * @param array   $options         Any options required for the import, such as merge, key, etc.
	 * @param boolean $output_realtime Set to true to output the log in real time as the import happens.
	 *
	 * @throws Exception
	 *
	 * @return \Core\ModelImportLogger
	 */
	public static function Import($data, $options, $output_realtime = false) {
		$log = new \Core\ModelImportLogger('User Importer', $output_realtime);

		$merge = isset($options['merge']) ? $options['merge'] : true;
		$pk    = isset($options['key']) ? $options['key'] : null;

		if(!$pk) {
			throw new Exception(
				'Import requires a "key" field on options containing the primary key to compare against locally.'
			);
		}

		// Load in members from the group

		// Set the default group on new accounts, if a default is set.
		$defaultgroups = \UserGroupModel::Find(["default = 1"]);
		$groups        = [];
		$gnames        = [];
		foreach($defaultgroups as $g) {
			/** @var \UserGroupModel $g */
			$groups[] = $g->get('id');
			$gnames[] = $g->get('name');
		}
		if(sizeof($groups)) {
			$log->log('Found ' . sizeof($groups) . ' default groups for new users: ' . implode(', ', $gnames));
		}
		else {
			$log->log('No groups set as default, new users will not belong to any groups.');
		}
		
		$log->log('Starting ' . ($merge ? '*MERGE*' : '*skipping*' ) . ' import of ' . sizeof($data) . ' users');

		foreach($data as $dat) {

			if(isset($dat[$pk])){
				// Only check the information if the primary key is set on this record.
				if($pk == 'email' || $pk == 'id') {
					// These are the only two fields on the User object itself.
					$user = UserModel::Find([$pk . ' = ' . $dat[ $pk ]], 1);
				}
				else {
					$uucm = UserUserConfigModel::Find(['key = ' . $pk, 'value = ' . $dat[ $pk ]], 1);

					if($uucm) {
						$user = $uucm->getLink('UserModel');
					}
					else {

						// Try the lookup from the email address instead.
						// This will force accounts that exist to be synced up correctly.
						// The only caveat to this is that users will not be updated with the foreign key if merge is disabled.
						$user = UserModel::Find(['email = ' . $dat['email']], 1);
					}
				}
			}
			else{
				$user = null;
			}
			

			$status_type = $user ? 'Updated' : 'Created';

			if($user && !$merge) {
				$log->duplicate('Skipped user ' . $user->getLabel() . ', already exists and merge not requested');
				// Skip to the next record.
				continue;
			}

			if(!$user) {
				// All incoming users must have an email address!
				if(!isset($dat['email'])) {
					$log->error('Unable to import user without an email address!');
					// Skip to the next record.
					continue;
				}

				// Meta fields that may or may not be present, but should be for reporting purposes.
				if(!isset($dat['registration_ip'])) {
					$dat['registration_ip'] = REMOTE_IP;
				}
				if(!isset($dat['registration_source'])) {
					$dat['registration_source'] = \Core\user()->exists() ? 'admin' : 'self';
				}
				if(!isset($dat['registration_invitee'])) {
					$dat['registration_invitee'] = \Core\user()->get('id');
				}

				// New user!
				$user = new UserModel();
			}
			// No else needed, else is there IS a valid $user object and it's setup ready to go.

			
			// Handle all the properties for this user!
			foreach($dat as $key => $val){
				
				if($key == 'avatar' && strpos($val, '://') !== false){
					// Sync the user avatar.
					$log->actionStart('Downloading ' . $dat['avatar']);
					$f    = new \Core\Filestore\Backends\FileRemote($dat['avatar']);
					$dest = \Core\Filestore\Factory::File('public/user/avatar/' . $f->getBaseFilename());
					if($dest->identicalTo($f)) {
						$log->actionSkipped();
					}
					else {
						$f->copyTo($dest);
						$user->set('avatar', 'public/user/avatar/' . $dest->getBaseFilename());
						$log->actionSuccess();
					}
				}
				elseif($key == 'profiles' && is_array($val)) {
					$new_profiles = $val;

					// Pull the current profiles from the account
					$profiles = $user->get('external_profiles');
					if($profiles && is_array($profiles)) {
						$current_flat = [];
						foreach($profiles as $current_profile) {
							$current_flat[] = $current_profile['url'];
						}

						// Merge in any *actual* new profile
						foreach($new_profiles as $new_profile) {
							if(!in_array($new_profile['url'], $current_flat)) {
								$profiles[] = $new_profile;
							}
						}

						unset($new_profile, $new_profiles, $current_flat, $current_profile);
					}
					else {
						$profiles = $new_profiles;
						unset($new_profiles);
					}

					$user->set('external_profiles', $profiles);
				}
				elseif($key == 'backend'){
					// Was a backend requested?
					// This gets merged instead of replaced entirely.
					$user->enableAuthDriver($val);
				}
				elseif($key == 'groups'){
					$user->setGroups($val);
				}
				else{
					// Default Behaviour,
					// save the key into whatever field it was set to go to.
					$user->set($key, $val);
				}
			}

			try {
				// Set the default groups loaded from the system.
				if(!$user->exists()){
					$user->setGroups($groups);	
				}

				$status = $user->save();
			}
			catch(Exception $e) {
				$log->error($e->getMessage());
				// Skip to the next.
				continue;
			}
			
			if($status) {
				$log->success($status_type . ' user ' . $user->getLabel() . ' successfully!');
			}
			else {
				$log->skip('Skipped user ' . $user->getLabel() . ', no changes detected.');
			}
		}

		$log->finalize();

		return $log;
	}