Commit 629077c9cf69e57329dcb0631442cb5dd118c5e3

Authored by Everton Muniz
Committed by GitHub
2 parents 9073dc2c d0deee7d
Exists in 2.8 and in 8 other branches 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7

Merge pull request #3731 from portabilis/encoding-fix

Encoding fix
composer.json
... ... @@ -9,6 +9,7 @@
9 9 "require": {
10 10 "portabilis/jasperphp": "v1.2.0",
11 11 "robmorgan/phinx": "v0.8.1",
12   - "gilbitron/php-simplecache": "^1.4"
  12 + "gilbitron/php-simplecache": "^1.4",
  13 + "cocur/slugify": "^3.1"
13 14 }
14 15 }
... ...
composer.lock
1 1 {
2 2 "_readme": [
3 3 "This file locks the dependencies of your project to a known state",
4   - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
  4 + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
5 5 "This file is @generated automatically"
6 6 ],
7   - "content-hash": "54fd5e2dc075b55d008b31c2cdc6776e",
  7 + "content-hash": "ceda83eeb3051ebd372f452e2fa30a93",
8 8 "packages": [
9 9 {
  10 + "name": "cocur/slugify",
  11 + "version": "v3.1",
  12 + "source": {
  13 + "type": "git",
  14 + "url": "https://github.com/cocur/slugify.git",
  15 + "reference": "b2ccf7b735f4f3df3979aef2e1ebf8e19ca772f7"
  16 + },
  17 + "dist": {
  18 + "type": "zip",
  19 + "url": "https://api.github.com/repos/cocur/slugify/zipball/b2ccf7b735f4f3df3979aef2e1ebf8e19ca772f7",
  20 + "reference": "b2ccf7b735f4f3df3979aef2e1ebf8e19ca772f7",
  21 + "shasum": ""
  22 + },
  23 + "require": {
  24 + "ext-mbstring": "*",
  25 + "php": ">=5.5.9"
  26 + },
  27 + "require-dev": {
  28 + "laravel/framework": "~5.1",
  29 + "latte/latte": "~2.2",
  30 + "league/container": "^2.2.0",
  31 + "mikey179/vfsstream": "~1.6",
  32 + "mockery/mockery": "~0.9",
  33 + "nette/di": "~2.2",
  34 + "phpunit/phpunit": "~4.8|~5.2",
  35 + "pimple/pimple": "~1.1",
  36 + "plumphp/plum": "~0.1",
  37 + "silex/silex": "~1.3",
  38 + "symfony/config": "~2.4|~3.0",
  39 + "symfony/dependency-injection": "~2.4|~3.0",
  40 + "symfony/http-kernel": "~2.4|~3.0",
  41 + "twig/twig": "~1.26|~2.0",
  42 + "zendframework/zend-modulemanager": "~2.2",
  43 + "zendframework/zend-servicemanager": "~2.2",
  44 + "zendframework/zend-view": "~2.2"
  45 + },
  46 + "type": "library",
  47 + "autoload": {
  48 + "psr-4": {
  49 + "Cocur\\Slugify\\": "src"
  50 + }
  51 + },
  52 + "notification-url": "https://packagist.org/downloads/",
  53 + "license": [
  54 + "MIT"
  55 + ],
  56 + "authors": [
  57 + {
  58 + "name": "Ivo Bathke",
  59 + "email": "ivo.bathke@gmail.com"
  60 + },
  61 + {
  62 + "name": "Florian Eckerstorfer",
  63 + "email": "florian@eckerstorfer.co",
  64 + "homepage": "https://florian.ec"
  65 + }
  66 + ],
  67 + "description": "Converts a string into a slug.",
  68 + "keywords": [
  69 + "slug",
  70 + "slugify"
  71 + ],
  72 + "time": "2018-01-22T09:00:48+00:00"
  73 + },
  74 + {
10 75 "name": "gilbitron/php-simplecache",
11 76 "version": "1.4.2",
12 77 "source": {
... ... @@ -204,21 +269,22 @@
204 269 },
205 270 {
206 271 "name": "symfony/config",
207   - "version": "v3.4.8",
  272 + "version": "v3.4.11",
208 273 "source": {
209 274 "type": "git",
210 275 "url": "https://github.com/symfony/config.git",
211   - "reference": "7c2a9d44f4433863e9bca682e7f03609234657f9"
  276 + "reference": "73e055cf2e6467715f187724a0347ea32079967c"
212 277 },
213 278 "dist": {
214 279 "type": "zip",
215   - "url": "https://api.github.com/repos/symfony/config/zipball/7c2a9d44f4433863e9bca682e7f03609234657f9",
216   - "reference": "7c2a9d44f4433863e9bca682e7f03609234657f9",
  280 + "url": "https://api.github.com/repos/symfony/config/zipball/73e055cf2e6467715f187724a0347ea32079967c",
  281 + "reference": "73e055cf2e6467715f187724a0347ea32079967c",
217 282 "shasum": ""
218 283 },
219 284 "require": {
220 285 "php": "^5.5.9|>=7.0.8",
221   - "symfony/filesystem": "~2.8|~3.0|~4.0"
  286 + "symfony/filesystem": "~2.8|~3.0|~4.0",
  287 + "symfony/polyfill-ctype": "~1.8"
222 288 },
223 289 "conflict": {
224 290 "symfony/dependency-injection": "<3.3",
... ... @@ -263,20 +329,20 @@
263 329 ],
264 330 "description": "Symfony Config Component",
265 331 "homepage": "https://symfony.com",
266   - "time": "2018-03-19T22:32:39+00:00"
  332 + "time": "2018-05-14T16:49:53+00:00"
267 333 },
268 334 {
269 335 "name": "symfony/console",
270   - "version": "v3.4.8",
  336 + "version": "v3.4.11",
271 337 "source": {
272 338 "type": "git",
273 339 "url": "https://github.com/symfony/console.git",
274   - "reference": "d4bb70fa24d540c309d88a9d6e43fb2d339b1fbf"
  340 + "reference": "36f83f642443c46f3cf751d4d2ee5d047d757a27"
275 341 },
276 342 "dist": {
277 343 "type": "zip",
278   - "url": "https://api.github.com/repos/symfony/console/zipball/d4bb70fa24d540c309d88a9d6e43fb2d339b1fbf",
279   - "reference": "d4bb70fa24d540c309d88a9d6e43fb2d339b1fbf",
  344 + "url": "https://api.github.com/repos/symfony/console/zipball/36f83f642443c46f3cf751d4d2ee5d047d757a27",
  345 + "reference": "36f83f642443c46f3cf751d4d2ee5d047d757a27",
280 346 "shasum": ""
281 347 },
282 348 "require": {
... ... @@ -297,7 +363,7 @@
297 363 "symfony/process": "~3.3|~4.0"
298 364 },
299 365 "suggest": {
300   - "psr/log": "For using the console logger",
  366 + "psr/log-implementation": "For using the console logger",
301 367 "symfony/event-dispatcher": "",
302 368 "symfony/lock": "",
303 369 "symfony/process": ""
... ... @@ -332,20 +398,20 @@
332 398 ],
333 399 "description": "Symfony Console Component",
334 400 "homepage": "https://symfony.com",
335   - "time": "2018-04-03T05:22:50+00:00"
  401 + "time": "2018-05-16T08:49:21+00:00"
336 402 },
337 403 {
338 404 "name": "symfony/debug",
339   - "version": "v3.4.8",
  405 + "version": "v3.4.11",
340 406 "source": {
341 407 "type": "git",
342 408 "url": "https://github.com/symfony/debug.git",
343   - "reference": "9cf7c2271cfb89ef9727db1b740ca77be57bf9d7"
  409 + "reference": "b28fd73fefbac341f673f5efd707d539d6a19f68"
344 410 },
345 411 "dist": {
346 412 "type": "zip",
347   - "url": "https://api.github.com/repos/symfony/debug/zipball/9cf7c2271cfb89ef9727db1b740ca77be57bf9d7",
348   - "reference": "9cf7c2271cfb89ef9727db1b740ca77be57bf9d7",
  413 + "url": "https://api.github.com/repos/symfony/debug/zipball/b28fd73fefbac341f673f5efd707d539d6a19f68",
  414 + "reference": "b28fd73fefbac341f673f5efd707d539d6a19f68",
349 415 "shasum": ""
350 416 },
351 417 "require": {
... ... @@ -388,24 +454,25 @@
388 454 ],
389 455 "description": "Symfony Debug Component",
390 456 "homepage": "https://symfony.com",
391   - "time": "2018-04-03T05:22:50+00:00"
  457 + "time": "2018-05-16T14:03:39+00:00"
392 458 },
393 459 {
394 460 "name": "symfony/filesystem",
395   - "version": "v3.4.8",
  461 + "version": "v3.4.11",
396 462 "source": {
397 463 "type": "git",
398 464 "url": "https://github.com/symfony/filesystem.git",
399   - "reference": "253a4490b528597aa14d2bf5aeded6f5e5e4a541"
  465 + "reference": "8e03ca3fa52a0f56b87506f38cf7bd3f9442b3a0"
400 466 },
401 467 "dist": {
402 468 "type": "zip",
403   - "url": "https://api.github.com/repos/symfony/filesystem/zipball/253a4490b528597aa14d2bf5aeded6f5e5e4a541",
404   - "reference": "253a4490b528597aa14d2bf5aeded6f5e5e4a541",
  469 + "url": "https://api.github.com/repos/symfony/filesystem/zipball/8e03ca3fa52a0f56b87506f38cf7bd3f9442b3a0",
  470 + "reference": "8e03ca3fa52a0f56b87506f38cf7bd3f9442b3a0",
405 471 "shasum": ""
406 472 },
407 473 "require": {
408   - "php": "^5.5.9|>=7.0.8"
  474 + "php": "^5.5.9|>=7.0.8",
  475 + "symfony/polyfill-ctype": "~1.8"
409 476 },
410 477 "type": "library",
411 478 "extra": {
... ... @@ -437,20 +504,75 @@
437 504 ],
438 505 "description": "Symfony Filesystem Component",
439 506 "homepage": "https://symfony.com",
440   - "time": "2018-02-22T10:48:49+00:00"
  507 + "time": "2018-05-16T08:49:21+00:00"
  508 + },
  509 + {
  510 + "name": "symfony/polyfill-ctype",
  511 + "version": "v1.8.0",
  512 + "source": {
  513 + "type": "git",
  514 + "url": "https://github.com/symfony/polyfill-ctype.git",
  515 + "reference": "7cc359f1b7b80fc25ed7796be7d96adc9b354bae"
  516 + },
  517 + "dist": {
  518 + "type": "zip",
  519 + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/7cc359f1b7b80fc25ed7796be7d96adc9b354bae",
  520 + "reference": "7cc359f1b7b80fc25ed7796be7d96adc9b354bae",
  521 + "shasum": ""
  522 + },
  523 + "require": {
  524 + "php": ">=5.3.3"
  525 + },
  526 + "type": "library",
  527 + "extra": {
  528 + "branch-alias": {
  529 + "dev-master": "1.8-dev"
  530 + }
  531 + },
  532 + "autoload": {
  533 + "psr-4": {
  534 + "Symfony\\Polyfill\\Ctype\\": ""
  535 + },
  536 + "files": [
  537 + "bootstrap.php"
  538 + ]
  539 + },
  540 + "notification-url": "https://packagist.org/downloads/",
  541 + "license": [
  542 + "MIT"
  543 + ],
  544 + "authors": [
  545 + {
  546 + "name": "Symfony Community",
  547 + "homepage": "https://symfony.com/contributors"
  548 + },
  549 + {
  550 + "name": "Gert de Pagter",
  551 + "email": "BackEndTea@gmail.com"
  552 + }
  553 + ],
  554 + "description": "Symfony polyfill for ctype functions",
  555 + "homepage": "https://symfony.com",
  556 + "keywords": [
  557 + "compatibility",
  558 + "ctype",
  559 + "polyfill",
  560 + "portable"
  561 + ],
  562 + "time": "2018-04-30T19:57:29+00:00"
441 563 },
442 564 {
443 565 "name": "symfony/polyfill-mbstring",
444   - "version": "v1.7.0",
  566 + "version": "v1.8.0",
445 567 "source": {
446 568 "type": "git",
447 569 "url": "https://github.com/symfony/polyfill-mbstring.git",
448   - "reference": "78be803ce01e55d3491c1397cf1c64beb9c1b63b"
  570 + "reference": "3296adf6a6454a050679cde90f95350ad604b171"
449 571 },
450 572 "dist": {
451 573 "type": "zip",
452   - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/78be803ce01e55d3491c1397cf1c64beb9c1b63b",
453   - "reference": "78be803ce01e55d3491c1397cf1c64beb9c1b63b",
  574 + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/3296adf6a6454a050679cde90f95350ad604b171",
  575 + "reference": "3296adf6a6454a050679cde90f95350ad604b171",
454 576 "shasum": ""
455 577 },
456 578 "require": {
... ... @@ -462,7 +584,7 @@
462 584 "type": "library",
463 585 "extra": {
464 586 "branch-alias": {
465   - "dev-master": "1.7-dev"
  587 + "dev-master": "1.8-dev"
466 588 }
467 589 },
468 590 "autoload": {
... ... @@ -496,24 +618,25 @@
496 618 "portable",
497 619 "shim"
498 620 ],
499   - "time": "2018-01-30T19:27:44+00:00"
  621 + "time": "2018-04-26T10:06:28+00:00"
500 622 },
501 623 {
502 624 "name": "symfony/yaml",
503   - "version": "v3.4.8",
  625 + "version": "v3.4.11",
504 626 "source": {
505 627 "type": "git",
506 628 "url": "https://github.com/symfony/yaml.git",
507   - "reference": "a42f9da85c7c38d59f5e53f076fe81a091f894d0"
  629 + "reference": "c5010cc1692ce1fa328b1fb666961eb3d4a85bb0"
508 630 },
509 631 "dist": {
510 632 "type": "zip",
511   - "url": "https://api.github.com/repos/symfony/yaml/zipball/a42f9da85c7c38d59f5e53f076fe81a091f894d0",
512   - "reference": "a42f9da85c7c38d59f5e53f076fe81a091f894d0",
  633 + "url": "https://api.github.com/repos/symfony/yaml/zipball/c5010cc1692ce1fa328b1fb666961eb3d4a85bb0",
  634 + "reference": "c5010cc1692ce1fa328b1fb666961eb3d4a85bb0",
513 635 "shasum": ""
514 636 },
515 637 "require": {
516   - "php": "^5.5.9|>=7.0.8"
  638 + "php": "^5.5.9|>=7.0.8",
  639 + "symfony/polyfill-ctype": "~1.8"
517 640 },
518 641 "conflict": {
519 642 "symfony/console": "<3.4"
... ... @@ -554,7 +677,7 @@
554 677 ],
555 678 "description": "Symfony Yaml Component",
556 679 "homepage": "https://symfony.com",
557   - "time": "2018-04-03T05:14:20+00:00"
  680 + "time": "2018-05-03T23:18:14+00:00"
558 681 }
559 682 ],
560 683 "packages-dev": [],
... ...
ieducar/intranet/include/modules/clsModulesAuditoriaGeral.inc.php
... ... @@ -29,6 +29,7 @@
29 29 */
30 30  
31 31 require_once 'include/pmieducar/geral.inc.php';
  32 +require_once 'lib/Utils/SafeJson.php';
32 33  
33 34 /**
34 35 * clsModulesAuditoriaGeral class.
... ... @@ -108,7 +109,7 @@ class clsModulesAuditoriaGeral
108 109 function converteArrayDadosParaJson($dados) {
109 110 $dados = $this->removeKeyNaoNumerica($dados);
110 111 $dados = $this->removeKeysDesnecessarias($dados);
111   - $dados = json_encode($dados);
  112 + $dados = SafeJson::encode($dados);
112 113 $dados = str_replace("'", "''", $dados);
113 114 return $dados;
114 115 }
... ...
ieducar/intranet/include/pmieducar/clsPmieducarConfiguracoesGerais.inc.php
... ... @@ -29,6 +29,7 @@
29 29 */
30 30  
31 31 require_once 'include/pmieducar/geral.inc.php';
  32 +require_once 'lib/Utils/SafeJson.php';
32 33  
33 34 /**
34 35 * clsPmieducarConfiguracoesGerais class.
... ... @@ -234,7 +235,7 @@ class clsPmieducarConfiguracoesGerais
234 235 }
235 236  
236 237 if (is_array($this->custom_labels)) {
237   - $customLabels = json_encode($this->custom_labels);
  238 + $customLabels = SafeJson::encode($this->custom_labels);
238 239 $set[] = "custom_labels = '{$customLabels}'";
239 240 }
240 241  
... ...
ieducar/lib/Portabilis/Controller/ApiCoreController.php
... ... @@ -44,6 +44,7 @@ require_once &#39;lib/Portabilis/Array/Utils.php&#39;;
44 44 require_once 'lib/Portabilis/Utils/Database.php';
45 45 require_once 'lib/Portabilis/String/Utils.php';
46 46 require_once 'lib/Portabilis/Utils/User.php';
  47 +require_once 'lib/Utils/SafeJson.php';
47 48  
48 49 class ApiCoreController extends Core_Controller_Page_EditController
49 50 {
... ... @@ -255,14 +256,14 @@ class ApiCoreController extends Core_Controller_Page_EditController
255 256 $this->appendResponse('msgs', $this->messenger->getMsgs());
256 257 $this->appendResponse('any_error_msg', $this->messenger->hasMsgWithType('error'));
257 258  
258   - $response = json_encode($this->response);
  259 + $response = SafeJson::encode($this->response);
259 260 }
260 261 catch (Exception $e){
261 262 error_log("Erro inesperado no metodo prepareResponse da classe ApiCoreController: {$e->getMessage()}");
262 263 $response = array('msgs' => array('msg' => 'Erro inesperado no servidor. Por favor, tente novamente.',
263 264 'type' => 'error'));
264 265  
265   - $response = json_encode($response);
  266 + $response = SafeJson::encode($response);
266 267 }
267 268  
268 269 echo $response;
... ...
ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchCustom.php
... ... @@ -32,6 +32,7 @@
32 32 require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php';
33 33 require_once 'lib/Portabilis/Utils/Database.php';
34 34 require_once 'lib/Portabilis/String/Utils.php';
  35 +require_once 'lib/Utils/SafeJson.php';
35 36  
36 37 /**
37 38 * Portabilis_View_Helper_Input_MultipleSearchCustom class.
... ... @@ -64,7 +65,7 @@ class Portabilis_View_Helper_Input_Resource_MultipleSearchCustom extends Portabi
64 65 $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} };
65 66 $optionsVarName.placeholder = safeUtf8Decode('Selecione');";
66 67  
67   - $json = json_encode($options['options']['options']['values']);
  68 + $json = SafeJson::encode($options['options']['options']['values']);
68 69  
69 70 $js .= 'arrayOptions.push({element : $j("#'. $options['objectName'] .'"),values : '. $json .'})';
70 71  
... ... @@ -77,4 +78,4 @@ class Portabilis_View_Helper_Input_Resource_MultipleSearchCustom extends Portabi
77 78 $jsFile = '/modules/Portabilis/Assets/Javascripts/Frontend/Inputs/Resource/MultipleSearchCustom.js';
78 79 Portabilis_View_Helper_Application::loadJavascript($this->viewInstance, $jsFile);
79 80 }
80   -}
81 81 \ No newline at end of file
  82 +}
... ...
ieducar/lib/Portabilis/View/Helper/Input/Resource/MultipleSearchSerie.php
... ... @@ -3,6 +3,7 @@
3 3 require_once 'lib/Portabilis/View/Helper/Input/MultipleSearch.php';
4 4 require_once 'lib/Portabilis/Utils/Database.php';
5 5 require_once 'lib/Portabilis/String/Utils.php';
  6 +require_once 'lib/Utils/SafeJson.php';
6 7  
7 8 class Portabilis_View_Helper_Input_Resource_MultipleSearchSerie extends Portabilis_View_Helper_Input_MultipleSearch
8 9 {
... ... @@ -28,7 +29,7 @@ class Portabilis_View_Helper_Input_Resource_MultipleSearchSerie extends Portabil
28 29 $js = "if (typeof $optionsVarName == 'undefined') { $optionsVarName = {} };
29 30 $optionsVarName.placeholder = safeUtf8Decode('Selecione');";
30 31  
31   - $json = json_encode($options['options']['values']);
  32 + $json = SafeJson::encode($options['options']['values']);
32 33  
33 34 $js .= 'arrayOptions.push({element : $j("#'. $options['objectName'] . "_serie-". $options['options']['coluna'] .'"),values : '. $json .'})';
34 35  
... ...
ieducar/lib/Utils/SafeJson.php 0 → 100644
... ... @@ -0,0 +1,23 @@
  1 +<?php
  2 +
  3 +class SafeJson {
  4 +
  5 + public static function encode($value, $options = 0, $depth = 512)
  6 + {
  7 + return self::handle(json_encode($value, $options, $depth));
  8 + }
  9 +
  10 + public static function decode($json, $assoc = false)
  11 + {
  12 + return self::handle(json_decode($json, $assoc));
  13 + }
  14 +
  15 + private static function handle($value)
  16 + {
  17 + if ($value === false) {
  18 + throw new Exception(json_last_error_msg());
  19 + }
  20 +
  21 + return $value;
  22 + }
  23 +}
... ...
ieducar/modules/Avaliacao/Views/DiarioApiController.php
1 1 <?php
2 2  
  3 +use Cocur\Slugify\Slugify;
  4 +
3 5 require_once 'Avaliacao/Model/NotaComponenteDataMapper.php';
4 6 require_once 'Avaliacao/Model/NotaGeralDataMapper.php';
5 7 require_once 'Avaliacao/Service/Boletim.php';
... ... @@ -18,6 +20,9 @@ require_once &#39;Portabilis/Array/Utils.php&#39;;
18 20 require_once 'Portabilis/String/Utils.php';
19 21 require_once 'Portabilis/Object/Utils.php';
20 22  
  23 +//todo: Mover pra algum outro lugar
  24 +require_once __DIR__ . '/../../../vendor/autoload.php';
  25 +
21 26 class DiarioApiController extends ApiCoreController
22 27 {
23 28 protected $_dataMapper = 'Avaliacao_Model_NotaComponenteDataMapper';
... ... @@ -1158,6 +1163,9 @@ class DiarioApiController extends ApiCoreController
1158 1163  
1159 1164 $turmaId = $this->getRequest()->turma_id;
1160 1165 $situacoes = $this->getSituacaoComponentes();
  1166 +
  1167 + $slugify = new Slugify();
  1168 +
1161 1169 foreach ($_componentesCurriculares as $_componente) {
1162 1170 $componente = array();
1163 1171 $componenteId = $_componente->get('id');
... ... @@ -1204,8 +1212,8 @@ class DiarioApiController extends ApiCoreController
1204 1212 //criando chave para ordenamento temporário
1205 1213 //área de conhecimento + componente curricular
1206 1214  
1207   - $componente['ordem_nome_area_conhecimento'] = strtr($nomeArea, "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ", "aaaaeeiooouucAAAAEEIOOOUUC");
1208   - $componente['ordem_componente_curricular'] = strtr(($_componente->get('nome')), "áàãâéêíóôõúüçÁÀÃÂÉÊÍÓÔÕÚÜÇ", "aaaaeeiooouucAAAAEEIOOOUUC");
  1215 + $componente['ordem_nome_area_conhecimento'] = $slugify->slugify($nomeArea);
  1216 + $componente['ordem_componente_curricular'] = $slugify->slugify($_componente->get('nome'));
1209 1217 $componentesCurriculares[] = $componente;
1210 1218 }
1211 1219  
... ...
ieducar/modules/HistoricoEscolar/Views/ProcessamentoApiController.php
1   -<?php
2   -
3   -require_once 'Core/Controller/Page/EditController.php';
4   -require_once 'Avaliacao/Model/NotaComponenteDataMapper.php';
5   -require_once 'Avaliacao/Service/Boletim.php';
6   -require_once 'App/Model/MatriculaSituacao.php';
7   -require_once 'RegraAvaliacao/Model/TipoPresenca.php';
8   -require_once 'RegraAvaliacao/Model/TipoParecerDescritivo.php';
9   -
10   -require_once 'include/pmieducar/clsPmieducarTurma.inc.php';
11   -require_once 'include/pmieducar/clsPmieducarMatricula.inc.php';
12   -require_once 'include/pmieducar/clsPmieducarHistoricoEscolar.inc.php';
13   -require_once 'include/pmieducar/clsPmieducarHistoricoDisciplinas.inc.php';
14   -
15   -require_once 'lib/Portabilis/String/Utils.php';
16   -require_once 'Portabilis/Utils/Database.php';
17   -
18   -
19   -// TODO migrar classe novo padrao api controller
20   -class ProcessamentoApiController extends Core_Controller_Page_EditController
21   -{
22   - protected $_dataMapper = 'Avaliacao_Model_NotaComponenteDataMapper';
23   - protected $_processoAp = 999613;
24   - protected $_nivelAcessoOption = App_Model_NivelAcesso::SOMENTE_ESCOLA;
25   - protected $_saveOption = false;
26   - protected $_deleteOption = false;
27   - protected $_titulo = '';
28   - var $DISCIPLINA_DISPENSADA = "Disp";
29   -
30   - protected function validatesPresenceOf(&$value, $name, $raiseExceptionOnEmpty = false, $msg = '', $addMsgOnEmpty = true)
31   - {
32   - if (!isset($value) || (empty($value) && !is_numeric($value))) {
33   - if ($addMsgOnEmpty) {
34   - $msg = empty($msg) ? "É necessário receber uma variavel '$name'" : $msg;
35   - $this->appendMsg($msg);
36   - }
37   -
38   - if ($raiseExceptionOnEmpty) {
39   - throw new Exception($msg);
40   - }
41   -
42   - return false;
43   - }
44   - return true;
45   - }
46   -
47   - protected function validatesValueIsNumeric(&$value, $name, $raiseExceptionOnError = false, $msg = '', $addMsgOnError = true)
48   - {
49   - if (!is_numeric($value)) {
50   - if ($addMsgOnError) {
51   - $msg = empty($msg) ? "O valor recebido para variavel '$name' deve ser numerico" : $msg;
52   - $this->appendMsg($msg);
53   - }
54   -
55   - if ($raiseExceptionOnError) {
56   - throw new Exception($msg);
57   - }
58   -
59   - return false;
60   - }
61   - return true;
62   - }
63   -
64   - protected function validatesValueIsArray(&$value, $name, $raiseExceptionOnError = false, $msg = '', $addMsgOnError = true)
65   - {
66   -
67   - if (!is_array($value)) {
68   - if ($addMsgOnError) {
69   - $msg = empty($msg) ? "Deve ser recebido uma lista de '$name'" : $msg;
70   - $this->appendMsg($msg);
71   - }
72   -
73   - if ($raiseExceptionOnError) {
74   - throw new Exception($msg);
75   - }
76   -
77   - return false;
78   - }
79   - return true;
80   - }
81   -
82   - protected function validatesValueInSetOf(&$value, $setExpectedValues, $name, $raiseExceptionOnError = false, $msg = '')
83   - {
84   - if (!in_array($value, $setExpectedValues)) {
85   - $msg = empty($msg) ? "Valor recebido na variavel '$name' é invalido" : $msg;
86   - $this->appendMsg($msg);
87   -
88   - if ($raiseExceptionOnError) {
89   - throw new Exception($msg);
90   - }
91   -
92   - return false;
93   - }
94   - return true;
95   - }
96   -
97   -
98   - protected function requiresLogin($raiseExceptionOnEmpty)
99   - {
100   - return $this->validatesPresenceOf($this->getSession()->id_pessoa, '', $raiseExceptionOnEmpty, 'Usuário deve estar logado');
101   - }
102   -
103   - protected function validatesPresenceOfInstituicaoId($raiseExceptionOnEmpty)
104   - {
105   - return $this->validatesPresenceOf($this->getRequest()->instituicao_id, 'instituicao_id', $raiseExceptionOnEmpty);
106   - }
107   -
108   - protected function validatesPresenceOfEscolaId($raiseExceptionOnEmpty)
109   - {
110   - return $this->validatesPresenceOf($this->getRequest()->escola_id, 'escola_id', $raiseExceptionOnEmpty);
111   - }
112   -
113   - protected function validatesPresenceOfCursoId($raiseExceptionOnEmpty)
114   - {
115   - return $this->validatesPresenceOf($this->getRequest()->curso_id, 'curso_id', $raiseExceptionOnEmpty);
116   - }
117   -
118   - protected function validatesPresenceOfSerieId($raiseExceptionOnEmpty, $addMsgOnEmpty = true)
119   - {
120   - return $this->validatesPresenceOf($this->getRequest()->serie_id, 'serie_id', $raiseExceptionOnEmpty, '', $addMsgOnEmpty);
121   - }
122   -
123   - protected function validatesPresenceOfAno($raiseExceptionOnEmpty)
124   - {
125   - return $this->validatesPresenceOf($this->getRequest()->ano, 'ano', $raiseExceptionOnEmpty);
126   - }
127   -
128   - protected function validatesPresenceOfMatriculaId($raiseExceptionOnEmpty)
129   - {
130   - return $this->validatesPresenceOf($this->getRequest()->matricula_id, 'matricula_id', $raiseExceptionOnEmpty);
131   - }
132   -
133   - protected function validatesValueIsInBd($fieldName, &$value, $schemaName, $tableName, $raiseExceptionOnError = true)
134   - {
135   - $sql = "select 1 from $schemaName.$tableName where $fieldName = $1";
136   - $isValid = Portabilis_Utils_DataBase::selectField($sql, $value) == '1';
137   -
138   - if (!$isValid) {
139   - $msg = "O valor informado {$value} para $tableName, não esta presente no banco de dados.";
140   - $this->appendMsg($msg);
141   -
142   - if ($raiseExceptionOnError) {
143   - throw new Exception($msg);
144   - }
145   -
146   - return false;
147   - }
148   -
149   - return true;
150   - }
151   -
152   - protected function validatesPresenceAndValueInDbOfGradeCursoId($raiseExceptionOnError)
153   - {
154   - return $this->validatesPresenceOf($this->getRequest()->grade_curso_id, 'grade_curso_id', $raiseExceptionOnError) &&
155   - $this->validatesValueIsInBd('id', $this->getRequest()->grade_curso_id, 'pmieducar', 'historico_grade_curso', $raiseExceptionOnError);
156   - }
157   -
158   - protected function validatesPresenceOfDiasLetivos($raiseExceptionOnEmpty)
159   - {
160   - return $this->validatesPresenceOf($this->getRequest()->dias_letivos, 'dias_letivos', $raiseExceptionOnEmpty);
161   - }
162   -
163   - protected function validatesValueOfAttValueIsNumeric($raiseExceptionOnError)
164   - {
165   - return $this->validatesValueIsNumeric($this->getRequest()->att_value, 'att_value', $raiseExceptionOnError);
166   - }
167   -
168   - protected function validatesPresenceOfAttValue($raiseExceptionOnEmpty)
169   - {
170   - return $this->validatesPresenceOf($this->getRequest()->att_value, 'att_value', $raiseExceptionOnEmpty);
171   - }
172   -
173   -
174   - protected function validatesPresenceAndValueInSetOfAtt($raiseExceptionOnError)
175   - {
176   - $result = $this->validatesPresenceOf($this->getRequest()->att, 'att', $raiseExceptionOnError);
177   -
178   - if ($result) {
179   - $expectedAtts = array('matriculas', 'processamento', 'historico');
180   - $result = $this->validatesValueInSetOf($this->getRequest()->att, $expectedAtts, 'att', $raiseExceptionOnError);
181   - }
182   - return $result;
183   - }
184   -
185   -
186   - protected function validatesPresenceAndValueInSetOfOper($raiseExceptionOnError)
187   - {
188   - $result = $this->validatesPresenceOf($this->getRequest()->oper, 'oper', $raiseExceptionOnError);
189   -
190   - if ($result) {
191   - $expectedOpers = array('post', 'get', 'delete');
192   - $result = $this->validatesValueInSetOf($this->getRequest()->oper, $expectedOpers, 'oper', $raiseExceptionOnError);
193   - }
194   - return $result;
195   - }
196   -
197   -
198   - protected function validatesPresenceAndValueInSetOfExtraCurricular($raiseExceptionOnError)
199   - {
200   - $result = $this->validatesPresenceOf($this->getRequest()->extra_curricular, 'extra_curricular', $raiseExceptionOnError);
201   -
202   - if ($result) {
203   - $expectedOpers = array(0, 1);
204   - $result = $this->validatesValueInSetOf($this->getRequest()->extra_curricular, $expectedOpers, 'extra_curricular', $raiseExceptionOnError);
205   - }
206   - return $result;
207   - }
208   -
209   - protected function validatesPresenceAndValueOfPercentualFrequencia($raiseExceptionOnError)
210   - {
211   - $name = 'percentual_frequencia';
212   - $isValid = $this->validatesPresenceOf($this->getRequest()->percentual_frequencia, $name, $raiseExceptionOnError);
213   -
214   - if ($isValid && $this->getRequest()->percentual_frequencia != 'buscar-boletim') {
215   - $isValid = $this->validatesValueIsNumeric($this->getRequest()->percentual_frequencia, $name, $raiseExceptionOnError);
216   - }
217   -
218   - return $isValid;
219   - }
220   -
221   - protected function validatesPresenceOfNotas($raiseExceptionOnError)
222   - {
223   - return $this->validatesPresenceOf($this->getRequest()->notas, 'notas', $raiseExceptionOnError);
224   - }
225   -
226   - protected function validatesPresenceAndValueOfFaltas($raiseExceptionOnError)
227   - {
228   - $name = 'faltas';
229   - $isValid = $this->validatesPresenceOf($this->getRequest()->faltas, $name, $raiseExceptionOnError);
230   -
231   - if ($isValid && $this->getRequest()->faltas != 'buscar-boletim') {
232   - $isValid = $this->validatesValueIsNumeric($this->getRequest()->faltas, $name, $raiseExceptionOnError);
233   - }
234   -
235   - return $isValid;
236   - }
237   -
238   -
239   - protected function validatesPresenceAndValueOfDisciplinas($raiseExceptionOnError)
240   - {
241   - $name = 'disciplinas';
242   - $isValid = $this->validatesPresenceOf($this->getRequest()->disciplinas, $name, $raiseExceptionOnError);
243   -
244   - if ($isValid && $this->getRequest()->disciplinas != 'buscar-boletim') {
245   - $isValid = $this->validatesValueIsArray($this->getRequest()->disciplinas, 'disciplinas', $raiseExceptionOnError);
246   - if ($isValid) {
247   - foreach ($this->getRequest()->disciplinas as $disciplina) {
248   - $isValid = $this->validatesPresenceOf($disciplina['nome'], 'nome (para todas disciplinas)', $raiseExceptionOnError);
249   -
250   - if ($isValid && isset($disciplina['falta']) && trim($disciplina['falta']) != '') {
251   - $isValid = $this->validatesValueIsNumeric($disciplina['falta'], 'falta (para todas disciplinas)', $raiseExceptionOnError);
252   - }
253   - }
254   - }
255   - }
256   - return $isValid;
257   - }
258   -
259   - protected function validatesPresenceAndValueInSetOfSituacao($raiseExceptionOnError)
260   - {
261   - $name = 'situacao';
262   - $isValid = $this->validatesPresenceOf($this->getRequest()->situacao, $name, $raiseExceptionOnError);
263   -
264   - if ($isValid) {
265   - $expectedOpers = array('buscar-matricula', 'aprovado', 'reprovado', 'em-andamento', 'transferido');
266   - $isValid = $this->validatesValueInSetOf($this->getRequest()->situacao, $expectedOpers, $name, $raiseExceptionOnError);
267   - }
268   -
269   - return $isValid;
270   - }
271   -
272   -
273   - /* esta funcao só pode ser chamada após setar $this->getService() */
274   - protected function validatesPresenceOfComponenteCurricularId($raiseExceptionOnEmpty, $addMsgOnEmpty = true)
275   - {
276   - return $this->validatesPresenceOf($this->getRequest()->componente_curricular_id, 'componente_curricular_id', $raiseExceptionOnEmpty, $msg = '', $addMsgOnEmpty);
277   - }
278   -
279   -
280   - protected function canAcceptRequest()
281   - {
282   - try {
283   - $this->requiresLogin(true);
284   - $this->validatesPresenceAndValueInSetOfAtt(true);
285   - $this->validatesPresenceAndValueInSetOfOper(true);
286   - } catch (Exception $e) {
287   - return false;
288   - }
289   - return true;
290   - }
291   -
292   -
293   - protected function canGetMatriculas()
294   - {
295   - return $this->validatesPresenceOfAno(false) &&
296   - $this->validatesPresenceOfInstituicaoId(false) &&
297   - $this->validatesPresenceOfEscolaId(false);
298   - }
299   -
300   -
301   - protected function canPostProcessamento()
302   - {
303   - $canPost = $this->validatesPresenceOfInstituicaoId(false) &&
304   - $this->validatesPresenceOfMatriculaId(false) &&
305   - $this->validatesPresenceOfDiasLetivos(false) &&
306   - $this->validatesPresenceAndValueInSetOfSituacao(false) &&
307   - $this->validatesPresenceAndValueInSetOfExtraCurricular(false) &&
308   - $this->validatesPresenceAndValueInDbOfGradeCursoId(false) &&
309   - $this->validatesPresenceAndValueOfPercentualFrequencia(false) &&
310   - $this->validatesPresenceAndValueOfDisciplinas(false);
311   -
312   - if ($canPost && $this->getRequest()->disciplinas == 'buscar-boletim') {
313   - $canPost = $this->validatesPresenceOfNotas(false) && $this->validatesPresenceAndValueOfFaltas(false);
314   - }
315   -
316   - if ($canPost) {
317   - $sql = "select 1 from pmieducar.matricula where cod_matricula = $1 and ativo = 1";
318   -
319   - if (!Portabilis_Utils_Database::selectField($sql, $this->getRequest()->matricula_id)) {
320   - $this->appendMsg("A matricula {$this->getRequest()->matricula_id} não existe ou esta desativa", 'error');
321   - $canPost = false;
322   - }
323   - }
324   -
325   - if ($canPost) {
326   - $sql = "select 1 from pmieducar.matricula_turma where ref_cod_matricula = $1 and ativo = 1 limit 1";
327   -
328   - if (!Portabilis_Utils_Database::selectField($sql, $this->getRequest()->matricula_id)) {
329   - $this->appendMsg("A matricula {$this->getRequest()->matricula_id} não está enturmada.", 'error');
330   - $canPost = false;
331   - }
332   - }
333   - return $canPost && $this->setService();
334   - }
335   -
336   -
337   - protected function canDeleteHistorico()
338   - {
339   - return $this->validatesPresenceOfInstituicaoId(false) &&
340   - $this->validatesPresenceOfMatriculaId(false);
341   - }
342   -
343   -
344   - protected function deleteHistorico()
345   - {
346   - if ($this->canDeleteHistorico()) {
347   -
348   - $matriculaId = $this->getRequest()->matricula_id;
349   - $alunoId = $this->getAlunoIdByMatriculaId($matriculaId);
350   - $dadosMatricula = $this->getdadosMatricula($matriculaId);
351   - $ano = $dadosMatricula['ano'];
352   -
353   - if ($this->existsHistorico($alunoId, $ano, $matriculaId)) {
354   - $sequencial = $this->getSequencial($alunoId, $ano, $matriculaId);
355   - $this->deleteHistoricoDisplinas($alunoId, $sequencial);
356   -
357   - $historicoEscolar = new clsPmieducarHistoricoEscolar(
358   - $ref_cod_aluno = $alunoId,
359   - $sequencial,
360   - $ref_usuario_exc = $this->getSession()->id_pessoa,
361   - $ref_usuario_cad = null,
362   - //TODO nm_curso
363   - $nm_serie = null,
364   - $ano = $ano,
365   - $carga_horaria = null,
366   - $dias_letivos = null,
367   - $escola = null,
368   - $escola_cidade = null,
369   - $escola_uf = null,
370   - $observacao = null,
371   - $aprovado = null,
372   - $data_cadastro = null,
373   - $data_exclusao = date('Y-m-d'),
374   - $ativo = 0
375   - );
376   - $historicoEscolar->edita();
377   -
378   - $this->appendMsg('Histórico escolar removido com sucesso', 'success');
379   - } else {
380   - $this->appendMsg("Histórico matricula $matriculaId inexistente ou já removido", 'notice');
381   - }
382   -
383   - $situacaoHistorico = $this->getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = true);
384   -
385   - $this->appendResponse('situacao_historico', $situacaoHistorico);
386   - $this->appendResponse('link_to_historico', '');
387   - }
388   - }
389   -
390   - protected function deleteHistoricoDisplinas($alunoId, $historicoSequencial)
391   - {
392   - $historicoDisciplinas = new clsPmieducarHistoricoDisciplinas();
393   - $historicoDisciplinas->excluirTodos($alunoId, $historicoSequencial);
394   - }
395   -
396   -
397   - protected function getdadosEscola($escolaId)
398   - {
399   - $sql = "select
400   - (select pes.nome from pmieducar.escola esc, cadastro.pessoa pes
401   - where esc.ref_cod_instituicao = $1 and esc.cod_escola = $2
402   - and pes.idpes = esc.ref_idpes) as nome,
403   -
404   - (select coalesce((select coalesce((select municipio.nome from public.municipio,
405   - cadastro.endereco_pessoa, cadastro.juridica, public.bairro, pmieducar.escola
406   - where endereco_pessoa.idbai = bairro.idbai and bairro.idmun = municipio.idmun and
407   - juridica.idpes = endereco_pessoa.idpes and juridica.idpes = escola.ref_idpes and
408   - escola.cod_escola = $2),(select endereco_externo.cidade from cadastro.endereco_externo,
409   - pmieducar.escola where endereco_externo.idpes = escola.ref_idpes and escola.cod_escola = $2))),
410   - (select municipio from pmieducar.escola_complemento where ref_cod_escola = $2))) as cidade,
411   -
412   - (select coalesce((select coalesce((select municipio.sigla_uf from public.municipio,
413   - cadastro.endereco_pessoa, cadastro.juridica, public.bairro, pmieducar.escola
414   - where endereco_pessoa.idbai = bairro.idbai and bairro.idmun = municipio.idmun and
415   - juridica.idpes = endereco_pessoa.idpes and juridica.idpes = escola.ref_idpes and
416   - escola.cod_escola = $2),(select endereco_externo.sigla_uf from cadastro.endereco_externo,
417   - pmieducar.escola where endereco_externo.idpes = escola.ref_idpes and escola.cod_escola = $2))),
418   - (select inst.ref_sigla_uf from pmieducar.instituicao inst where inst.cod_instituicao = $1))) as uf";
419   -
420   - $params = array('params' => array($this->getrequest()->instituicao_id, $escolaId), 'return_only' => 'first-line');
421   - return Portabilis_Utils_Database::fetchPreparedQuery($sql, $params);
422   - }
423   -
424   -
425   - protected function getNextHistoricoSequencial($alunoId)
426   - {
427   - //A consulta leva em consideração historicos inativos pois o sequencial é chave composta com ref_cod_aluno id
428   - $sql = "select coalesce(max(sequencial), 0) + 1 from pmieducar.historico_escolar where ref_cod_aluno = $1";
429   -
430   - return Portabilis_Utils_Database::selectField($sql, $alunoId);
431   - }
432   -
433   -
434   - protected function getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId)
435   - {
436   - $sql = "select coalesce(max(sequencial), 0) + 1 from pmieducar.historico_disciplinas where
437   - ref_sequencial = $1 and ref_ref_cod_aluno = $2";
438   -
439   - return Portabilis_Utils_Database::selectField($sql, array($historicoSequencial, $alunoId));
440   - }
441   -
442   -
443   - protected function getSituacaoMatricula($matriculaId = null)
444   - {
445   - if (!is_null($matriculaId)) {
446   -
447   - if (!is_null($this->getService(false, false))) {
448   - $situacao = $this->getService()->getOption('aprovado');
449   - } else {
450   - $sql = "select aprovado from pmieducar.matricula where cod_matricula = $1";
451   - $situacao = Portabilis_Utils_Database::selectField($sql, $matriculaId);
452   - }
453   -
454   - } else if ($this->getRequest()->situacao == 'buscar-matricula') {
455   - $situacao = $this->getService()->getOption('aprovado');
456   - } else {
457   - $situacoes = array(
458   - 'aprovado' => App_Model_MatriculaSituacao::APROVADO,
459   - 'reprovado' => App_Model_MatriculaSituacao::REPROVADO,
460   - 'em-andamento' => App_Model_MatriculaSituacao::EM_ANDAMENTO,
461   - 'transferido' => App_Model_MatriculaSituacao::TRANSFERIDO
462   - );
463   - $situacao = $situacoes[$this->getRequest()->situacao];
464   - }
465   - return $situacao;
466   - }
467   -
468   - protected function getPercentualFrequencia()
469   - {
470   - if ($this->getRequest()->percentual_frequencia == 'buscar-boletim') {
471   - $percentual = round($this->getService()->getSituacaoFaltas()->porcentagemPresenca, 2);
472   - } else {
473   - $percentual = $this->getRequest()->percentual_frequencia;
474   - }
475   - return str_replace(',', '.', $percentual);
476   - }
477   -
478   - protected function getFaltaGlobalizada($defaultValue = null)
479   - {
480   - $faltaGeral = $this->getService()->getRegra()->get('tipoPresenca') == RegraAvaliacao_Model_TipoPresenca::GERAL;
481   -
482   - if (! $faltaGeral) {
483   - return $defaultValue;
484   - }
485   -
486   - return $this->getFalta();
487   - }
488   -
489   - protected function postProcessamento()
490   - {
491   - if ($this->canPostProcessamento()) {
492   - $matriculaId = $this->getRequest()->matricula_id;
493   -
494   - try {
495   - $alunoId = $this->getAlunoIdByMatriculaId($matriculaId);
496   - $dadosMatricula = $this->getdadosMatricula($matriculaId);
497   - $dadosEscola = $this->getdadosEscola($dadosMatricula['escola_id']);
498   - $ano = $dadosMatricula['ano'];
499   - $isNewHistorico = !$this->existsHistorico($alunoId, $ano, $matriculaId);
500   -
501   - if ($isNewHistorico) {
502   - $sequencial = $this->getNextHistoricoSequencial($alunoId);
503   -
504   - $historicoEscolar = new clsPmieducarHistoricoEscolar(
505   - $alunoId,
506   - $sequencial,
507   - $ref_usuario_exc = null,
508   - $ref_usuario_cad = $this->getSession()->id_pessoa,
509   - $dadosMatricula['nome_serie'],
510   - $ano,
511   - $this->getService()->getOption('serieCargaHoraria'),
512   - $this->getRequest()->dias_letivos,
513   - strtoupper($dadosEscola['nome']),
514   - strtoupper($dadosEscola['cidade']),
515   - $dadosEscola['uf'],
516   - $this->getRequest()->observacao,
517   - $this->getSituacaoMatricula(),
518   - $data_cadastro = date('Y-m-d'),
519   - $data_exclusao = null,
520   - $ativo = 1,
521   - $this->getFaltaGlobalizada($defaultValue = 'null'),
522   - $dadosMatricula['instituicao_id'],
523   - $origem = '', //TODO
524   - $this->getRequest()->extra_curricular,
525   - $matriculaId,
526   - $this->getPercentualFrequencia(),
527   - $this->getRequest()->registro,
528   - $this->getRequest()->livro,
529   - $this->getRequest()->folha,
530   - $dadosMatricula['nome_curso'],
531   - $this->getRequest()->grade_curso_id,
532   - null,
533   - $dadosMatricula['escola_id'],
534   - $this->getRequest()->dependencia,
535   - $this->getRequest()->posicao
536   - );
537   -
538   - $historicoEscolar->cadastra();
539   - $this->recreateHistoricoDisciplinas($sequencial, $alunoId, $dadosMatricula['turma_id']);
540   -
541   - $this->appendMsg('Histórico processado com sucesso', 'success');
542   - } else {
543   -
544   - $sequencial = $this->getSequencial($alunoId, $ano, $matriculaId);
545   -
546   - $historicoEscolar = new clsPmieducarHistoricoEscolar(
547   - $alunoId,
548   - $sequencial,
549   - $this->getSession()->id_pessoa,
550   - $ref_usuario_cad = null,
551   - $dadosMatricula['nome_serie'],
552   - $ano,
553   - $this->getService()->getOption('serieCargaHoraria'),
554   - $this->getRequest()->dias_letivos,
555   - strtoupper($dadosEscola['nome']),
556   - strtoupper($dadosEscola['cidade']),
557   - $dadosEscola['uf'],
558   - $this->getRequest()->observacao,
559   - $this->getSituacaoMatricula(),
560   - $data_cadastro = null,
561   - $data_exclusao = null,
562   - $ativo = 1,
563   - $this->getFaltaGlobalizada($defaultValue = 'null'),
564   - $dadosMatricula['instituicao_id'],
565   - $origem = '', //TODO
566   - $this->getRequest()->extra_curricular,
567   - $matriculaId,
568   - $this->getPercentualFrequencia(),
569   - $this->getRequest()->registro,
570   - $this->getRequest()->livro,
571   - $this->getRequest()->folha,
572   - $dadosMatricula['nome_curso'],
573   - $this->getRequest()->grade_curso_id,
574   - null,
575   - $dadosMatricula['escola_id'],
576   - $this->getRequest()->dependencia,
577   - $this->getRequest()->posicao
578   - );
579   -
580   - $historicoEscolar->edita();
581   - $this->recreateHistoricoDisciplinas($sequencial, $alunoId, $dadosMatricula['turma_id']);
582   - $this->appendMsg('Histórico reprocessado com sucesso', 'success');
583   - }
584   -
585   - } catch (Exception $e) {
586   - $this->appendMsg('Erro ao processar histórico, detalhes:' . $e->getMessage(), 'error', true);
587   - }
588   -
589   - $situacaoHistorico = $this->getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = true);
590   - $linkToHistorico = $this->getLinkToHistorico($alunoId, $ano, $matriculaId);
591   -
592   - $this->appendResponse('situacao_historico', $situacaoHistorico);
593   - $this->appendResponse('link_to_historico', $linkToHistorico);
594   - }
595   - }
596   -
597   -
598   - protected function _createHistoricoDisciplinas($fields)
599   - {
600   - $historicoDisciplina = new clsPmieducarHistoricoDisciplinas(
601   - $fields['sequencial'],
602   - $fields['alunoId'],
603   - $fields['historicoSequencial'],
604   - $fields['nome'],
605   - $fields['nota'],
606   - $fields['falta'],
607   - $fields['ordenamento'],
608   - $fields['carga_horaria_disciplina'],
609   - $fields['dependencia']
610   - );
611   - $historicoDisciplina->cadastra();
612   - }
613   -
614   - protected function shouldProcessAreaConhecimento($areaConhecimento)
615   - {
616   - if (!empty($this->getRequest()->area_conhecimento)) {
617   - return in_array($areaConhecimento, $this->getRequest()->area_conhecimento);
618   - }
619   - return true;
620   - }
621   -
622   - protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, $turmaId = null)
623   - {
624   -
625   - $this->deleteHistoricoDisplinas($alunoId, $historicoSequencial);
626   -
627   - if ($this->getRequest()->disciplinas == 'buscar-boletim') {
628   -
629   - $cnsNota = RegraAvaliacao_Model_Nota_TipoValor;
630   - $tpNota = $this->getService()->getRegra()->get('tipoNota');
631   - $situacaoFaltasCc = $this->getService()->getSituacaoFaltas()->componentesCurriculares;
632   - $mediasCc = $this->getService()->getMediasComponentes();
633   - $turmaId = $this->getRequest()->turma_id ?: $turmaId;
634   - $mediaAreaConhecimento = $this->getRequest()->media_area_conhecimento;
635   - $processarMediaGeral = $this->getRequest()->processar_media_geral;
636   -
637   - $aprovadoDependencia = $this->getSituacaoMatricula($aluno['ref_cod_matricula']) == 12;
638   -
639   - foreach ($this->getService()->getComponentes() as $componenteCurricular) {
640   - if (!$this->shouldProcessAreaConhecimento($componenteCurricular->get('area_conhecimento'))) {
641   - continue;
642   - }
643   - $ccId = $componenteCurricular->get('id');
644   - $reprovado = $mediasCc[$ccId][0]->situacao == 2;
645   - $disciplinaDependencia = ($aprovadoDependencia && $reprovado);
646   - $nome = $componenteCurricular->nome;
647   - $ordenamento = $componenteCurricular->ordenamento;
648   - $carga_horaria_disciplina = $componenteCurricular->carga_horaria_disciplina;
649   - $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId);
650   - $nota = '';
651   - $notaConceitualNumerica = '';
652   -
653   - if (clsPmieducarTurma::verificaDisciplinaDispensada($turmaId, $ccId)) {
654   - $nota = $this->DISCIPLINA_DISPENSADA;
655   - } elseif ($this->getRequest()->notas == 'buscar-boletim') {
656   - if ($tpNota == $cnsNota::CONCEITUAL) {
657   - if ($GLOBALS['coreExt']['Config']->app->processar_historicos_conceituais == "1") {
658   - $nota = (string)$mediasCc[$ccId][0]->mediaArredondada;
659   - $notaConceitualNumerica = (string)$mediasCc[$ccId][0]->media;
660   - }
661   - } elseif ($tpNota == $cnsNota::NUMERICA) {
662   - $nota = (string)$mediasCc[$ccId][0]->mediaArredondada;
663   - } elseif ($tpNota == $cnsNota::NUMERICACONCEITUAL) {
664   - $nota = (string)$mediasCc[$ccId][0]->mediaArredondada;
665   - $notaConceitualNumerica = (string)$mediasCc[$ccId][0]->media;
666   - }
667   - } else {
668   - $nota = $this->getRequest()->notas;
669   - }
670   -
671   - if (is_numeric($nota)) {
672   - $nota = sprintf("%.1f", $nota);
673   - }
674   -
675   - if ($processarMediaGeral) {
676   - $nota = '-';
677   - }
678   -
679   - if ($mediaAreaConhecimento) {
680   - $nota = str_replace(',', '.', $nota);
681   - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nome'] = $componenteCurricular->area_conhecimento->nome;
682   - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nota'] += $nota;
683   - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nota_conceitual_numerica'] += $notaConceitualNumerica;
684   - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['falta'] += $this->getFalta($situacaoFaltasCc[$ccId]);
685   - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['ordenamento'] = $componenteCurricular->area_conhecimento->ordenamento;
686   - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['carga_horaria_disciplina'] = $componenteCurricular->area_conhecimento->carga_horaria_disciplina;
687   - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['dependencia'] = $disciplinaDependencia;
688   - $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['count']++;
689   - } else {
690   - $this->_createHistoricoDisciplinas(
691   - array(
692   - "sequencial" => $sequencial,
693   - "alunoId" => $alunoId,
694   - "historicoSequencial" => $historicoSequencial,
695   - "nome" => $nome,
696   - "nota" => $nota,
697   - "falta" => $this->getFalta($situacaoFaltasCc[$ccId]),
698   - "ordenamento" => $ordenamento,
699   - "carga_horaria_disciplina" => $carga_horaria_disciplina,
700   - "dependencia" => $disciplinaDependencia
701   - )
702   - );
703   - }
704   - }
705   -
706   - if ($mediaAreaConhecimento) {
707   - foreach ($arrayAreaConhecimento as $key => $value) {
708   -
709   - $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId);
710   -
711   - if ($this->getRequest()->notas == 'buscar-boletim') {
712   - $nota = number_format(($value['nota_conceitual_numerica'] / $value['count']), 2, ',', '');
713   - }
714   -
715   - if ($processarMediaGeral) {
716   - $nota = '-';
717   - }
718   -
719   - $this->_createHistoricoDisciplinas(
720   - array(
721   - "sequencial" => $sequencial,
722   - "alunoId" => $alunoId,
723   - "historicoSequencial" => $historicoSequencial,
724   - "nome" => $value['nome'],
725   - "nota" => $nota,
726   - "falta" => round($value['falta'] / $value['count']),
727   - "ordenamento" => $value['ordenamento'],
728   - "carga_horaria_disciplina" => $value['carga_horaria_disciplina'],
729   - "dependencia" => $value['dependencia']
730   - )
731   - );
732   - }
733   - }
734   - if ($processarMediaGeral) {
735   - $componentesCurriculares['media_geral'] = $this->insereComponenteMediaGeral($historicoSequencial, $alunoId);
736   - }
737   - } else {
738   - foreach ($this->getRequest()->disciplinas as $disciplina) {
739   - $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId);
740   -
741   - $this->_createHistoricoDisciplinas(
742   - array(
743   - "sequencial" => $sequencial,
744   - "alunoId" => $alunoId,
745   - "historicoSequencial" => $historicoSequencial,
746   - "nome" => $disciplina['nome'],
747   - "nota" => $disciplina['nota'],
748   - "falta" => $falta = $disciplina['falta'],
749   - "ordenamento" => $value['ordenamento'],
750   - "carga_horaria_disciplina" => $value['carga_horaria_disciplina'],
751   - "dependencia" => $value['dependencia']
752   - )
753   - );
754   - }
755   - }
756   - }
757   -
758   - protected function insereComponenteMediaGeral($historicoSequencial, $alunoId)
759   - {
760   - $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId);
761   - $historicoEscolar = new clsPmieducarHistoricoEscolar($alunoId, $historicoSequencial);
762   -
763   - $historicoEscolar->insereComponenteMediaGeral($sequencial);
764   - }
765   -
766   - protected function getFalta($situacaoFaltaComponenteCurricular = null)
767   - {
768   - if ($this->getRequest()->faltas == 'buscar-boletim') {
769   -
770   - $cnsPresenca = RegraAvaliacao_Model_TipoPresenca;
771   - $tpPresenca = $this->getService()->getRegra()->get('tipoPresenca');
772   -
773   - //retorna '' caso não exista situacaoFalta para o componente curricular,
774   - //como nos casos em que a regra de avaliação muda
775   - if ($tpPresenca == $cnsPresenca::POR_COMPONENTE && !is_null($situacaoFaltaComponenteCurricular)) {
776   - $falta = $situacaoFaltaComponenteCurricular->total;
777   - } elseif ($tpPresenca == $cnsPresenca::POR_COMPONENTE) {
778   - $falta = '';
779   - } elseif ($tpPresenca == $cnsPresenca::GERAL) {
780   - $falta = $this->getService()->getSituacaoFaltas()->totalFaltas;
781   - }
782   - } else {
783   - $falta = $this->getRequest()->faltas;
784   - }
785   -
786   - return $falta;
787   - }
788   -
789   - protected function getDadosMatricula($matriculaId)
790   - {
791   - $ano = $this->getAnoMatricula($matriculaId);
792   - $sql = "select ref_ref_cod_serie as serie_id, ref_cod_curso as curso_id from pmieducar.matricula
793   - where cod_matricula = $1";
794   -
795   - $params = array('params' => $matriculaId, 'return_only' => 'first-line');
796   - $idsSerieCurso = Portabilis_Utils_Database::fetchPreparedQuery($sql, $params);
797   -
798   - $matriculas = array();
799   -
800   - $matriculaTurma = new clsPmieducarMatriculaTurma();
801   - $matriculaTurma = $matriculaTurma->lista(
802   - $matriculaId,
803   - null,
804   - null,
805   - null,
806   - null,
807   - null,
808   - null,
809   - null,
810   - 1,
811   - $idsSerieCurso['serie_id'],
812   - $idsSerieCurso['curso_id']
813   - );
814   -
815   - $matriculaTurma = $matriculaTurma[0];
816   -
817   - $dadosMatricula = array();
818   -
819   - if (is_array($matriculaTurma) && count($matriculaTurma) > 0) {
820   - $dadosMatricula['ano'] = $ano;
821   - $dadosMatricula['instituicao_id'] = $matriculaTurma['ref_cod_instituicao'];
822   - $dadosMatricula['escola_id'] = $matriculaTurma['ref_ref_cod_escola'];
823   - $dadosMatricula['turma_id'] = $matriculaTurma['ref_cod_turma'];
824   - $dadosMatricula['nome_serie'] = $this->getNomeSerie($matriculaTurma['ref_ref_cod_serie']);
825   -
826   - $dadosMatricula['nome_curso'] = $matriculaTurma['nm_curso'];
827   - } else {
828   - throw new Exception("Não foi possivel recuperar os dados da matricula: $matriculaId.");
829   - }
830   -
831   - return $dadosMatricula;
832   - }
833   -
834   - protected function getAlunoIdByMatriculaId($matriculaId)
835   - {
836   - $sql = "select ref_cod_aluno from pmieducar.matricula where cod_matricula = $1";
837   -
838   - return Portabilis_Utils_Database::selectField($sql, $matriculaId);
839   - }
840   -
841   - protected function getAnoMatricula($matriculaId)
842   - {
843   - $sql = "select ano from pmieducar.matricula where cod_matricula = $1";
844   -
845   - return Portabilis_Utils_Database::selectField($sql, $matriculaId);
846   - }
847   -
848   - protected function getNomeSerie($serieId)
849   - {
850   - $sql = "select nm_serie from pmieducar.serie where cod_serie = $1";
851   -
852   - return Portabilis_String_Utils::toLatin1(Portabilis_Utils_Database::selectField($sql, $serieId));
853   - }
854   -
855   - protected function getSequencial($alunoId, $ano, $matriculaId)
856   - {
857   - $sql = "select sequencial from pmieducar.historico_escolar where ref_cod_aluno = $1 and ano = $2
858   - and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = 1 limit 1";
859   -
860   - $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId);
861   - return Portabilis_Utils_Database::selectField($sql, $params);
862   - }
863   -
864   - protected function existsHistorico($alunoId, $ano, $matriculaId, $ativo = 1, $reload = false)
865   - {
866   - if (!isset($this->existsHistorico) || $reload) {
867   - $sql = "select 1 from pmieducar.historico_escolar where ref_cod_aluno = $1 and ano = $2
868   - and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = $5";
869   -
870   - $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId, $ativo);
871   - $this->existsHistorico = Portabilis_Utils_Database::selectField($sql, $params) == 1;
872   - }
873   -
874   - return $this->existsHistorico;
875   - }
876   -
877   - protected function getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = false)
878   - {
879   - if ($this->existsHistorico($alunoId, $ano, $matriculaId, 1, $reload)) {
880   - $situacao = 'Processado';
881   - } else {
882   - $situacao = 'Sem histórico';
883   - }
884   -
885   - return $this->toUtf8($situacao);
886   - }
887   -
888   - protected function getLinkToHistorico($alunoId, $ano, $matriculaId)
889   - {
890   - $sql = "select sequencial from pmieducar.historico_escolar where ref_cod_aluno = $1 and
891   - ano = $2 and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = 1";
892   -
893   - $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId);
894   - $sequencial = Portabilis_Utils_DataBase::selectField($sql, $params);
895   -
896   - if (is_numeric($sequencial)) {
897   - $link = "/intranet/educar_historico_escolar_det.php?ref_cod_aluno=$alunoId&sequencial=$sequencial";
898   - } else {
899   - $link = '';
900   - }
901   -
902   - return $link;
903   - }
904   -
905   - protected function getMatriculas()
906   - {
907   - $matriculas = array();
908   -
909   - if ($this->canGetMatriculas()) {
910   - $alunos = new clsPmieducarMatriculaTurma();
911   - $alunos->setOrderby('ref_cod_curso, ref_ref_cod_serie, ref_cod_turma, sequencial_fechamento, nome');
912   -
913   - $alunos = $alunos->lista(
914   - $this->getRequest()->matricula_id,
915   - $this->getRequest()->turma_id,
916   - null,
917   - null,
918   - null,
919   - null,
920   - null,
921   - null,
922   - 1,
923   - $this->getRequest()->serie_id,
924   - $this->getRequest()->curso_id,
925   - $this->getRequest()->escola_id,
926   - $this->getRequest()->instituicao_id,
927   - $this->getRequest()->aluno_id,
928   - null,
929   - null,
930   - null,
931   - null,
932   - $this->getRequest()->ano,
933   - null,
934   - true,
935   - null,
936   - null,
937   - true,
938   - null,
939   - null,
940   - null,
941   - null,
942   - null,
943   - null,
944   - null,
945   - null,
946   - null,
947   - null,
948   - $this->getRequest()->dependencia
949   - );
950   -
951   - if (!is_array($alunos)) {
952   - $alunos = array();
953   - }
954   -
955   - $situacoesMatricula = array(
956   - 'aprovado' => App_Model_MatriculaSituacao::APROVADO,
957   - 'reprovado' => App_Model_MatriculaSituacao::REPROVADO,
958   - 'reprovado-faltas' => App_Model_MatriculaSituacao::REPROVADO_POR_FALTAS,
959   - 'em-andamento' => App_Model_MatriculaSituacao::EM_ANDAMENTO,
960   - 'aprovado-conselho' => App_Model_MatriculaSituacao::APROVADO_PELO_CONSELHO,
961   - 'aprovado-dependencia' => App_Model_MatriculaSituacao::APROVADO_COM_DEPENDENCIA
962   - );
963   -
964   - foreach ($alunos as $aluno) {
965   -
966   - $situacaoMatricula = $this->getSituacaoMatricula($aluno['ref_cod_matricula']);
967   -
968   - if (in_array($situacaoMatricula, $situacoesMatricula)) {
969   - $matricula = array();
970   - $matriculaId = $aluno['ref_cod_matricula'];
971   - $matricula['matricula_id'] = $matriculaId;
972   - $matricula['aluno_id'] = $aluno['ref_cod_aluno'];
973   - $matricula['nome'] = $this->toUtf8($aluno['nome_aluno']);
974   - $matricula['nome_curso'] = $this->toUtf8($aluno['nm_curso']);
975   - $matricula['nome_serie'] = $this->toUtf8($this->getNomeSerie($aluno['ref_ref_cod_serie']));
976   - $matricula['nome_turma'] = $this->toUtf8($aluno['nm_turma']);
977   - $matricula['situacao_historico'] = $this->getSituacaoHistorico($aluno['ref_cod_aluno'], $this->getRequest()->ano, $matriculaId, $reload = true);
978   - $matricula['link_to_historico'] = $this->getLinkToHistorico($aluno['ref_cod_aluno'], $this->getRequest()->ano, $matriculaId);
979   - $matriculas[] = $matricula;
980   - }
981   - }
982   - }
983   -
984   - return $matriculas;
985   - }
986   -
987   - protected function getObservacaoPadraoSerie()
988   - {
989   - if ($this->validatesPresenceOfSerieId(false, false)) {
990   - $sql = "select coalesce(observacao_historico, '') as observacao_historico from pmieducar.serie
991   - where cod_serie = $1";
992   -
993   - $observacao = Portabilis_Utils_DataBase::selectField($sql, $this->getRequest()->serie_id);
994   - } else {
995   - $observacao = '';
996   - }
997   -
998   - return $this->toUtf8($observacao);
999   - }
1000   -
1001   - protected function saveService()
1002   - {
1003   - try {
1004   - $this->getService()->save();
1005   - } catch (CoreExt_Service_Exception $e) {
1006   - //excecoes ignoradas :( servico lanca excecoes de alertas, que não são exatamente erros.
1007   - //error_log('CoreExt_Service_Exception ignorada: ' . $e->getMessage());
1008   - }
1009   - }
1010   -
1011   - protected function getService($raiseExceptionOnErrors = false, $appendMsgOnErrors = true)
1012   - {
1013   - if (isset($this->service) && !is_null($this->service)) {
1014   - return $this->service;
1015   - }
1016   -
1017   - $msg = 'Erro ao recuperar serviço boletim: serviço não definido.';
1018   - if ($appendMsgOnErrors) {
1019   - $this->appendMsg($msg);
1020   - }
1021   -
1022   - if ($raiseExceptionOnErrors) {
1023   - throw new Exception($msg);
1024   - }
1025   -
1026   - return null;
1027   - }
1028   -
1029   - protected function canSetService($validatesPresenceOfMatriculaId = true)
1030   - {
1031   - try {
1032   - $this->requiresLogin(true);
1033   - if ($validatesPresenceOfMatriculaId) {
1034   - $this->validatesPresenceOfMatriculaId(true);
1035   - }
1036   - } catch (Exception $e) {
1037   - return false;
1038   - }
1039   - return true;
1040   - }
1041   -
1042   - protected function setService($matriculaId = null)
1043   - {
1044   - if ($this->canSetService($validatesPresenceOfMatriculaId = is_null($matriculaId))) {
1045   - try {
1046   -
1047   - if (!$matriculaId) {
1048   - $matriculaId = $this->getRequest()->matricula_id;
1049   - }
1050   -
1051   - $this->service = new Avaliacao_Service_Boletim(
1052   - array(
1053   - 'matricula' => $matriculaId,
1054   - 'usuario' => $this->getSession()->id_pessoa
1055   - )
1056   - );
1057   -
1058   - return true;
1059   - } catch (Exception $e) {
1060   - $this->appendMsg('Exception ao instanciar serviço boletim: ' . $e->getMessage(), 'error', $encodeToUtf8 = true);
1061   - }
1062   - }
1063   - return false;
1064   - }
1065   -
1066   - protected function notImplementedError()
1067   - {
1068   - $this->appendMsg("Operação '{$this->getRequest()->oper}' inválida para o att '{$this->getRequest()->att}'");
1069   - }
1070   -
1071   - public function Gerar()
1072   - {
1073   - $this->msgs = array();
1074   - $this->response = array();
1075   -
1076   - if ($this->canAcceptRequest()) {
1077   - try {
1078   -
1079   - if (isset($this->getRequest()->matricula_id)) {
1080   - $this->appendResponse('matricula_id', $this->getRequest()->matricula_id);
1081   - }
1082   -
1083   - if ($this->getRequest()->oper == 'get') {
1084   - if ($this->getRequest()->att == 'matriculas') {
1085   - $matriculas = $this->getMatriculas();
1086   - $this->appendResponse('matriculas', $matriculas);
1087   - $this->appendResponse('observacao_padrao', $this->getObservacaoPadraoSerie());
1088   - } else {
1089   - $this->notImplementedError();
1090   - }
1091   -
1092   - } elseif ($this->getRequest()->oper == 'post') {
1093   - if ($this->getRequest()->att == 'processamento') {
1094   - $this->postProcessamento();
1095   - } else {
1096   - $this->notImplementedError();
1097   - }
1098   - } elseif ($this->getRequest()->oper == 'delete') {
1099   - if ($this->getRequest()->att == 'historico') {
1100   - $this->deleteHistorico();
1101   - } else {
1102   - $this->notImplementedError();
1103   - }
1104   - }
1105   - } catch (Exception $e) {
1106   - $this->appendMsg('Exception: ' . $e->getMessage(), $type = 'error', $encodeToUtf8 = true);
1107   - }
1108   - }
1109   - echo $this->prepareResponse();
1110   - }
1111   -
1112   - protected function appendResponse($name, $value)
1113   - {
1114   - $this->response[$name] = $value;
1115   - }
1116   -
1117   - protected function prepareResponse()
1118   - {
1119   - $msgs = array();
1120   - $this->appendResponse('att', isset($this->getRequest()->att) ? $this->getRequest()->att : '');
1121   -
1122   - foreach ($this->msgs as $m) {
1123   - $msgs[] = array('msg' => $m['msg'], 'type' => $m['type']);
1124   - }
1125   - $this->appendResponse('msgs', $msgs);
1126   -
1127   - echo json_encode($this->response);
1128   - }
1129   -
1130   - protected function appendMsg($msg, $type = "error", $encodeToUtf8 = false)
1131   - {
1132   - if ($encodeToUtf8) {
1133   - $msg = utf8_encode($msg);
1134   - }
1135   -
1136   - //error_log("$type msg: '$msg'");
1137   - $this->msgs[] = array('msg' => $msg, 'type' => $type);
1138   - }
1139   -
1140   - public function generate(CoreExt_Controller_Page_Interface $instance)
1141   - {
1142   - header('Content-type: application/json');
1143   - $instance->Gerar();
1144   - }
1145   -
1146   -
1147   - // TODO remover metodo, ao migrar esta classe para novo padrao
1148   -
1149   - protected function toUtf8($str, $options = array())
1150   - {
1151   - return Portabilis_String_Utils::toUtf8($str, $options);
1152   - }
1153   -}
  1 +<?php
  2 +
  3 +require_once 'Core/Controller/Page/EditController.php';
  4 +require_once 'Avaliacao/Model/NotaComponenteDataMapper.php';
  5 +require_once 'Avaliacao/Service/Boletim.php';
  6 +require_once 'App/Model/MatriculaSituacao.php';
  7 +require_once 'RegraAvaliacao/Model/TipoPresenca.php';
  8 +require_once 'RegraAvaliacao/Model/TipoParecerDescritivo.php';
  9 +
  10 +require_once 'include/pmieducar/clsPmieducarTurma.inc.php';
  11 +require_once 'include/pmieducar/clsPmieducarMatricula.inc.php';
  12 +require_once 'include/pmieducar/clsPmieducarHistoricoEscolar.inc.php';
  13 +require_once 'include/pmieducar/clsPmieducarHistoricoDisciplinas.inc.php';
  14 +
  15 +require_once 'lib/Portabilis/String/Utils.php';
  16 +require_once 'Portabilis/Utils/Database.php';
  17 +require_once 'lib/Utils/SafeJson.php';
  18 +
  19 +
  20 +// TODO migrar classe novo padrao api controller
  21 +class ProcessamentoApiController extends Core_Controller_Page_EditController
  22 +{
  23 + protected $_dataMapper = 'Avaliacao_Model_NotaComponenteDataMapper';
  24 + protected $_processoAp = 999613;
  25 + protected $_nivelAcessoOption = App_Model_NivelAcesso::SOMENTE_ESCOLA;
  26 + protected $_saveOption = false;
  27 + protected $_deleteOption = false;
  28 + protected $_titulo = '';
  29 + var $DISCIPLINA_DISPENSADA = "Disp";
  30 +
  31 + protected function validatesPresenceOf(&$value, $name, $raiseExceptionOnEmpty = false, $msg = '', $addMsgOnEmpty = true)
  32 + {
  33 + if (!isset($value) || (empty($value) && !is_numeric($value))) {
  34 + if ($addMsgOnEmpty) {
  35 + $msg = empty($msg) ? "É necessário receber uma variavel '$name'" : $msg;
  36 + $this->appendMsg($msg);
  37 + }
  38 +
  39 + if ($raiseExceptionOnEmpty) {
  40 + throw new Exception($msg);
  41 + }
  42 +
  43 + return false;
  44 + }
  45 + return true;
  46 + }
  47 +
  48 + protected function validatesValueIsNumeric(&$value, $name, $raiseExceptionOnError = false, $msg = '', $addMsgOnError = true)
  49 + {
  50 + if (!is_numeric($value)) {
  51 + if ($addMsgOnError) {
  52 + $msg = empty($msg) ? "O valor recebido para variavel '$name' deve ser numerico" : $msg;
  53 + $this->appendMsg($msg);
  54 + }
  55 +
  56 + if ($raiseExceptionOnError) {
  57 + throw new Exception($msg);
  58 + }
  59 +
  60 + return false;
  61 + }
  62 + return true;
  63 + }
  64 +
  65 + protected function validatesValueIsArray(&$value, $name, $raiseExceptionOnError = false, $msg = '', $addMsgOnError = true)
  66 + {
  67 +
  68 + if (!is_array($value)) {
  69 + if ($addMsgOnError) {
  70 + $msg = empty($msg) ? "Deve ser recebido uma lista de '$name'" : $msg;
  71 + $this->appendMsg($msg);
  72 + }
  73 +
  74 + if ($raiseExceptionOnError) {
  75 + throw new Exception($msg);
  76 + }
  77 +
  78 + return false;
  79 + }
  80 + return true;
  81 + }
  82 +
  83 + protected function validatesValueInSetOf(&$value, $setExpectedValues, $name, $raiseExceptionOnError = false, $msg = '')
  84 + {
  85 + if (!in_array($value, $setExpectedValues)) {
  86 + $msg = empty($msg) ? "Valor recebido na variavel '$name' é invalido" : $msg;
  87 + $this->appendMsg($msg);
  88 +
  89 + if ($raiseExceptionOnError) {
  90 + throw new Exception($msg);
  91 + }
  92 +
  93 + return false;
  94 + }
  95 + return true;
  96 + }
  97 +
  98 +
  99 + protected function requiresLogin($raiseExceptionOnEmpty)
  100 + {
  101 + return $this->validatesPresenceOf($this->getSession()->id_pessoa, '', $raiseExceptionOnEmpty, 'Usuário deve estar logado');
  102 + }
  103 +
  104 + protected function validatesPresenceOfInstituicaoId($raiseExceptionOnEmpty)
  105 + {
  106 + return $this->validatesPresenceOf($this->getRequest()->instituicao_id, 'instituicao_id', $raiseExceptionOnEmpty);
  107 + }
  108 +
  109 + protected function validatesPresenceOfEscolaId($raiseExceptionOnEmpty)
  110 + {
  111 + return $this->validatesPresenceOf($this->getRequest()->escola_id, 'escola_id', $raiseExceptionOnEmpty);
  112 + }
  113 +
  114 + protected function validatesPresenceOfCursoId($raiseExceptionOnEmpty)
  115 + {
  116 + return $this->validatesPresenceOf($this->getRequest()->curso_id, 'curso_id', $raiseExceptionOnEmpty);
  117 + }
  118 +
  119 + protected function validatesPresenceOfSerieId($raiseExceptionOnEmpty, $addMsgOnEmpty = true)
  120 + {
  121 + return $this->validatesPresenceOf($this->getRequest()->serie_id, 'serie_id', $raiseExceptionOnEmpty, '', $addMsgOnEmpty);
  122 + }
  123 +
  124 + protected function validatesPresenceOfAno($raiseExceptionOnEmpty)
  125 + {
  126 + return $this->validatesPresenceOf($this->getRequest()->ano, 'ano', $raiseExceptionOnEmpty);
  127 + }
  128 +
  129 + protected function validatesPresenceOfMatriculaId($raiseExceptionOnEmpty)
  130 + {
  131 + return $this->validatesPresenceOf($this->getRequest()->matricula_id, 'matricula_id', $raiseExceptionOnEmpty);
  132 + }
  133 +
  134 + protected function validatesValueIsInBd($fieldName, &$value, $schemaName, $tableName, $raiseExceptionOnError = true)
  135 + {
  136 + $sql = "select 1 from $schemaName.$tableName where $fieldName = $1";
  137 + $isValid = Portabilis_Utils_DataBase::selectField($sql, $value) == '1';
  138 +
  139 + if (!$isValid) {
  140 + $msg = "O valor informado {$value} para $tableName, não esta presente no banco de dados.";
  141 + $this->appendMsg($msg);
  142 +
  143 + if ($raiseExceptionOnError) {
  144 + throw new Exception($msg);
  145 + }
  146 +
  147 + return false;
  148 + }
  149 +
  150 + return true;
  151 + }
  152 +
  153 + protected function validatesPresenceAndValueInDbOfGradeCursoId($raiseExceptionOnError)
  154 + {
  155 + return $this->validatesPresenceOf($this->getRequest()->grade_curso_id, 'grade_curso_id', $raiseExceptionOnError) &&
  156 + $this->validatesValueIsInBd('id', $this->getRequest()->grade_curso_id, 'pmieducar', 'historico_grade_curso', $raiseExceptionOnError);
  157 + }
  158 +
  159 + protected function validatesPresenceOfDiasLetivos($raiseExceptionOnEmpty)
  160 + {
  161 + return $this->validatesPresenceOf($this->getRequest()->dias_letivos, 'dias_letivos', $raiseExceptionOnEmpty);
  162 + }
  163 +
  164 + protected function validatesValueOfAttValueIsNumeric($raiseExceptionOnError)
  165 + {
  166 + return $this->validatesValueIsNumeric($this->getRequest()->att_value, 'att_value', $raiseExceptionOnError);
  167 + }
  168 +
  169 + protected function validatesPresenceOfAttValue($raiseExceptionOnEmpty)
  170 + {
  171 + return $this->validatesPresenceOf($this->getRequest()->att_value, 'att_value', $raiseExceptionOnEmpty);
  172 + }
  173 +
  174 +
  175 + protected function validatesPresenceAndValueInSetOfAtt($raiseExceptionOnError)
  176 + {
  177 + $result = $this->validatesPresenceOf($this->getRequest()->att, 'att', $raiseExceptionOnError);
  178 +
  179 + if ($result) {
  180 + $expectedAtts = array('matriculas', 'processamento', 'historico');
  181 + $result = $this->validatesValueInSetOf($this->getRequest()->att, $expectedAtts, 'att', $raiseExceptionOnError);
  182 + }
  183 + return $result;
  184 + }
  185 +
  186 +
  187 + protected function validatesPresenceAndValueInSetOfOper($raiseExceptionOnError)
  188 + {
  189 + $result = $this->validatesPresenceOf($this->getRequest()->oper, 'oper', $raiseExceptionOnError);
  190 +
  191 + if ($result) {
  192 + $expectedOpers = array('post', 'get', 'delete');
  193 + $result = $this->validatesValueInSetOf($this->getRequest()->oper, $expectedOpers, 'oper', $raiseExceptionOnError);
  194 + }
  195 + return $result;
  196 + }
  197 +
  198 +
  199 + protected function validatesPresenceAndValueInSetOfExtraCurricular($raiseExceptionOnError)
  200 + {
  201 + $result = $this->validatesPresenceOf($this->getRequest()->extra_curricular, 'extra_curricular', $raiseExceptionOnError);
  202 +
  203 + if ($result) {
  204 + $expectedOpers = array(0, 1);
  205 + $result = $this->validatesValueInSetOf($this->getRequest()->extra_curricular, $expectedOpers, 'extra_curricular', $raiseExceptionOnError);
  206 + }
  207 + return $result;
  208 + }
  209 +
  210 + protected function validatesPresenceAndValueOfPercentualFrequencia($raiseExceptionOnError)
  211 + {
  212 + $name = 'percentual_frequencia';
  213 + $isValid = $this->validatesPresenceOf($this->getRequest()->percentual_frequencia, $name, $raiseExceptionOnError);
  214 +
  215 + if ($isValid && $this->getRequest()->percentual_frequencia != 'buscar-boletim') {
  216 + $isValid = $this->validatesValueIsNumeric($this->getRequest()->percentual_frequencia, $name, $raiseExceptionOnError);
  217 + }
  218 +
  219 + return $isValid;
  220 + }
  221 +
  222 + protected function validatesPresenceOfNotas($raiseExceptionOnError)
  223 + {
  224 + return $this->validatesPresenceOf($this->getRequest()->notas, 'notas', $raiseExceptionOnError);
  225 + }
  226 +
  227 + protected function validatesPresenceAndValueOfFaltas($raiseExceptionOnError)
  228 + {
  229 + $name = 'faltas';
  230 + $isValid = $this->validatesPresenceOf($this->getRequest()->faltas, $name, $raiseExceptionOnError);
  231 +
  232 + if ($isValid && $this->getRequest()->faltas != 'buscar-boletim') {
  233 + $isValid = $this->validatesValueIsNumeric($this->getRequest()->faltas, $name, $raiseExceptionOnError);
  234 + }
  235 +
  236 + return $isValid;
  237 + }
  238 +
  239 +
  240 + protected function validatesPresenceAndValueOfDisciplinas($raiseExceptionOnError)
  241 + {
  242 + $name = 'disciplinas';
  243 + $isValid = $this->validatesPresenceOf($this->getRequest()->disciplinas, $name, $raiseExceptionOnError);
  244 +
  245 + if ($isValid && $this->getRequest()->disciplinas != 'buscar-boletim') {
  246 + $isValid = $this->validatesValueIsArray($this->getRequest()->disciplinas, 'disciplinas', $raiseExceptionOnError);
  247 + if ($isValid) {
  248 + foreach ($this->getRequest()->disciplinas as $disciplina) {
  249 + $isValid = $this->validatesPresenceOf($disciplina['nome'], 'nome (para todas disciplinas)', $raiseExceptionOnError);
  250 +
  251 + if ($isValid && isset($disciplina['falta']) && trim($disciplina['falta']) != '') {
  252 + $isValid = $this->validatesValueIsNumeric($disciplina['falta'], 'falta (para todas disciplinas)', $raiseExceptionOnError);
  253 + }
  254 + }
  255 + }
  256 + }
  257 + return $isValid;
  258 + }
  259 +
  260 + protected function validatesPresenceAndValueInSetOfSituacao($raiseExceptionOnError)
  261 + {
  262 + $name = 'situacao';
  263 + $isValid = $this->validatesPresenceOf($this->getRequest()->situacao, $name, $raiseExceptionOnError);
  264 +
  265 + if ($isValid) {
  266 + $expectedOpers = array('buscar-matricula', 'aprovado', 'reprovado', 'em-andamento', 'transferido');
  267 + $isValid = $this->validatesValueInSetOf($this->getRequest()->situacao, $expectedOpers, $name, $raiseExceptionOnError);
  268 + }
  269 +
  270 + return $isValid;
  271 + }
  272 +
  273 +
  274 + /* esta funcao só pode ser chamada após setar $this->getService() */
  275 + protected function validatesPresenceOfComponenteCurricularId($raiseExceptionOnEmpty, $addMsgOnEmpty = true)
  276 + {
  277 + return $this->validatesPresenceOf($this->getRequest()->componente_curricular_id, 'componente_curricular_id', $raiseExceptionOnEmpty, $msg = '', $addMsgOnEmpty);
  278 + }
  279 +
  280 +
  281 + protected function canAcceptRequest()
  282 + {
  283 + try {
  284 + $this->requiresLogin(true);
  285 + $this->validatesPresenceAndValueInSetOfAtt(true);
  286 + $this->validatesPresenceAndValueInSetOfOper(true);
  287 + } catch (Exception $e) {
  288 + return false;
  289 + }
  290 + return true;
  291 + }
  292 +
  293 +
  294 + protected function canGetMatriculas()
  295 + {
  296 + return $this->validatesPresenceOfAno(false) &&
  297 + $this->validatesPresenceOfInstituicaoId(false) &&
  298 + $this->validatesPresenceOfEscolaId(false);
  299 + }
  300 +
  301 +
  302 + protected function canPostProcessamento()
  303 + {
  304 + $canPost = $this->validatesPresenceOfInstituicaoId(false) &&
  305 + $this->validatesPresenceOfMatriculaId(false) &&
  306 + $this->validatesPresenceOfDiasLetivos(false) &&
  307 + $this->validatesPresenceAndValueInSetOfSituacao(false) &&
  308 + $this->validatesPresenceAndValueInSetOfExtraCurricular(false) &&
  309 + $this->validatesPresenceAndValueInDbOfGradeCursoId(false) &&
  310 + $this->validatesPresenceAndValueOfPercentualFrequencia(false) &&
  311 + $this->validatesPresenceAndValueOfDisciplinas(false);
  312 +
  313 + if ($canPost && $this->getRequest()->disciplinas == 'buscar-boletim') {
  314 + $canPost = $this->validatesPresenceOfNotas(false) && $this->validatesPresenceAndValueOfFaltas(false);
  315 + }
  316 +
  317 + if ($canPost) {
  318 + $sql = "select 1 from pmieducar.matricula where cod_matricula = $1 and ativo = 1";
  319 +
  320 + if (!Portabilis_Utils_Database::selectField($sql, $this->getRequest()->matricula_id)) {
  321 + $this->appendMsg("A matricula {$this->getRequest()->matricula_id} não existe ou esta desativa", 'error');
  322 + $canPost = false;
  323 + }
  324 + }
  325 +
  326 + if ($canPost) {
  327 + $sql = "select 1 from pmieducar.matricula_turma where ref_cod_matricula = $1 and ativo = 1 limit 1";
  328 +
  329 + if (!Portabilis_Utils_Database::selectField($sql, $this->getRequest()->matricula_id)) {
  330 + $this->appendMsg("A matricula {$this->getRequest()->matricula_id} não está enturmada.", 'error');
  331 + $canPost = false;
  332 + }
  333 + }
  334 + return $canPost && $this->setService();
  335 + }
  336 +
  337 +
  338 + protected function canDeleteHistorico()
  339 + {
  340 + return $this->validatesPresenceOfInstituicaoId(false) &&
  341 + $this->validatesPresenceOfMatriculaId(false);
  342 + }
  343 +
  344 +
  345 + protected function deleteHistorico()
  346 + {
  347 + if ($this->canDeleteHistorico()) {
  348 +
  349 + $matriculaId = $this->getRequest()->matricula_id;
  350 + $alunoId = $this->getAlunoIdByMatriculaId($matriculaId);
  351 + $dadosMatricula = $this->getdadosMatricula($matriculaId);
  352 + $ano = $dadosMatricula['ano'];
  353 +
  354 + if ($this->existsHistorico($alunoId, $ano, $matriculaId)) {
  355 + $sequencial = $this->getSequencial($alunoId, $ano, $matriculaId);
  356 + $this->deleteHistoricoDisplinas($alunoId, $sequencial);
  357 +
  358 + $historicoEscolar = new clsPmieducarHistoricoEscolar(
  359 + $ref_cod_aluno = $alunoId,
  360 + $sequencial,
  361 + $ref_usuario_exc = $this->getSession()->id_pessoa,
  362 + $ref_usuario_cad = null,
  363 + //TODO nm_curso
  364 + $nm_serie = null,
  365 + $ano = $ano,
  366 + $carga_horaria = null,
  367 + $dias_letivos = null,
  368 + $escola = null,
  369 + $escola_cidade = null,
  370 + $escola_uf = null,
  371 + $observacao = null,
  372 + $aprovado = null,
  373 + $data_cadastro = null,
  374 + $data_exclusao = date('Y-m-d'),
  375 + $ativo = 0
  376 + );
  377 + $historicoEscolar->edita();
  378 +
  379 + $this->appendMsg('Histórico escolar removido com sucesso', 'success');
  380 + } else {
  381 + $this->appendMsg("Histórico matricula $matriculaId inexistente ou já removido", 'notice');
  382 + }
  383 +
  384 + $situacaoHistorico = $this->getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = true);
  385 +
  386 + $this->appendResponse('situacao_historico', $situacaoHistorico);
  387 + $this->appendResponse('link_to_historico', '');
  388 + }
  389 + }
  390 +
  391 + protected function deleteHistoricoDisplinas($alunoId, $historicoSequencial)
  392 + {
  393 + $historicoDisciplinas = new clsPmieducarHistoricoDisciplinas();
  394 + $historicoDisciplinas->excluirTodos($alunoId, $historicoSequencial);
  395 + }
  396 +
  397 +
  398 + protected function getdadosEscola($escolaId)
  399 + {
  400 + $sql = "select
  401 + (select pes.nome from pmieducar.escola esc, cadastro.pessoa pes
  402 + where esc.ref_cod_instituicao = $1 and esc.cod_escola = $2
  403 + and pes.idpes = esc.ref_idpes) as nome,
  404 +
  405 + (select coalesce((select coalesce((select municipio.nome from public.municipio,
  406 + cadastro.endereco_pessoa, cadastro.juridica, public.bairro, pmieducar.escola
  407 + where endereco_pessoa.idbai = bairro.idbai and bairro.idmun = municipio.idmun and
  408 + juridica.idpes = endereco_pessoa.idpes and juridica.idpes = escola.ref_idpes and
  409 + escola.cod_escola = $2),(select endereco_externo.cidade from cadastro.endereco_externo,
  410 + pmieducar.escola where endereco_externo.idpes = escola.ref_idpes and escola.cod_escola = $2))),
  411 + (select municipio from pmieducar.escola_complemento where ref_cod_escola = $2))) as cidade,
  412 +
  413 + (select coalesce((select coalesce((select municipio.sigla_uf from public.municipio,
  414 + cadastro.endereco_pessoa, cadastro.juridica, public.bairro, pmieducar.escola
  415 + where endereco_pessoa.idbai = bairro.idbai and bairro.idmun = municipio.idmun and
  416 + juridica.idpes = endereco_pessoa.idpes and juridica.idpes = escola.ref_idpes and
  417 + escola.cod_escola = $2),(select endereco_externo.sigla_uf from cadastro.endereco_externo,
  418 + pmieducar.escola where endereco_externo.idpes = escola.ref_idpes and escola.cod_escola = $2))),
  419 + (select inst.ref_sigla_uf from pmieducar.instituicao inst where inst.cod_instituicao = $1))) as uf";
  420 +
  421 + $params = array('params' => array($this->getrequest()->instituicao_id, $escolaId), 'return_only' => 'first-line');
  422 + return Portabilis_Utils_Database::fetchPreparedQuery($sql, $params);
  423 + }
  424 +
  425 +
  426 + protected function getNextHistoricoSequencial($alunoId)
  427 + {
  428 + //A consulta leva em consideração historicos inativos pois o sequencial é chave composta com ref_cod_aluno id
  429 + $sql = "select coalesce(max(sequencial), 0) + 1 from pmieducar.historico_escolar where ref_cod_aluno = $1";
  430 +
  431 + return Portabilis_Utils_Database::selectField($sql, $alunoId);
  432 + }
  433 +
  434 +
  435 + protected function getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId)
  436 + {
  437 + $sql = "select coalesce(max(sequencial), 0) + 1 from pmieducar.historico_disciplinas where
  438 + ref_sequencial = $1 and ref_ref_cod_aluno = $2";
  439 +
  440 + return Portabilis_Utils_Database::selectField($sql, array($historicoSequencial, $alunoId));
  441 + }
  442 +
  443 +
  444 + protected function getSituacaoMatricula($matriculaId = null)
  445 + {
  446 + if (!is_null($matriculaId)) {
  447 +
  448 + if (!is_null($this->getService(false, false))) {
  449 + $situacao = $this->getService()->getOption('aprovado');
  450 + } else {
  451 + $sql = "select aprovado from pmieducar.matricula where cod_matricula = $1";
  452 + $situacao = Portabilis_Utils_Database::selectField($sql, $matriculaId);
  453 + }
  454 +
  455 + } else if ($this->getRequest()->situacao == 'buscar-matricula') {
  456 + $situacao = $this->getService()->getOption('aprovado');
  457 + } else {
  458 + $situacoes = array(
  459 + 'aprovado' => App_Model_MatriculaSituacao::APROVADO,
  460 + 'reprovado' => App_Model_MatriculaSituacao::REPROVADO,
  461 + 'em-andamento' => App_Model_MatriculaSituacao::EM_ANDAMENTO,
  462 + 'transferido' => App_Model_MatriculaSituacao::TRANSFERIDO
  463 + );
  464 + $situacao = $situacoes[$this->getRequest()->situacao];
  465 + }
  466 + return $situacao;
  467 + }
  468 +
  469 + protected function getPercentualFrequencia()
  470 + {
  471 + if ($this->getRequest()->percentual_frequencia == 'buscar-boletim') {
  472 + $percentual = round($this->getService()->getSituacaoFaltas()->porcentagemPresenca, 2);
  473 + } else {
  474 + $percentual = $this->getRequest()->percentual_frequencia;
  475 + }
  476 + return str_replace(',', '.', $percentual);
  477 + }
  478 +
  479 + protected function getFaltaGlobalizada($defaultValue = null)
  480 + {
  481 + $faltaGeral = $this->getService()->getRegra()->get('tipoPresenca') == RegraAvaliacao_Model_TipoPresenca::GERAL;
  482 +
  483 + if (! $faltaGeral) {
  484 + return $defaultValue;
  485 + }
  486 +
  487 + return $this->getFalta();
  488 + }
  489 +
  490 + protected function postProcessamento()
  491 + {
  492 + if ($this->canPostProcessamento()) {
  493 + $matriculaId = $this->getRequest()->matricula_id;
  494 +
  495 + try {
  496 + $alunoId = $this->getAlunoIdByMatriculaId($matriculaId);
  497 + $dadosMatricula = $this->getdadosMatricula($matriculaId);
  498 + $dadosEscola = $this->getdadosEscola($dadosMatricula['escola_id']);
  499 + $ano = $dadosMatricula['ano'];
  500 + $isNewHistorico = !$this->existsHistorico($alunoId, $ano, $matriculaId);
  501 +
  502 + if ($isNewHistorico) {
  503 + $sequencial = $this->getNextHistoricoSequencial($alunoId);
  504 +
  505 + $historicoEscolar = new clsPmieducarHistoricoEscolar(
  506 + $alunoId,
  507 + $sequencial,
  508 + $ref_usuario_exc = null,
  509 + $ref_usuario_cad = $this->getSession()->id_pessoa,
  510 + $dadosMatricula['nome_serie'],
  511 + $ano,
  512 + $this->getService()->getOption('serieCargaHoraria'),
  513 + $this->getRequest()->dias_letivos,
  514 + strtoupper($dadosEscola['nome']),
  515 + strtoupper($dadosEscola['cidade']),
  516 + $dadosEscola['uf'],
  517 + $this->getRequest()->observacao,
  518 + $this->getSituacaoMatricula(),
  519 + $data_cadastro = date('Y-m-d'),
  520 + $data_exclusao = null,
  521 + $ativo = 1,
  522 + $this->getFaltaGlobalizada($defaultValue = 'null'),
  523 + $dadosMatricula['instituicao_id'],
  524 + $origem = '', //TODO
  525 + $this->getRequest()->extra_curricular,
  526 + $matriculaId,
  527 + $this->getPercentualFrequencia(),
  528 + $this->getRequest()->registro,
  529 + $this->getRequest()->livro,
  530 + $this->getRequest()->folha,
  531 + $dadosMatricula['nome_curso'],
  532 + $this->getRequest()->grade_curso_id,
  533 + null,
  534 + $dadosMatricula['escola_id'],
  535 + $this->getRequest()->dependencia,
  536 + $this->getRequest()->posicao
  537 + );
  538 +
  539 + $historicoEscolar->cadastra();
  540 + $this->recreateHistoricoDisciplinas($sequencial, $alunoId, $dadosMatricula['turma_id']);
  541 +
  542 + $this->appendMsg('Histórico processado com sucesso', 'success');
  543 + } else {
  544 +
  545 + $sequencial = $this->getSequencial($alunoId, $ano, $matriculaId);
  546 +
  547 + $historicoEscolar = new clsPmieducarHistoricoEscolar(
  548 + $alunoId,
  549 + $sequencial,
  550 + $this->getSession()->id_pessoa,
  551 + $ref_usuario_cad = null,
  552 + $dadosMatricula['nome_serie'],
  553 + $ano,
  554 + $this->getService()->getOption('serieCargaHoraria'),
  555 + $this->getRequest()->dias_letivos,
  556 + strtoupper($dadosEscola['nome']),
  557 + strtoupper($dadosEscola['cidade']),
  558 + $dadosEscola['uf'],
  559 + $this->getRequest()->observacao,
  560 + $this->getSituacaoMatricula(),
  561 + $data_cadastro = null,
  562 + $data_exclusao = null,
  563 + $ativo = 1,
  564 + $this->getFaltaGlobalizada($defaultValue = 'null'),
  565 + $dadosMatricula['instituicao_id'],
  566 + $origem = '', //TODO
  567 + $this->getRequest()->extra_curricular,
  568 + $matriculaId,
  569 + $this->getPercentualFrequencia(),
  570 + $this->getRequest()->registro,
  571 + $this->getRequest()->livro,
  572 + $this->getRequest()->folha,
  573 + $dadosMatricula['nome_curso'],
  574 + $this->getRequest()->grade_curso_id,
  575 + null,
  576 + $dadosMatricula['escola_id'],
  577 + $this->getRequest()->dependencia,
  578 + $this->getRequest()->posicao
  579 + );
  580 +
  581 + $historicoEscolar->edita();
  582 + $this->recreateHistoricoDisciplinas($sequencial, $alunoId, $dadosMatricula['turma_id']);
  583 + $this->appendMsg('Histórico reprocessado com sucesso', 'success');
  584 + }
  585 +
  586 + } catch (Exception $e) {
  587 + $this->appendMsg('Erro ao processar histórico, detalhes:' . $e->getMessage(), 'error', true);
  588 + }
  589 +
  590 + $situacaoHistorico = $this->getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = true);
  591 + $linkToHistorico = $this->getLinkToHistorico($alunoId, $ano, $matriculaId);
  592 +
  593 + $this->appendResponse('situacao_historico', $situacaoHistorico);
  594 + $this->appendResponse('link_to_historico', $linkToHistorico);
  595 + }
  596 + }
  597 +
  598 +
  599 + protected function _createHistoricoDisciplinas($fields)
  600 + {
  601 + $historicoDisciplina = new clsPmieducarHistoricoDisciplinas(
  602 + $fields['sequencial'],
  603 + $fields['alunoId'],
  604 + $fields['historicoSequencial'],
  605 + $fields['nome'],
  606 + $fields['nota'],
  607 + $fields['falta'],
  608 + $fields['ordenamento'],
  609 + $fields['carga_horaria_disciplina'],
  610 + $fields['dependencia']
  611 + );
  612 + $historicoDisciplina->cadastra();
  613 + }
  614 +
  615 + protected function shouldProcessAreaConhecimento($areaConhecimento)
  616 + {
  617 + if (!empty($this->getRequest()->area_conhecimento)) {
  618 + return in_array($areaConhecimento, $this->getRequest()->area_conhecimento);
  619 + }
  620 + return true;
  621 + }
  622 +
  623 + protected function recreateHistoricoDisciplinas($historicoSequencial, $alunoId, $turmaId = null)
  624 + {
  625 +
  626 + $this->deleteHistoricoDisplinas($alunoId, $historicoSequencial);
  627 +
  628 + if ($this->getRequest()->disciplinas == 'buscar-boletim') {
  629 +
  630 + $cnsNota = RegraAvaliacao_Model_Nota_TipoValor;
  631 + $tpNota = $this->getService()->getRegra()->get('tipoNota');
  632 + $situacaoFaltasCc = $this->getService()->getSituacaoFaltas()->componentesCurriculares;
  633 + $mediasCc = $this->getService()->getMediasComponentes();
  634 + $turmaId = $this->getRequest()->turma_id ?: $turmaId;
  635 + $mediaAreaConhecimento = $this->getRequest()->media_area_conhecimento;
  636 + $processarMediaGeral = $this->getRequest()->processar_media_geral;
  637 +
  638 + $aprovadoDependencia = $this->getSituacaoMatricula($aluno['ref_cod_matricula']) == 12;
  639 +
  640 + foreach ($this->getService()->getComponentes() as $componenteCurricular) {
  641 + if (!$this->shouldProcessAreaConhecimento($componenteCurricular->get('area_conhecimento'))) {
  642 + continue;
  643 + }
  644 + $ccId = $componenteCurricular->get('id');
  645 + $reprovado = $mediasCc[$ccId][0]->situacao == 2;
  646 + $disciplinaDependencia = ($aprovadoDependencia && $reprovado);
  647 + $nome = $componenteCurricular->nome;
  648 + $ordenamento = $componenteCurricular->ordenamento;
  649 + $carga_horaria_disciplina = $componenteCurricular->carga_horaria_disciplina;
  650 + $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId);
  651 + $nota = '';
  652 + $notaConceitualNumerica = '';
  653 +
  654 + if (clsPmieducarTurma::verificaDisciplinaDispensada($turmaId, $ccId)) {
  655 + $nota = $this->DISCIPLINA_DISPENSADA;
  656 + } elseif ($this->getRequest()->notas == 'buscar-boletim') {
  657 + if ($tpNota == $cnsNota::CONCEITUAL) {
  658 + if ($GLOBALS['coreExt']['Config']->app->processar_historicos_conceituais == "1") {
  659 + $nota = (string)$mediasCc[$ccId][0]->mediaArredondada;
  660 + $notaConceitualNumerica = (string)$mediasCc[$ccId][0]->media;
  661 + }
  662 + } elseif ($tpNota == $cnsNota::NUMERICA) {
  663 + $nota = (string)$mediasCc[$ccId][0]->mediaArredondada;
  664 + } elseif ($tpNota == $cnsNota::NUMERICACONCEITUAL) {
  665 + $nota = (string)$mediasCc[$ccId][0]->mediaArredondada;
  666 + $notaConceitualNumerica = (string)$mediasCc[$ccId][0]->media;
  667 + }
  668 + } else {
  669 + $nota = $this->getRequest()->notas;
  670 + }
  671 +
  672 + if (is_numeric($nota)) {
  673 + $nota = sprintf("%.1f", $nota);
  674 + }
  675 +
  676 + if ($processarMediaGeral) {
  677 + $nota = '-';
  678 + }
  679 +
  680 + if ($mediaAreaConhecimento) {
  681 + $nota = str_replace(',', '.', $nota);
  682 + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nome'] = $componenteCurricular->area_conhecimento->nome;
  683 + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nota'] += $nota;
  684 + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['nota_conceitual_numerica'] += $notaConceitualNumerica;
  685 + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['falta'] += $this->getFalta($situacaoFaltasCc[$ccId]);
  686 + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['ordenamento'] = $componenteCurricular->area_conhecimento->ordenamento;
  687 + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['carga_horaria_disciplina'] = $componenteCurricular->area_conhecimento->carga_horaria_disciplina;
  688 + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['dependencia'] = $disciplinaDependencia;
  689 + $arrayAreaConhecimento[$componenteCurricular->area_conhecimento->id]['count']++;
  690 + } else {
  691 + $this->_createHistoricoDisciplinas(
  692 + array(
  693 + "sequencial" => $sequencial,
  694 + "alunoId" => $alunoId,
  695 + "historicoSequencial" => $historicoSequencial,
  696 + "nome" => $nome,
  697 + "nota" => $nota,
  698 + "falta" => $this->getFalta($situacaoFaltasCc[$ccId]),
  699 + "ordenamento" => $ordenamento,
  700 + "carga_horaria_disciplina" => $carga_horaria_disciplina,
  701 + "dependencia" => $disciplinaDependencia
  702 + )
  703 + );
  704 + }
  705 + }
  706 +
  707 + if ($mediaAreaConhecimento) {
  708 + foreach ($arrayAreaConhecimento as $key => $value) {
  709 +
  710 + $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId);
  711 +
  712 + if ($this->getRequest()->notas == 'buscar-boletim') {
  713 + $nota = number_format(($value['nota_conceitual_numerica'] / $value['count']), 2, ',', '');
  714 + }
  715 +
  716 + if ($processarMediaGeral) {
  717 + $nota = '-';
  718 + }
  719 +
  720 + $this->_createHistoricoDisciplinas(
  721 + array(
  722 + "sequencial" => $sequencial,
  723 + "alunoId" => $alunoId,
  724 + "historicoSequencial" => $historicoSequencial,
  725 + "nome" => $value['nome'],
  726 + "nota" => $nota,
  727 + "falta" => round($value['falta'] / $value['count']),
  728 + "ordenamento" => $value['ordenamento'],
  729 + "carga_horaria_disciplina" => $value['carga_horaria_disciplina'],
  730 + "dependencia" => $value['dependencia']
  731 + )
  732 + );
  733 + }
  734 + }
  735 + if ($processarMediaGeral) {
  736 + $componentesCurriculares['media_geral'] = $this->insereComponenteMediaGeral($historicoSequencial, $alunoId);
  737 + }
  738 + } else {
  739 + foreach ($this->getRequest()->disciplinas as $disciplina) {
  740 + $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId);
  741 +
  742 + $this->_createHistoricoDisciplinas(
  743 + array(
  744 + "sequencial" => $sequencial,
  745 + "alunoId" => $alunoId,
  746 + "historicoSequencial" => $historicoSequencial,
  747 + "nome" => $disciplina['nome'],
  748 + "nota" => $disciplina['nota'],
  749 + "falta" => $falta = $disciplina['falta'],
  750 + "ordenamento" => $value['ordenamento'],
  751 + "carga_horaria_disciplina" => $value['carga_horaria_disciplina'],
  752 + "dependencia" => $value['dependencia']
  753 + )
  754 + );
  755 + }
  756 + }
  757 + }
  758 +
  759 + protected function insereComponenteMediaGeral($historicoSequencial, $alunoId)
  760 + {
  761 + $sequencial = $this->getNextHistoricoDisciplinasSequencial($historicoSequencial, $alunoId);
  762 + $historicoEscolar = new clsPmieducarHistoricoEscolar($alunoId, $historicoSequencial);
  763 +
  764 + $historicoEscolar->insereComponenteMediaGeral($sequencial);
  765 + }
  766 +
  767 + protected function getFalta($situacaoFaltaComponenteCurricular = null)
  768 + {
  769 + if ($this->getRequest()->faltas == 'buscar-boletim') {
  770 +
  771 + $cnsPresenca = RegraAvaliacao_Model_TipoPresenca;
  772 + $tpPresenca = $this->getService()->getRegra()->get('tipoPresenca');
  773 +
  774 + //retorna '' caso não exista situacaoFalta para o componente curricular,
  775 + //como nos casos em que a regra de avaliação muda
  776 + if ($tpPresenca == $cnsPresenca::POR_COMPONENTE && !is_null($situacaoFaltaComponenteCurricular)) {
  777 + $falta = $situacaoFaltaComponenteCurricular->total;
  778 + } elseif ($tpPresenca == $cnsPresenca::POR_COMPONENTE) {
  779 + $falta = '';
  780 + } elseif ($tpPresenca == $cnsPresenca::GERAL) {
  781 + $falta = $this->getService()->getSituacaoFaltas()->totalFaltas;
  782 + }
  783 + } else {
  784 + $falta = $this->getRequest()->faltas;
  785 + }
  786 +
  787 + return $falta;
  788 + }
  789 +
  790 + protected function getDadosMatricula($matriculaId)
  791 + {
  792 + $ano = $this->getAnoMatricula($matriculaId);
  793 + $sql = "select ref_ref_cod_serie as serie_id, ref_cod_curso as curso_id from pmieducar.matricula
  794 + where cod_matricula = $1";
  795 +
  796 + $params = array('params' => $matriculaId, 'return_only' => 'first-line');
  797 + $idsSerieCurso = Portabilis_Utils_Database::fetchPreparedQuery($sql, $params);
  798 +
  799 + $matriculas = array();
  800 +
  801 + $matriculaTurma = new clsPmieducarMatriculaTurma();
  802 + $matriculaTurma = $matriculaTurma->lista(
  803 + $matriculaId,
  804 + null,
  805 + null,
  806 + null,
  807 + null,
  808 + null,
  809 + null,
  810 + null,
  811 + 1,
  812 + $idsSerieCurso['serie_id'],
  813 + $idsSerieCurso['curso_id']
  814 + );
  815 +
  816 + $matriculaTurma = $matriculaTurma[0];
  817 +
  818 + $dadosMatricula = array();
  819 +
  820 + if (is_array($matriculaTurma) && count($matriculaTurma) > 0) {
  821 + $dadosMatricula['ano'] = $ano;
  822 + $dadosMatricula['instituicao_id'] = $matriculaTurma['ref_cod_instituicao'];
  823 + $dadosMatricula['escola_id'] = $matriculaTurma['ref_ref_cod_escola'];
  824 + $dadosMatricula['turma_id'] = $matriculaTurma['ref_cod_turma'];
  825 + $dadosMatricula['nome_serie'] = $this->getNomeSerie($matriculaTurma['ref_ref_cod_serie']);
  826 +
  827 + $dadosMatricula['nome_curso'] = $matriculaTurma['nm_curso'];
  828 + } else {
  829 + throw new Exception("Não foi possivel recuperar os dados da matricula: $matriculaId.");
  830 + }
  831 +
  832 + return $dadosMatricula;
  833 + }
  834 +
  835 + protected function getAlunoIdByMatriculaId($matriculaId)
  836 + {
  837 + $sql = "select ref_cod_aluno from pmieducar.matricula where cod_matricula = $1";
  838 +
  839 + return Portabilis_Utils_Database::selectField($sql, $matriculaId);
  840 + }
  841 +
  842 + protected function getAnoMatricula($matriculaId)
  843 + {
  844 + $sql = "select ano from pmieducar.matricula where cod_matricula = $1";
  845 +
  846 + return Portabilis_Utils_Database::selectField($sql, $matriculaId);
  847 + }
  848 +
  849 + protected function getNomeSerie($serieId)
  850 + {
  851 + $sql = "select nm_serie from pmieducar.serie where cod_serie = $1";
  852 +
  853 + return Portabilis_String_Utils::toLatin1(Portabilis_Utils_Database::selectField($sql, $serieId));
  854 + }
  855 +
  856 + protected function getSequencial($alunoId, $ano, $matriculaId)
  857 + {
  858 + $sql = "select sequencial from pmieducar.historico_escolar where ref_cod_aluno = $1 and ano = $2
  859 + and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = 1 limit 1";
  860 +
  861 + $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId);
  862 + return Portabilis_Utils_Database::selectField($sql, $params);
  863 + }
  864 +
  865 + protected function existsHistorico($alunoId, $ano, $matriculaId, $ativo = 1, $reload = false)
  866 + {
  867 + if (!isset($this->existsHistorico) || $reload) {
  868 + $sql = "select 1 from pmieducar.historico_escolar where ref_cod_aluno = $1 and ano = $2
  869 + and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = $5";
  870 +
  871 + $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId, $ativo);
  872 + $this->existsHistorico = Portabilis_Utils_Database::selectField($sql, $params) == 1;
  873 + }
  874 +
  875 + return $this->existsHistorico;
  876 + }
  877 +
  878 + protected function getSituacaoHistorico($alunoId, $ano, $matriculaId, $reload = false)
  879 + {
  880 + if ($this->existsHistorico($alunoId, $ano, $matriculaId, 1, $reload)) {
  881 + $situacao = 'Processado';
  882 + } else {
  883 + $situacao = 'Sem histórico';
  884 + }
  885 +
  886 + return $this->toUtf8($situacao);
  887 + }
  888 +
  889 + protected function getLinkToHistorico($alunoId, $ano, $matriculaId)
  890 + {
  891 + $sql = "select sequencial from pmieducar.historico_escolar where ref_cod_aluno = $1 and
  892 + ano = $2 and ref_cod_instituicao = $3 and ref_cod_matricula = $4 and ativo = 1";
  893 +
  894 + $params = array($alunoId, $ano, $this->getRequest()->instituicao_id, $matriculaId);
  895 + $sequencial = Portabilis_Utils_DataBase::selectField($sql, $params);
  896 +
  897 + if (is_numeric($sequencial)) {
  898 + $link = "/intranet/educar_historico_escolar_det.php?ref_cod_aluno=$alunoId&sequencial=$sequencial";
  899 + } else {
  900 + $link = '';
  901 + }
  902 +
  903 + return $link;
  904 + }
  905 +
  906 + protected function getMatriculas()
  907 + {
  908 + $matriculas = array();
  909 +
  910 + if ($this->canGetMatriculas()) {
  911 + $alunos = new clsPmieducarMatriculaTurma();
  912 + $alunos->setOrderby('ref_cod_curso, ref_ref_cod_serie, ref_cod_turma, sequencial_fechamento, nome');
  913 +
  914 + $alunos = $alunos->lista(
  915 + $this->getRequest()->matricula_id,
  916 + $this->getRequest()->turma_id,
  917 + null,
  918 + null,
  919 + null,
  920 + null,
  921 + null,
  922 + null,
  923 + 1,
  924 + $this->getRequest()->serie_id,
  925 + $this->getRequest()->curso_id,
  926 + $this->getRequest()->escola_id,
  927 + $this->getRequest()->instituicao_id,
  928 + $this->getRequest()->aluno_id,
  929 + null,
  930 + null,
  931 + null,
  932 + null,
  933 + $this->getRequest()->ano,
  934 + null,
  935 + true,
  936 + null,
  937 + null,
  938 + true,
  939 + null,
  940 + null,
  941 + null,
  942 + null,
  943 + null,
  944 + null,
  945 + null,
  946 + null,
  947 + null,
  948 + null,
  949 + $this->getRequest()->dependencia
  950 + );
  951 +
  952 + if (!is_array($alunos)) {
  953 + $alunos = array();
  954 + }
  955 +
  956 + $situacoesMatricula = array(
  957 + 'aprovado' => App_Model_MatriculaSituacao::APROVADO,
  958 + 'reprovado' => App_Model_MatriculaSituacao::REPROVADO,
  959 + 'reprovado-faltas' => App_Model_MatriculaSituacao::REPROVADO_POR_FALTAS,
  960 + 'em-andamento' => App_Model_MatriculaSituacao::EM_ANDAMENTO,
  961 + 'aprovado-conselho' => App_Model_MatriculaSituacao::APROVADO_PELO_CONSELHO,
  962 + 'aprovado-dependencia' => App_Model_MatriculaSituacao::APROVADO_COM_DEPENDENCIA
  963 + );
  964 +
  965 + foreach ($alunos as $aluno) {
  966 +
  967 + $situacaoMatricula = $this->getSituacaoMatricula($aluno['ref_cod_matricula']);
  968 +
  969 + if (in_array($situacaoMatricula, $situacoesMatricula)) {
  970 + $matricula = array();
  971 + $matriculaId = $aluno['ref_cod_matricula'];
  972 + $matricula['matricula_id'] = $matriculaId;
  973 + $matricula['aluno_id'] = $aluno['ref_cod_aluno'];
  974 + $matricula['nome'] = $this->toUtf8($aluno['nome_aluno']);
  975 + $matricula['nome_curso'] = $this->toUtf8($aluno['nm_curso']);
  976 + $matricula['nome_serie'] = $this->toUtf8($this->getNomeSerie($aluno['ref_ref_cod_serie']));
  977 + $matricula['nome_turma'] = $this->toUtf8($aluno['nm_turma']);
  978 + $matricula['situacao_historico'] = $this->getSituacaoHistorico($aluno['ref_cod_aluno'], $this->getRequest()->ano, $matriculaId, $reload = true);
  979 + $matricula['link_to_historico'] = $this->getLinkToHistorico($aluno['ref_cod_aluno'], $this->getRequest()->ano, $matriculaId);
  980 + $matriculas[] = $matricula;
  981 + }
  982 + }
  983 + }
  984 +
  985 + return $matriculas;
  986 + }
  987 +
  988 + protected function getObservacaoPadraoSerie()
  989 + {
  990 + if ($this->validatesPresenceOfSerieId(false, false)) {
  991 + $sql = "select coalesce(observacao_historico, '') as observacao_historico from pmieducar.serie
  992 + where cod_serie = $1";
  993 +
  994 + $observacao = Portabilis_Utils_DataBase::selectField($sql, $this->getRequest()->serie_id);
  995 + } else {
  996 + $observacao = '';
  997 + }
  998 +
  999 + return $this->toUtf8($observacao);
  1000 + }
  1001 +
  1002 + protected function saveService()
  1003 + {
  1004 + try {
  1005 + $this->getService()->save();
  1006 + } catch (CoreExt_Service_Exception $e) {
  1007 + //excecoes ignoradas :( servico lanca excecoes de alertas, que não são exatamente erros.
  1008 + //error_log('CoreExt_Service_Exception ignorada: ' . $e->getMessage());
  1009 + }
  1010 + }
  1011 +
  1012 + protected function getService($raiseExceptionOnErrors = false, $appendMsgOnErrors = true)
  1013 + {
  1014 + if (isset($this->service) && !is_null($this->service)) {
  1015 + return $this->service;
  1016 + }
  1017 +
  1018 + $msg = 'Erro ao recuperar serviço boletim: serviço não definido.';
  1019 + if ($appendMsgOnErrors) {
  1020 + $this->appendMsg($msg);
  1021 + }
  1022 +
  1023 + if ($raiseExceptionOnErrors) {
  1024 + throw new Exception($msg);
  1025 + }
  1026 +
  1027 + return null;
  1028 + }
  1029 +
  1030 + protected function canSetService($validatesPresenceOfMatriculaId = true)
  1031 + {
  1032 + try {
  1033 + $this->requiresLogin(true);
  1034 + if ($validatesPresenceOfMatriculaId) {
  1035 + $this->validatesPresenceOfMatriculaId(true);
  1036 + }
  1037 + } catch (Exception $e) {
  1038 + return false;
  1039 + }
  1040 + return true;
  1041 + }
  1042 +
  1043 + protected function setService($matriculaId = null)
  1044 + {
  1045 + if ($this->canSetService($validatesPresenceOfMatriculaId = is_null($matriculaId))) {
  1046 + try {
  1047 +
  1048 + if (!$matriculaId) {
  1049 + $matriculaId = $this->getRequest()->matricula_id;
  1050 + }
  1051 +
  1052 + $this->service = new Avaliacao_Service_Boletim(
  1053 + array(
  1054 + 'matricula' => $matriculaId,
  1055 + 'usuario' => $this->getSession()->id_pessoa
  1056 + )
  1057 + );
  1058 +
  1059 + return true;
  1060 + } catch (Exception $e) {
  1061 + $this->appendMsg('Exception ao instanciar serviço boletim: ' . $e->getMessage(), 'error', $encodeToUtf8 = true);
  1062 + }
  1063 + }
  1064 + return false;
  1065 + }
  1066 +
  1067 + protected function notImplementedError()
  1068 + {
  1069 + $this->appendMsg("Operação '{$this->getRequest()->oper}' inválida para o att '{$this->getRequest()->att}'");
  1070 + }
  1071 +
  1072 + public function Gerar()
  1073 + {
  1074 + $this->msgs = array();
  1075 + $this->response = array();
  1076 +
  1077 + if ($this->canAcceptRequest()) {
  1078 + try {
  1079 +
  1080 + if (isset($this->getRequest()->matricula_id)) {
  1081 + $this->appendResponse('matricula_id', $this->getRequest()->matricula_id);
  1082 + }
  1083 +
  1084 + if ($this->getRequest()->oper == 'get') {
  1085 + if ($this->getRequest()->att == 'matriculas') {
  1086 + $matriculas = $this->getMatriculas();
  1087 + $this->appendResponse('matriculas', $matriculas);
  1088 + $this->appendResponse('observacao_padrao', $this->getObservacaoPadraoSerie());
  1089 + } else {
  1090 + $this->notImplementedError();
  1091 + }
  1092 +
  1093 + } elseif ($this->getRequest()->oper == 'post') {
  1094 + if ($this->getRequest()->att == 'processamento') {
  1095 + $this->postProcessamento();
  1096 + } else {
  1097 + $this->notImplementedError();
  1098 + }
  1099 + } elseif ($this->getRequest()->oper == 'delete') {
  1100 + if ($this->getRequest()->att == 'historico') {
  1101 + $this->deleteHistorico();
  1102 + } else {
  1103 + $this->notImplementedError();
  1104 + }
  1105 + }
  1106 + } catch (Exception $e) {
  1107 + $this->appendMsg('Exception: ' . $e->getMessage(), $type = 'error', $encodeToUtf8 = true);
  1108 + }
  1109 + }
  1110 + echo $this->prepareResponse();
  1111 + }
  1112 +
  1113 + protected function appendResponse($name, $value)
  1114 + {
  1115 + $this->response[$name] = $value;
  1116 + }
  1117 +
  1118 + protected function prepareResponse()
  1119 + {
  1120 + $msgs = array();
  1121 + $this->appendResponse('att', isset($this->getRequest()->att) ? $this->getRequest()->att : '');
  1122 +
  1123 + foreach ($this->msgs as $m) {
  1124 + $msgs[] = array('msg' => $m['msg'], 'type' => $m['type']);
  1125 + }
  1126 + $this->appendResponse('msgs', $msgs);
  1127 +
  1128 + echo SafeJson::encode($this->response);
  1129 + }
  1130 +
  1131 + protected function appendMsg($msg, $type = "error", $encodeToUtf8 = false)
  1132 + {
  1133 + if ($encodeToUtf8) {
  1134 + $msg = utf8_encode($msg);
  1135 + }
  1136 +
  1137 + //error_log("$type msg: '$msg'");
  1138 + $this->msgs[] = array('msg' => $msg, 'type' => $type);
  1139 + }
  1140 +
  1141 + public function generate(CoreExt_Controller_Page_Interface $instance)
  1142 + {
  1143 + header('Content-type: application/json');
  1144 + $instance->Gerar();
  1145 + }
  1146 +
  1147 +
  1148 + // TODO remover metodo, ao migrar esta classe para novo padrao
  1149 +
  1150 + protected function toUtf8($str, $options = array())
  1151 + {
  1152 + return Portabilis_String_Utils::toUtf8($str, $options);
  1153 + }
  1154 +}
... ...