Compare commits

...

1 Commits

Author SHA1 Message Date
Matheus Garcia 5a0b202d31 Adaptação para Moodle 3.4 7 years ago
  1. 50
      README.txt
  2. 21
      define.class.php
  3. 136
      field.class.php
  4. 14
      lang/en/profilefield_cpf.php
  5. 15
      lang/pt_br/profilefield_cpf.php
  6. 13
      version.php

50
README.txt

@ -0,0 +1,50 @@
CPF Profile Field
===
This is a CPF field to user profiles into moodle.
The Cadastro de Pessoas Físicas (CPF) – Portuguese for Natural Persons Register – is a number attributed by the Brazilian revenue agency (Receita Federal – Federal Revenue) to both Brazilians and resident aliens who pay taxes or take part, directly or indirectly, in activities that provide revenue for any of the dozens of different types of taxes existing in Brazil.
More about CPF: http://en.wikipedia.org/wiki/Cadastro_de_Pessoas_F%C3%ADsicas
For Everyone
---
This plugin was made to add possibility to add CPF field in the user profile form.
Moodle documentation about profilefields -> http://docs.moodle.org/26/en/User_profile_fields
I recommend to insert a mask plugin to the CPF field. I did as follows:
- Added the Jquery masked Input plugin -> http://digitalbush.com/projects/masked-input-plugin/
- Added the follow code relative to the masked field into the selected theme file:
> jQuery("#profilefield_cpf").mask("999.999.999-99");
Para Brasileiros
---
Como CPF é um padrão brasileiro, a explicação será em português. :)
Este plugin foi criado para possibilitar a inclusão do campo cpf nos formulários de criação de novos usuários e também na alteração dos dados do usuário.
Documentação de como utilizar os profilefields -> http://docs.moodle.org/26/en/User_profile_fields
Recomendo inserir um plugin de máscara para o campo CPF. Eu fiz da seguinte forma:
- Adicionei o plugin Jquery masked Input -> http://digitalbush.com/projects/masked-input-plugin/
- Adicionei o seguinte código referente à mascara do campo no tema utilizado:
> jQuery("#profilefield_cpf").mask("999.999.999-99");
Installation
---
As usual:
* Download the source code (zip or git clone)
* Uncompress to user/profile/field/cpf
* Go to **Notifications**
License
---
It is released as GPL v3.
Authors:
* Willian Mano - http://willianmano.net
Copyright 2014 onwards Willian Mano (http://willianmano.net)

21
define.class.php

@ -1,14 +1,19 @@
<?php
class profile_define_cpf extends profile_define_base {
function define_form_specific($form) {
/// Default data
$form->addElement('text', 'defaultdata', get_string('profiledefaultdata', 'admin'), 'size="50"');
$form->setType('defaultdata', PARAM_TEXT);
public function define_form_specific($form) {
// Default data.
$form->addElement('text', 'defaultdata', 'Informe o CPF');
$form->setType('defaultdata', PARAM_TEXT);
$form->setDefault('defaultdata', '(somente dígitos)')
}
function define_validate_specific($data) {
$errors = array();
// Make sure defaultdata is not false
if ($data->defaultdata == false) {
$errors['cpf'] = 'Obrigatório'; //get_string('noprovided', 'profilefield_cpf');
}
return $errors;
}
}

136
field.class.php

@ -1,57 +1,117 @@
<?php
class profile_field_cpf extends profile_field_base {
/**
* Overwrite the base class to display the data for this field
*/
function display_data() {
/// Default formatting
$data = parent::display_data();
$data = str_pad($data, 11, '0', STR_PAD_LEFT); // Prevent low digits formatting errors
if ($data !== '') {
$data = substr($data,0,3).'.'.substr($data,3,3).'.'.substr($data,6,3).'-'.substr($data,9,2);
public function edit_field_add($mform) {
$mform->addElement(
'text',
$this->inputname,
format_string($this->field->name),
'maxlength="11" size="11" id="profilefield_cpf" pattern="[0-9]{11}" data-tip="Informe o CPF (apenas números)" title="Apenas números"'
);
$mform->setType($this->inputname, PARAM_TEXT);
// if ($this->is_required() and !has_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM))) {
// $mform->addRule($this->inputname, get_string('regexerrormessage', 'pluginname'), 'regex', '\d{11}');
$mform->addRule($this->inputname, get_string('onlydigits', 'profilefield_cpf'), 'numeric', null, 'client');
//get_string('required'), 'nonzero', null, 'client');
// }
}
public function edit_validate_field($usernew) {
$return = array();
if (isset($usernew->{$this->inputname})) {
if (!$this->exists($usernew->{$this->inputname}, $usernew->id)) {
$return[$this->inputname] = get_string('cpfexists', 'profilefield_cpf');
} else if (!$this->validatecpf($usernew->{$this->inputname})) {
$return[$this->inputname] = get_string('invalidcpf', 'profilefield_cpf');
}
}
return $data;
return $return;
}
function edit_field_add($mform) {
/// Create the form field
$mform->addElement('text', $this->inputname, format_string($this->field->name), 'maxlength="11" size="11"');
$mform->setType($this->inputname, PARAM_TEXT);
// Define formatação para o campo de CPF
public function display_data() {
if( preg_match( "/^(\d{3})(\d{3})(\d{3})(\d{2})$/", $this->data, $matches ) ) {
$result = $matches[1] . '.' .$matches[2] . '.' . $matches[3] . '-' . $matches[4];
} else {
$result = $this->data;
}
return $result;
}
/*
Testa se já existe algum usuário com este mesmo número de CPF.
Se existir, retorna falso, do contrário retorna verdadeiro.
*/
private function exists($cpf = null, $userid = 0) {
global $DB;
// Por definição, se for admin, aceita 00000000000
if( is_siteadmin() && $cpf == '00000000000') {
return true;
}
// Verifica se um número foi informado.
if (is_null($cpf)) {
return false;
}
$sql = "SELECT uid.data FROM {user_info_data} uid
INNER JOIN {user_info_field} uif ON uid.fieldid = uif.id
INNER JOIN {user} u on uid.userid = u.id
WHERE uif.datatype = 'cpf' AND u.deleted = 0 AND uid.data = :cpf AND uid.userid <> :userid";
$params['cpf'] = $cpf;
$params['userid'] = $userid;
$dbcpf = current($DB->get_records_sql($sql, $params));
if (!empty($dbcpf)) {
return false;
} else {
return true;
}
}
function edit_validate_field($usernew) {
// Get default validation errors
$errors = parent::edit_validate_field($usernew);
if ($errors) {
return $errors;
/*
Verifica se um determinado valor passado corresponde a um número de CPF válido
Retorna verdadeiro apenas se DV bater com esperado
*/
private function validatecpf($cpf = null) {
// Por definição, se for admin, aceita 00000000000
if( is_siteadmin() && $cpf == '00000000000') {
return true;
}
// Verifica se um numero foi informado.
if (is_null($cpf)) {
return false;
}
if (!is_numeric($cpf)) {
return false;
}
//$cpf = str_pad($cpf, 11, '0', STR_PAD_LEFT);
// Based on script by Moacir, in http://codigofonte.uol.com.br/codigos/validacao-de-cpf-com-php
if (isset($usernew->{$this->inputname})) {
$cpf = $usernew->{$this->inputname};
if (!ctype_digit($cpf)) {
return array($this->inputname => get_string('cpf_digits', 'profilefield_cpf'));
}
if (strlen($cpf) != 11) {
return array($this->inputname => get_string('cpf_size', 'profilefield_cpf'));
}
if (in_array($cpf, array('00000000000', '11111111111', '22222222222', '33333333333', '44444444444', '55555555555', '66666666666', '77777777777', '88888888888', '99999999999'))) {
return array($this->inputname => get_string('cpf_invalid', 'profilefield_cpf'));
}
// Verifica se o numero de digitos informados eh igual a 11.
if (strlen($cpf) != 11) {
return false;
} else if ($cpf == '00000000000' || $cpf == '11111111111' || $cpf == '22222222222' ||
$cpf == '33333333333' || $cpf == '44444444444' || $cpf == '55555555555' ||
$cpf == '66666666666' || $cpf == '77777777777' || $cpf == '88888888888' ||
$cpf == '99999999999') {
return false;
} else {
// Calcula os digitos verificadores para verificar se o CPF eh valido.
for ($t = 9; $t < 11; $t++) {
for ($d = 0, $c = 0; $c < $t; $c++) {
$v = substr($cpf,$c,1);
$d += $v * (($t + 1) - $c);
$d += $cpf{$c} * (($t + 1) - $c);
}
$v = substr($cpf,$c,1);
$d = ((10 * $d) % 11) % 10;
if ($v != $d) {
return array($this->inputname => get_string('cpf_invalid', 'profilefield_cpf'));
if ($cpf{$c} != $d) {
return false;
}
}
return true;
}
return $errors;
}
}

14
lang/en/profilefield_cpf.php

@ -16,14 +16,14 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'profilefield_text', language 'en', branch 'MOODLE_20_STABLE'
* Strings for component 'cpf_text', language 'en'
*
* @package profilefield_text
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @package cpf_text
* @copyright 2014 onwards Willian Mano {@link http://willianmano.net}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'Brazilian CPF';
$string['cpf_digits'] = 'CPF must have only numeric digits';
$string['cpf_size'] = 'CPF must have 11 digits';
$string['cpf_invalid'] = 'Invalid CPF';
$string['pluginname'] = 'CPF input';
$string['invalidcpf'] = 'Invalid CPF';
$string['cpfexists'] = 'CPF already exists';
$string['onlydigits'] = 'Only digits are accepted';

15
lang/pt_br/profilefield_cpf.php

@ -16,14 +16,15 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'profilefield_text', language 'en', branch 'MOODLE_20_STABLE'
* Strings for component 'cpf_text', language 'pt_br'
*
* @package profilefield_text
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @package cpf_text
* @copyright 2014 onwards Willian Mano {@link http://willianmano.net}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['pluginname'] = 'CPF brasileiro';
$string['cpf_digits'] = 'O CPF deve ser formado apenas por dígitos numéricos';
$string['cpf_size'] = 'O CPF deve ter exatos 11 dígitos';
$string['cpf_invalid'] = 'CPF inválido';
$string['pluginname'] = 'Campo de CPF';
$string['invalidcpf'] = 'CPF inválido';
$string['cpfexists'] = 'CPF já existe';
$string['onlydigits'] = 'Informe apenas dígitos';
$string['required'] = 'É obrigatório informar o CPF';

13
version.php

@ -15,14 +15,15 @@
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package profilefield
* @subpackage text
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @package cpf
* @copyright 2014 onwards Willian Mano {@link http://willianmano.net}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2013050100; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2013050100; // Requires this Moodle version
$plugin->component = 'profilefield_cpf'; // Full name of the plugin (used for diagnostics)
$plugin->version = 2017051702; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2012062500; // Requires this Moodle version.
$plugin->maturity = MATURITY_STABLE;
$plugin->release = 'Version for Moodle 2.2 onwards';
$plugin->component = 'profilefield_cpf'; // Full name of the plugin (used for diagnostics).

Loading…
Cancel
Save