Browse Source

Adaptação para Moodle 3.4

MOODLE_34_STABLE
Matheus Garcia 7 years ago
parent
commit
5a0b202d31
  1. 50
      README.txt
  2. 19
      define.class.php
  3. 130
      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)

19
define.class.php

@ -1,14 +1,19 @@
<?php <?php
class profile_define_cpf extends profile_define_base { class profile_define_cpf extends profile_define_base {
public function define_form_specific($form) {
function define_form_specific($form) { // Default data.
/// Default data $form->addElement('text', 'defaultdata', 'Informe o CPF');
$form->addElement('text', 'defaultdata', get_string('profiledefaultdata', 'admin'), 'size="50"');
$form->setType('defaultdata', PARAM_TEXT); $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;
}
} }

130
field.class.php

@ -1,57 +1,117 @@
<?php <?php
class profile_field_cpf extends profile_field_base { class profile_field_cpf extends profile_field_base {
/** public function edit_field_add($mform) {
* Overwrite the base class to display the data for this field $mform->addElement(
*/ 'text',
function display_data() { $this->inputname,
/// Default formatting format_string($this->field->name),
$data = parent::display_data(); 'maxlength="11" size="11" id="profilefield_cpf" pattern="[0-9]{11}" data-tip="Informe o CPF (apenas números)" title="Apenas números"'
$data = str_pad($data, 11, '0', STR_PAD_LEFT); // Prevent low digits formatting errors );
if ($data !== '') { $mform->setType($this->inputname, PARAM_TEXT);
$data = substr($data,0,3).'.'.substr($data,3,3).'.'.substr($data,6,3).'-'.substr($data,9,2); // 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');
// }
} }
return $data;
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 $return;
} }
function edit_field_add($mform) { // Define formatação para o campo de CPF
/// Create the form field public function display_data() {
$mform->addElement('text', $this->inputname, format_string($this->field->name), 'maxlength="11" size="11"'); if( preg_match( "/^(\d{3})(\d{3})(\d{3})(\d{2})$/", $this->data, $matches ) ) {
$mform->setType($this->inputname, PARAM_TEXT); $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;
function edit_validate_field($usernew) { // Por definição, se for admin, aceita 00000000000
// Get default validation errors if( is_siteadmin() && $cpf == '00000000000') {
$errors = parent::edit_validate_field($usernew); return true;
if ($errors) {
return $errors;
} }
// Based on script by Moacir, in http://codigofonte.uol.com.br/codigos/validacao-de-cpf-com-php // Verifica se um número foi informado.
if (isset($usernew->{$this->inputname})) { if (is_null($cpf)) {
$cpf = $usernew->{$this->inputname}; return false;
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')); $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;
} }
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 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);
// 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 ($t = 9; $t < 11; $t++) {
for ($d = 0, $c = 0; $c < $t; $c++) { for ($d = 0, $c = 0; $c < $t; $c++) {
$v = substr($cpf,$c,1); $d += $cpf{$c} * (($t + 1) - $c);
$d += $v * (($t + 1) - $c);
} }
$v = substr($cpf,$c,1);
$d = ((10 * $d) % 11) % 10; $d = ((10 * $d) % 11) % 10;
if ($v != $d) { if ($cpf{$c} != $d) {
return array($this->inputname => get_string('cpf_invalid', 'profilefield_cpf')); 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/>. // 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 * @package cpf_text
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @copyright 2014 onwards Willian Mano {@link http://willianmano.net}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/ */
$string['pluginname'] = 'Brazilian CPF'; $string['pluginname'] = 'CPF input';
$string['cpf_digits'] = 'CPF must have only numeric digits'; $string['invalidcpf'] = 'Invalid CPF';
$string['cpf_size'] = 'CPF must have 11 digits'; $string['cpfexists'] = 'CPF already exists';
$string['cpf_invalid'] = 'Invalid CPF'; $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/>. // 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 * @package cpf_text
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @copyright 2014 onwards Willian Mano {@link http://willianmano.net}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/ */
$string['pluginname'] = 'CPF brasileiro'; $string['pluginname'] = 'Campo de CPF';
$string['cpf_digits'] = 'O CPF deve ser formado apenas por dígitos numéricos'; $string['invalidcpf'] = 'CPF inválido';
$string['cpf_size'] = 'O CPF deve ter exatos 11 dígitos'; $string['cpfexists'] = 'CPF já existe';
$string['cpf_invalid'] = 'CPF inválido'; $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/>. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* @package profilefield * @package cpf
* @subpackage text * @copyright 2014 onwards Willian Mano {@link http://willianmano.net}
* @copyright 2007 onwards Shane Elliot {@link http://pukunui.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/ */
defined('MOODLE_INTERNAL') || die(); defined('MOODLE_INTERNAL') || die();
$plugin->version = 2013050100; // The current plugin version (Date: YYYYMMDDXX) $plugin->version = 2017051702; // The current plugin version (Date: YYYYMMDDXX).
$plugin->requires = 2013050100; // Requires this Moodle version $plugin->requires = 2012062500; // Requires this Moodle version.
$plugin->component = 'profilefield_cpf'; // Full name of the plugin (used for diagnostics) $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