/** * Gets the field names * * @param array $exclude An array of columns to exclude * @return array */ public static function getFieldNames($exclude = array()) { // Get the field names $columns = array(); $columns[] = array('raw' => 'name', 'human' => Lang::txt('COM_MEMBERS_FIELD_NAME')); $fields = Field::all()->whereIn('action_browse', User::getAuthorisedViewLevels())->where('type', '!=', 'tags')->ordered()->rows(); foreach ($fields as $field) { if (in_array($field->get('name'), $exclude)) { continue; } $columns[] = array('raw' => $field->get('name'), 'human' => $field->get('label')); } return $columns; }
/** * Run Export * * @return void */ public function runTask() { $skip = array('password', 'params', 'usertype'); $keys = array(); $tags = array(); $members = Member::blank(); $attribs = $members->getStructure()->getTableColumns($members->getTableName()); foreach ($attribs as $key => $desc) { if (in_array(strtolower($key), $skip)) { continue; } $keys[$key] = $key; //array_push($keys, $key); } $attribs = Field::all()->ordered()->rows(); foreach ($attribs as $attrib) { if ($attrib->get('type') == 'tags') { array_push($tags, $attrib->get('name')); } if ($attrib->get('type') == 'address') { $keys[$attrib->get('name')] = $attrib->get('name') . ' Street 1'; $keys['_' . $attrib->get('name') . '_address2'] = $attrib->get('name') . ' Street 2'; $keys['_' . $attrib->get('name') . '_city'] = $attrib->get('name') . ' City'; $keys['_' . $attrib->get('name') . '_postal'] = $attrib->get('name') . ' Post Code'; $keys['_' . $attrib->get('name') . '_region'] = $attrib->get('name') . ' Region'; $keys['_' . $attrib->get('name') . '_country'] = $attrib->get('name') . ' Country'; $keys['_' . $attrib->get('name') . '_latitude'] = $attrib->get('name') . ' Latitude'; $keys['_' . $attrib->get('name') . '_longitude'] = $attrib->get('name') . ' Longitude'; continue; } $keys[$attrib->get('name')] = $attrib->get('name'); //array_push($keys, $attrib->get('name')); } // Get request vars $delimiter = Request::getVar('delimiter', ','); $csv = array(); $rows = $members->ordered()->rows(); // Convert to array and bind to object below // This may seem counter-intuitive but it's for // performance reasons. Otherwise, all the circular // references eat up memery. $rows = $rows->toArray(); // Gather up member information foreach ($rows as $row) { $member = Member::blank()->set($row); $tmp = array(); foreach ($keys as $key => $label) { if (substr($key, 0, 1) == '_') { if (!isset($tmp[$key])) { $tmp[$key] = ''; } continue; } if (in_array($key, $tags)) { $val = $member->tags('string'); } else { $val = $member->get($key); } if (is_array($val)) { $val = implode(';', $val); } else { if (strstr($val, '{')) { $v = json_decode((string) $val, true); if (!$v || json_last_error() !== JSON_ERROR_NONE) { // Nothing else to do } else { $i = 0; foreach ($v as $nm => $vl) { $k = '_' . $key . '_' . $nm; if ($i == 0) { $k = $key; } $tmp[$k] = $vl; $i++; } continue; } } } $tmp[$key] = $val; } unset($member); array_push($csv, $tmp); } //output csv directly as a download @ob_end_clean(); header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Expires: 0"); header("Content-Transfer-Encoding: binary"); header('Content-type: text/comma-separated-values'); header('Content-disposition: attachment; filename="members.csv"'); $out = fopen('php://output', 'w'); fputcsv($out, $keys); foreach ($csv as $row) { fputcsv($out, $row, $delimiter); } exit; }
?> <?php } ?> <?php } ?> </fieldset> <div class="clear"></div> <?php } ?> <?php // Convert to XML so we can use the Form processor $xml = Field::toXml($this->fields, 'create'); // Gather data to pass to the form processor $data = new Hubzero\Config\Registry(); // Create a new form Hubzero\Form\Form::addFieldPath(Component::path('com_members') . DS . 'models' . DS . 'fields'); $form = new Hubzero\Form\Form('profile', array('control' => 'profile')); $form->load($xml); $form->bind($data); $scripts = array(); $toggle = array(); if ($this->fields->count() > 0) { ?> <fieldset> <legend><?php echo Lang::txt('COM_MEMBERS_REGISTER_LEGEND_PERSONAL_INFO'); ?>
/** * Serve up an example CSV file * * @return void */ public function sampleTask() { $skip = array('gid', 'gidnumber', 'regIP', 'regHost', 'modifiedDate', 'proxypassword', 'loginshell', 'ftpshell', 'shadowexpire', 'params', 'proxyuidnumber'); $fields = array(); $row = array(); $member = Member::blank(); $attribs = $member->getStructure()->getTableColumns($member->getTableName()); foreach ($attribs as $key => $desc) { if (in_array(strtolower($key), $skip)) { continue; } $example = 'Example'; $desc = preg_replace('/\\(.*\\)/', '', $desc); if (in_array($desc, array('int', 'tinyint', 'float'))) { $example = '1'; } array_push($row, $example); array_push($fields, $key); } $attribs = Field::all()->including(['options', function ($option) { $option->select('*'); }])->ordered()->rows(); foreach ($attribs as $field) { $key = $field->get('name'); if (in_array(strtolower($key), $skip)) { continue; } $example = 'Example'; if ($field->options->count() || in_array($field->get('type'), array('select', 'dropdown', 'list', 'radio', 'radios', 'checkbox', 'checkboxes'))) { $example = 'example;example;example'; } array_push($row, $example); array_push($fields, $key); } // Output header @ob_end_clean(); header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Expires: 0"); header("Content-Transfer-Encoding: binary"); header('Content-type: text/comma-separated-values'); header('Content-disposition: attachment; filename="members.csv"'); echo $this->quoteCsvRow($fields); //array_map('ucfirst', $fields)); echo $this->quoteCsvRow($row); exit; }
/** * Return data on a resource view (this will be some form of HTML) * * @param object $resource Current resource * @param string $option Name of the component * @param array $areas Active area(s) * @param string $rtrn Data to be returned * @return array */ public function onResources($model, $option, $areas, $rtrn = 'all') { $arr = array('area' => $this->_name, 'html' => '', 'metadata' => ''); // Check if our area is in the array of areas we want to return results for if (is_array($areas)) { if (!array_intersect($areas, $this->onResourcesAreas($model)) && !array_intersect($areas, array_keys($this->onResourcesAreas($model)))) { $rtrn = 'metadata'; } } if (!$model->type->params->get('plg_usage')) { return $arr; } // Display only for tools if (!$model->isTool()) { //return $arr; $rtrn == 'metadata'; } // Check if we have a needed database table $database = App::get('db'); $tables = $database->getTableList(); $table = $database->getPrefix() . 'resource_stats_tools'; $url = Route::url('index.php?option=' . $option . '&' . ($model->resource->alias ? 'alias=' . $model->resource->alias : 'id=' . $model->resource->id) . '&active=' . $this->_name); if (!in_array($table, $tables)) { $arr['html'] = '<p class="error">' . Lang::txt('PLG_RESOURCES_USAGE_MISSING_TABLE') . '</p>'; $arr['metadata'] = '<p class="usage"><a href="' . $url . '">' . Lang::txt('PLG_RESOURCES_USAGE_DETAILED') . '</a></p>'; return $arr; } // Get/set some variables $dthis = Request::getVar('dthis', date('Y') . '-' . date('m')); $period = Request::getInt('period', $this->params->get('period', 14)); include_once PATH_CORE . DS . 'components' . DS . $option . DS . 'tables' . DS . 'stats.php'; if ($model->isTool()) { $stats = new \Components\Resources\Tables\Stats\Tools($database); } else { $stats = new \Components\Resources\Tables\Stats($database); } $stats->loadStats($model->resource->id, $period); //, $dthis); $clusters = new \Components\Resources\Tables\Stats\Clusters($database); $clusters->loadStats($model->resource->id); // Are we returning HTML? if ($rtrn == 'all' || $rtrn == 'html') { $action = Request::getVar('action', ''); if ($action == 'top') { $dtm = Request::getVar('datetime', '0000-00-00 00:00:00'); if (!preg_match("/([0-9]{4})-([0-9]{2})-([0-9]{2})[ ]([0-9]{2}):([0-9]{2}):([0-9]{2})/", $dtm)) { $dtm = '0000-00-00 00:00:00'; } $this->getTopValues($model->resource->id, $dtm); return; } if ($action == 'overview') { $this->getValues($model->resource->id, Request::getInt('period', 13)); return; } include_once \Component::path('com_members') . DS . 'models' . DS . 'profile' . DS . 'field.php'; $types = array(); $field = \Components\Members\Models\Profile\Field::all()->whereEquals('name', 'orgtype')->row(); if ($field->get('id')) { $options = $field->options()->ordered()->rows(); foreach ($options as $opt) { $type = new stdClass(); $type->id = $opt->get('id'); $type->type = $opt->get('value'); $type->title = $opt->get('label'); $types[] = $type; } } // Instantiate a view $view = $this->view('default', 'browse'); // Pass the view some info $view->option = $option; $view->resource = $model->resource; $view->stats = $stats; $view->chart_path = $this->params->get('chart_path', ''); $view->map_path = $this->params->get('map_path', ''); $view->dthis = $dthis; $view->period = $period; $view->params = $this->params; $view->organizations = $types; if ($this->getError()) { $view->setError($this->getError()); } // Return the output $arr['html'] = $view->loadTemplate(); } if ($rtrn == 'all' || $rtrn == 'metadata') { if (!$stats->users) { $stats->users = 0; } if ($model->isTool()) { $arr['metadata'] = '<p class="usage"><a href="' . $url . '">' . Lang::txt('PLG_RESOURCES_USAGE_NUM_USERS_DETAILED', $stats->users) . '</a></p>'; } else { $arr['metadata'] = '<p class="usage">' . Lang::txt('PLG_RESOURCES_USAGE_NUM_USERS', $stats->users) . '</p>'; } if (isset($clusters->users) && $clusters->users && isset($clusters->classes) && $clusters->classes) { $arr['metadata'] .= '<p class="usage">' . Lang::txt('PLG_RESOURCES_USAGE_NUM_USERS_IN_CLASSES', $clusters->users, $clusters->classes) . '</p>'; } } return $arr; }
/** * Map custom fields * * @return array */ public function fieldMap() { if (!$this->mapped) { include_once __DIR__ . DS . 'profile' . DS . 'field.php'; $fields = Field::all()->ordered()->rows(); foreach ($fields as $field) { if (isset($this->_fieldMap[$field->get('name')])) { continue; } $this->_fieldMap[$field->get('name')] = array($field->get('name'), strtolower($field->get('name')), preg_replace('/[^a-zA-Z0-9]/', '', $field->get('name'))); } } return $this->_fieldMap; }
/** * Display the form for registering an account * * @param object &$xregistration * @param string $task * @return void */ private function _show_registration_form(&$xregistration = null, $task = 'create') { $username = Request::getVar('username', User::get('username'), 'get'); $isSelf = User::get('username') == $username; // Get the registration object if (!is_object($xregistration)) { $xregistration = new \Components\Members\Models\Registration(); } // Push some values to the view $rules = \Hubzero\Password\Rule::all()->whereEquals('enabled', 1)->rows(); $password_rules = array(); foreach ($rules as $rule) { if (!empty($rule['description'])) { $password_rules[] = $rule['description']; } } $this->view->registrationUsername = Field::state('registrationUsername', 'RROO', $task); $this->view->registrationPassword = Field::state('registrationPassword', 'RRHH', $task); $this->view->registrationConfirmPassword = Field::state('registrationConfirmPassword', 'RRHH', $task); $this->view->registrationFullname = Field::state('registrationFullname', 'RRRR', $task); $this->view->registrationEmail = Field::state('registrationEmail', 'RRRR', $task); $this->view->registrationConfirmEmail = Field::state('registrationConfirmEmail', 'RRRR', $task); $this->view->registrationOptIn = Field::state('registrationOptIn', 'HHHH', $task); $this->view->registrationCAPTCHA = Field::state('registrationCAPTCHA', 'HHHH', $task); $this->view->registrationTOU = Field::state('registrationTOU', 'HHHH', $task); if ($task == 'update') { if (empty($this->view->xregistration->login)) { $this->view->registrationUsername = Field::STATE_REQUIRED; } else { $this->view->registrationUsername = Field::STATE_READONLY; } $this->view->registrationPassword = Field::STATE_HIDDEN; $this->view->registrationConfirmPassword = Field::STATE_HIDDEN; } if ($task == 'edit') { $this->view->registrationUsername = Field::STATE_READONLY; $this->view->registrationPassword = Field::STATE_HIDDEN; $this->view->registrationConfirmPassword = Field::STATE_HIDDEN; } if (User::get('auth_link_id') && $task == 'create') { $this->view->registrationPassword = Field::STATE_HIDDEN; $this->view->registrationConfirmPassword = Field::STATE_HIDDEN; } $fields = Field::all()->including(['options', function ($option) { $option->select('*')->ordered(); }])->where('action_' . $task, '!=', Field::STATE_HIDDEN)->ordered()->rows(); // Display the view $this->view->set('title', Lang::txt('COM_MEMBERS_REGISTER'))->set('sitename', Config::get('sitename'))->set('config', $this->config)->set('task', $task)->set('fields', $fields)->set('showMissing', true)->set('isSelf', $isSelf)->set('password_rules', $password_rules)->set('xregistration', $xregistration)->set('registration', $xregistration->_registration)->setLayout('default')->setErrors($this->getErrors())->display(); }
/** * Retrieves option values for a profile field * * @apiMethod GET * @apiUri /members/fieldValues * @apiParameter { * "name": "field", * "description": "Profile field of interest", * "type": "string", * "required": true, * "default": "" * } * @return void */ public function fieldValuesTask() { $name = Request::getVar('field', ''); $field = Field::all()->whereEquals('name', $name)->row(); if (!$field->get('id')) { App::abort(404, 'Field not found'); } // Create object with values $response = new stdClass(); $response->type = $field->get('type'); $values = array(); if ($field->get('type') == 'country') { $countries = \Hubzero\Geocode\Geocode::countries(); foreach ($countries as $option) { // Create a new option object based on the <option /> element. $tmp = new stdClass(); $tmp->value = (string) $option->code; $tmp->label = trim((string) $option->name); // Add the option object to the result set. $values[] = $tmp; } } else { foreach ($field->options()->ordered()->rows() as $option) { $values[] = $option->toObject(); } } $response->values = $values; // Return object $this->send($response); }
/** * Save profile schema * * @return void */ public function saveprofileTask() { // Check for request forgeries Request::checkToken(); if (!User::authorise('core.manage', $this->_option) && !User::authorise('core.admin', $this->_option)) { return $this->cancelTask(); } // Incoming data $profile = json_decode(Request::getVar('profile', '{}', 'post', 'none', 2)); // Get the old schema $fields = Field::all()->including(['options', function ($option) { $option->select('*')->ordered(); }])->ordered()->rows(); // Collect old fields $oldFields = array(); foreach ($fields as $oldField) { $oldFields[$oldField->get('id')] = $oldField; } foreach ($profile->fields as $i => $element) { $field = null; $fid = isset($element->field_id) ? $element->field_id : 0; if ($fid && isset($oldFields[$fid])) { $field = $oldFields[$fid]; // Remove found fields from the list // Anything remaining will be deleted unset($oldFields[$fid]); } $field = $field ?: Field::oneOrNew($fid); $field->set(array('type' => (string) $element->field_type, 'label' => (string) $element->label, 'name' => (string) $element->name, 'description' => isset($element->field_options->description) ? (string) $element->field_options->description : '', 'ordering' => $i + 1, 'access' => isset($element->access) ? (int) $element->access : 0, 'option_other' => isset($element->field_options->include_other_option) ? (int) $element->field_options->include_other_option : '', 'option_blank' => isset($element->field_options->include_blank_option) ? (int) $element->field_options->include_blank_option : '', 'action_create' => isset($element->create) ? (int) $element->create : 1, 'action_update' => isset($element->update) ? (int) $element->update : 1, 'action_edit' => isset($element->edit) ? (int) $element->edit : 1, 'action_browse' => isset($element->browse) ? (int) $element->browse : 0)); if ($field->get('type') == 'dropdown') { $field->set('type', 'select'); } if ($field->get('type') == 'paragraph') { $field->set('type', 'textarea'); } if (!$field->save()) { Notify::error($field->getError()); continue; } // Collect old options $oldOptions = array(); foreach ($field->options as $oldOption) { $oldOptions[$oldOption->get('id')] = $oldOption; } // Does this field have any set options? if (isset($element->field_options->options)) { foreach ($element->field_options->options as $k => $opt) { $option = null; $oid = isset($opt->field_id) ? $opt->field_id : 0; if ($oid && isset($oldOptions[$oid])) { $option = $oldOptions[$oid]; // Remove found options from the list // Anything remaining will be deleted unset($oldOptions[$oid]); } $dependents = array(); if (isset($opt->dependents)) { $dependents = explode(',', trim($opt->dependents)); $dependents = array_map('trim', $dependents); foreach ($dependents as $j => $dependent) { if (!$dependent) { unset($dependents[$j]); } } } $option = $option ?: Option::oneOrNew($oid); $option->set(array('field_id' => $field->get('id'), 'label' => (string) $opt->label, 'value' => isset($opt->value) ? (string) $opt->value : '', 'checked' => isset($opt->checked) ? (int) $opt->checked : 0, 'ordering' => $k + 1, 'dependents' => json_encode($dependents))); if (!$option->save()) { Notify::error($option->getError()); continue; } } } // Remove any options not in the incoming list foreach ($oldOptions as $option) { if (!$option->destroy()) { Notify::error($option->getError()); continue; } } } // Remove any fields not in the incoming list foreach ($oldFields as $field) { if (!$field->destroy()) { Notify::error($field->getError()); continue; } } // Set success message Notify::success(Lang::txt('COM_MEMBERS_PROFILE_SCHEMA_SAVED')); // Drop through to edit form? if ($this->getTask() == 'applyprofile') { // Redirect, instead of falling through, to avoid caching issues App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller . '&task=profile', false)); } // Redirect $this->cancelTask(); }
/** * Save changes to a profile * Outputs JSON when called via AJAX, redirects to profile otherwise * * @return string JSON */ public function saveTask() { // Check if they are logged in if (User::isGuest()) { return false; } Request::checkToken(array('get', 'post')); $no_html = Request::getVar('no_html', 0); // Incoming user ID $id = Request::getInt('id', 0, 'post'); // Do we have an ID? if (!$id) { App::abort(404, Lang::txt('COM_MEMBERS_NO_ID')); } // Load the profile $member = Member::oneOrFail($id); // Name changed? $name = Request::getVar('name', array(), 'post'); if ($name && !empty($name)) { $member->set('givenName', trim($name['first'])); $member->set('middleName', trim($name['middle'])); $member->set('surname', trim($name['last'])); $name = implode(' ', $name); $name = preg_replace('/\\s+/', ' ', $name); $member->set('name', $name); } // Set profile access $visibility = Request::getVar('profileaccess', null, 'post'); if (!is_null($visibility)) { $member->set('access', $visibility); } // Check email $oldemail = $member->get('email'); $email = Request::getVar('email', null, 'post'); if (!is_null($email)) { $member->set('email', (string) $email); // Unconfirm if the email address changed if ($oldemail != $email) { // Get a new confirmation code $confirm = \Components\Members\Helpers\Utility::genemailconfirm(); $member->set('activation', $confirm); } } // Receieve email updates? $sendEmail = Request::getVar('sendEmail', null, 'post'); if (!is_null($sendEmail)) { $member->set('sendEmail', $sendEmail); } // Usage agreement $usageAgreement = Request::getVar('usageAgreement', null, 'post'); if (!is_null($usageAgreement)) { $member->set('usageAgreement', (int) $usageAgreement); } // Are we declining the terms of use? // If yes we want to set the usage agreement to 0 and profile to private $declineTOU = Request::getVar('declinetou', 0); if ($declineTOU) { $member->set('access', 0); $member->set('usageAgreement', 0); } // Save the changes if (!$member->save()) { $this->setError($member->getError()); if ($no_html) { echo json_encode($this->getErrors()); exit; } return $this->editTask($member); } // Incoming profile edits $profile = Request::getVar('profile', array(), 'post', 'none', 2); $access = Request::getVar('access', array(), 'post'); $field_to_check = Request::getVar('field_to_check', array()); $old = Profile::collect($member->profiles); $profile = array_merge($old, $profile); // Compile profile data foreach ($profile as $key => $data) { if (isset($profile[$key]) && is_array($profile[$key])) { $profile[$key] = array_filter($profile[$key]); } if (isset($profile[$key . '_other']) && trim($profile[$key . '_other'])) { if (is_array($profile[$key])) { $profile[$key][] = $profile[$key . '_other']; } else { $profile[$key] = $profile[$key . '_other']; } unset($profile[$key . '_other']); } } // Validate profile data $fields = Field::all()->including(['options', function ($option) { $option->select('*'); }])->where('action_edit', '!=', Field::STATE_HIDDEN)->ordered()->rows(); $form = new \Hubzero\Form\Form('profile', array('control' => 'profile')); $form->load(Field::toXml($fields, 'edit', $profile)); $form->bind(new \Hubzero\Config\Registry($profile)); $errors = array('_missing' => array(), '_invalid' => array()); if (!$form->validate($profile)) { foreach ($form->getErrors() as $key => $error) { // Filter out fields if (!empty($field_to_check) && !in_array($key, $field_to_check)) { continue; } if ($error instanceof \Hubzero\Form\Exception\MissingData) { $errors['_missing'][$key] = (string) $error; } $errors['_invalid'][$key] = (string) $error; $this->setError((string) $error); } } if ($this->getError()) { if ($no_html) { echo json_encode($errors); exit; } return $this->editTask($member); } // Save profile data if (!$member->saveProfile($profile, $access)) { $this->setError($member->getError()); if ($no_html) { echo json_encode($this->getErrors()); exit; } return $this->editTask($member); } $email = $member->get('email'); // Make sure certain changes make it back to the user table if ($member->get('id') == User::get('id')) { $user = App::get('session')->get('user'); if ($member->get('name') != $user->get('name')) { $user->set('name', $member->get('name')); } // Update session if email is changing if ($member->get('email') != $user->get('email')) { $user->set('email', $member->get('email')); // Add item to session to mark that the user changed emails // this way we can serve profile images for these users but not all // unconfirmed users App::get('session')->set('userchangedemail', 1); } App::get('session')->set('user', $user); } // Send a new confirmation code AFTER we've successfully saved the changes to the e-mail address if ($email != $oldemail) { $this->_sendConfirmationCode($member->get('username'), $email, $confirm); } // If were declinging the terms we want to logout user and tell the javascript if ($declineTOU) { App::get('auth')->logout(); echo json_encode(array('loggedout' => true)); return; } if ($no_html) { // Output JSON echo json_encode(array('success' => true)); exit; } // Redirect App::redirect(Route::url('index.php?option=' . $this->_option . ($id ? '&id=' . $id . '&active=profile' : ''))); }
/** * Check Data integrity * * @return $this Current object */ public function check() { // Run save check method /*if (!$this->record->entry->check()) { array_push($this->record->errors, $this->record->entry->getError()); return $this; }*/ $xregistration = new \Components\Members\Models\Registration(); $xregistration->loadProfile($this->record->entry); // Check that required fields were filled in properly if (!$xregistration->check('edit', $this->record->entry->get('id'), array())) { $skip = array(); if (!empty($xregistration->_missing)) { foreach ($xregistration->_missing as $key => $missing) { if ($this->_mode == 'PATCH') { $skip[] = $key; continue; } array_push($this->record->errors, $missing); } } if (!empty($xregistration->_invalid)) { foreach ($xregistration->_invalid as $key => $invalid) { if (in_array($key, $skip)) { continue; } array_push($this->record->errors, $invalid); } } } // Validate profile data $fields = \Components\Members\Models\Profile\Field::all()->including(['options', function ($option) { $option->select('*'); }])->where('action_edit', '!=', \Components\Members\Models\Profile\Field::STATE_HIDDEN)->ordered()->rows(); $form = new \Hubzero\Form\Form('profile', array('control' => 'profile')); $form->load(\Components\Members\Models\Profile\Field::toXml($fields, 'edit')); $form->bind(new \Hubzero\Config\Registry($this->_profile)); if (!$form->validate($this->_profile)) { foreach ($form->getErrors() as $key => $error) { array_push($this->record->errors, (string) $error); } } return $this; }