Minifica todos os assets das bibliotecas
498328
private function createMinifyAssetsLib()
    {
        Helper::createFolderIfNoExist(PATH_HOME . 'assetsPublic/cache');
        Helper::createFolderIfNoExist(PATH_HOME . 'assetsPublic/view');

        //Remove todos os dados das pastas de assets
        foreach (Helper::listFolder(PATH_HOME . "assetsPublic/cache") as $cache) {
            if(!is_dir(PATH_HOME . "assetsPublic/cache/" . $cache))
                unlink(PATH_HOME . "assetsPublic/cache/" . $cache);
        }
        foreach (Helper::listFolder(PATH_HOME . "assetsPublic/view") as $cache) {
            if(!is_dir(PATH_HOME . "assetsPublic/view/" . $cache))
                unlink(PATH_HOME . "assetsPublic/view/" . $cache);
        }

        $vendors = Config::getViewPermissoes();
        $this->createRepositorioCache($vendors);
        $this->downloadAssetsCache($vendors);

        foreach ($vendors as $lib) {
            $path = PATH_HOME . VENDOR . $lib . "/public/";
            if (file_exists($path . "view")) {
                foreach (Helper::listFolder($path . "view") as $view) {
                    if (preg_match('/.php$/i', $view)) {

                        //para cada view
                        $nameView = str_replace('.php', '', $view);

                        if(!in_array($nameView, ['updateSystema']))
                            $this->createViewAssets($path, $nameView);
                    }
                }
            }
        }
    }
971872
function show()
    {
        //---Mostrar la imagen dependiendo del tipo de archivo
        switch($this->type)
        {
            case IMAGETYPE_JPEG:
                imagejpeg($this->image);
                break;
            case IMAGETYPE_GIF:
                imagegif($this->image);
                break;
            case IMAGETYPE_PNG:
                imagepng($this->image);
                break;
        }
    }
75410
def AnalizarAjusteDebito(self):
        ""
        # para compatibilidad con la generacion de PDF (completo datos)
        liq = {}
        if hasattr(self, "liquidacion") and self.liquidacion:
            liq.update(self.liquidacion)
        if hasattr(self, "ajuste") and 'ajusteDebito' in self.ajuste:
            liq.update(self.ajuste['ajusteDebito'])
        if self.__ajuste_debito:
            liq.update(self.__ajuste_debito)
            self.AnalizarLiquidacion(aut=self.__ajuste_debito, liq=liq, ajuste=True)
            self.AnalizarAjuste(self.__ajuste_base, base=False)  # datos generales
        return True
443938
function asset(entry, opts, cb) {
    ss.bundler.loadFile(entry, opts, null,
      function(output) {
        switch(entry.bundle) {
          case 'html':
            return cb(ss.bundler.injectTailIfNeeded(output,opts));
          case 'css':
            return cb( client.includes.css? output:'');
          case 'worker':
            //TODO
            if (opts.compress && entry.file.indexOf('.min') === -1) {
              output = ss.bundler.minifyJSFile(output, entry.file);
            }
            break;

          default:
            //TODO with options compress saved to avoid double compression
            output = bundler.wrapCode(output, entry, opts);
            if (opts.compress && entry.file.indexOf('.min') === -1) {
              output = ss.bundler.minifyJSFile(output, entry.file);
            }
            return cb(output);
        }
      },
      function(err) {
        ss.log.clientIssue(client,options,err,entry);
        switch(entry.ext) {
          case 'html':
            return cb('Couldn\'t format ' + entry.file + err.userInfoHTML);
          case 'css':
            return cb('/* couldn\'t format ' + entry.file + err.userInfoText+' */');
          default:
            return cb('// couldn\'t format ' + entry.file + err.userInfoText);
        }
      });
  }
687970
public function collection($name)
    {
        // Verificar se deve adicionar a colecao na lista
        if (! array_key_exists($name, $this->collections)) {
            $this->collections[$name] = [];
        }

        // Verificar se jah foi criado
        if (db()->hasCollection($name)) {
            return true;
        }

        // Criar colecao
        db()->createCollection($name);

        return true;
    }
48094
private function init(){
        //Load Archivos de Funciones
        $this->loadFunctionsFiles();
        //Instancio el sistema de Cache
        $this->cache= new Support\Cache\Cache();
        //EnolaContext->init(): Cargo las configuraciones de contexto faltante
        $this->context->init();
        //Instancio el motor de Dependencias
        $this->dependenciesEngine= new Support\DependencyEngine\DependenciesEngine();
        //Cargo las librerias definidas por el usuario
        $this->loadLibraries();
    }
488662
function(tiposMB, endian, noErrores) {
    if (!(this instanceof generadorBuffer)) return new generadorBuffer(tiposMB, endian, noErrores);
    this.bytesBuffer = 0;
    this.buff = new Array;
    this.tiposMB = tiposMB;
    this.endian = endian;
    this.noErrores = noErrores;
    
    /*
     * Creación de las funciones específicas para cada tipo de dato
     */
    
    // Obtenemos un array con los tipos de datos de ModBus
    var arrTipos = new Array;
    var tipo;
    for (tipo in this.tiposMB) {
        arrTipos.push(tipo);
    }  

    // Creamos las funciones correspondientes para cada tipo de dato, de forma que conviertan los bytes del buffer en el tipo numérico adecuado
    arrTipos.forEach((function (nombreTipo) {
        generadorBuffer.prototype[nombreTipo] = function(dato) {
            return this.agregarDato(nombreTipo, dato);
        }
    }).bind(this));
    
    return true; // Devuelve algo para evitar errores en la comprobación de código
}
1244288
public function index()
    {
        $page = Request::input('page');
        $perPage = config('typicms.galleries.per_page');
        $data = $this->repository->byPage($page, $perPage, ['translations']);
        $models = new Paginator($data->items, $data->totalItems, $perPage, null, ['path' => Paginator::resolveCurrentPath()]);

        return view('galleries::public.index')
            ->with(compact('models'));
    }
464878
def CargarFormatoPDF(self, archivo="liquidacion_form_c1116b_wslpg.csv"):
        ""

        # si no encuentro archivo, lo busco en el directorio predeterminado:
        if not os.path.exists(archivo):
            archivo = os.path.join(self.InstallDir, "plantillas", os.path.basename(archivo))

        if DEBUG: print "abriendo archivo ", archivo
        # inicializo la lista de los elementos:
        self.elements = []
        for lno, linea in enumerate(open(archivo.encode('latin1')).readlines()):
            if DEBUG: print "procesando linea ", lno, linea
            args = []
            for i,v in enumerate(linea.split(";")):
                if not v.startswith("'"): 
                    v = v.replace(",",".")
                else:
                    v = v#.decode('latin1')
                if v.strip()=='':
                    v = None
                else:
                    v = eval(v.strip())
                args.append(v)

            # corrijo path relativo para las imágenes:
            if args[1] == 'I':
                if not os.path.exists(args[14]):
                    args[14] = os.path.join(self.InstallDir, "plantillas", os.path.basename(args[14]))
                if DEBUG: print "NUEVO PATH:", args[14]          

            self.AgregarCampoPDF(*args)

        self.AgregarCampoPDF("anulado", 'T', 150, 250, 0, 0, 
              size=70, rotate=45, foreground=0x808080, 
              priority=-1)

        if HOMO:
            self.AgregarCampoPDF("homo", 'T', 100, 250, 0, 0,
                              size=70, rotate=45, foreground=0x808080, 
                              priority=-1)

        
        # cargo los elementos en la plantilla
        self.template.load_elements(self.elements)
        
        return True
580142
public function index() {
		$this->Prg->commonProcess();
        $conds = $this->Cliente->parseCriteria( $this->Prg->parsedParams() );
		$this->Cliente->recursive = 0;
                
        $descuentoMaximo = Configure::read('Mozo.descuento_maximo');
        $currentRole = $this->Session->read('Auth.User.role');
             
        
        if ( strtolower($currentRole) == 'mozo' && is_numeric( $descuentoMaximo ) ) {                
            $conds['OR'] = array(
                    "Descuento.porcentaje <= $descuentoMaximo",
                    'Descuento.porcentaje IS NULL'
                );
        }
        $this->Paginator->settings['conditions'] = $conds;
        
        $descuentos = $this->Cliente->Descuento->find('list');
		$tipoDocumentos = $this->Cliente->TipoDocumento->find('list');
		$ivaResponsabilidades = $this->Cliente->IvaResponsabilidad->find('list');
		$this->set(compact('descuentos', 'tipoDocumentos', 'ivaResponsabilidades'));
		$this->set('clientes', $this->Paginator->paginate());
		$this->set('_serialize', array('clientes'));
	}
599856
function minify($files,$mime=NULL,$header=TRUE,$path=NULL) {
		$fw=Base::instance();
		if (is_string($files))
			$files=$fw->split($files);
		if (!$mime)
			$mime=$this->mime($files[0]);
		preg_match('/\w+$/',$files[0],$ext);
		$cache=Cache::instance();
		$dst='';
		if (!isset($path))
			$path=$fw->UI.';./';
		foreach ($fw->split($path,FALSE) as $dir)
			foreach ($files as $file)
				if (is_file($save=$fw->fixslashes($dir.$file)) &&
					is_bool(strpos($save,'../')) &&
					preg_match('/\.(css|js)$/i',$file)) {
					if ($fw->CACHE &&
						($cached=$cache->exists(
							$hash=$fw->hash($save).'.'.$ext[0],$data)) &&
						$cached[0]>filemtime($save))
						$dst.=$data;
					else {
						$data='';
						$src=$fw->read($save);
						for ($ptr=0,$len=strlen($src);$ptr<$len;) {
							if (preg_match('/^@import\h+url'.
								'\(\h*([\'"])((?!(?:https?:)?\/\/).+?)\1\h*\)[^;]*;/',
								substr($src,$ptr),$parts)) {
								$path=dirname($file);
								$data.=$this->minify(
									($path?($path.'/'):'').$parts[2],
									$mime,$header
								);
								$ptr+=strlen($parts[0]);
								continue;
							}
							if ($ext[0]=='css'&&preg_match('/^url\(([^\'"].*?[^\'"])\)/i',
									substr($src,$ptr),$parts)) {
								$data.=$parts[0];
								$ptr+=strlen($parts[0]);
								continue;
							}
							if ($src[$ptr]=='/') {
								if ($src[$ptr+1]=='*') {
									// Multiline comment
									$str=strstr(
										substr($src,$ptr+2),'*/',TRUE);
									$ptr+=strlen($str)+4;
								}
								elseif ($src[$ptr+1]=='/') {
									// Single-line comment
									$str=strstr(
										substr($src,$ptr+2),"\n",TRUE);
									$ptr+=(empty($str))?
										strlen(substr($src,$ptr)):strlen($str)+2;
								}
								else {
									// Presume it's a regex pattern
									$regex=TRUE;
									// Backtrack and validate
									for ($ofs=$ptr;$ofs;$ofs--) {
										// Pattern should be preceded by
										// open parenthesis, colon,
										// object property or operator
										if (preg_match(
											'/(return|[(:=!+\-*&|])$/',
											substr($src,0,$ofs))) {
											$data.='/';
											$ptr++;
											while ($ptr<$len) {
												$data.=$src[$ptr];
												$ptr++;
												if ($src[$ptr-1]=='\\') {
													$data.=$src[$ptr];
													$ptr++;
												}
												elseif ($src[$ptr-1]=='/')
													break;
											}
											break;
										}
										elseif (!ctype_space($src[$ofs-1])) {
											// Not a regex pattern
											$regex=FALSE;
											break;
										}
									}
									if (!$regex) {
										// Division operator
										$data.=$src[$ptr];
										$ptr++;
									}
								}
								continue;
							}
							if (in_array($src[$ptr],['\'','"'])) {
								$match=$src[$ptr];
								$data.=$match;
								$ptr++;
								// String literal
								while ($ptr<$len) {
									$data.=$src[$ptr];
									$ptr++;
									if ($src[$ptr-1]=='\\') {
										$data.=$src[$ptr];
										$ptr++;
									}
									elseif ($src[$ptr-1]==$match)
										break;
								}
								continue;
							}
							if (ctype_space($src[$ptr])) {
								if ($ptr+1<strlen($src) &&
									preg_match('/[\w'.($ext[0]=='css'?
										'#\.%+\-*()\[\]':'\$').']{2}|'.
										'[+\-]{2}/',
										substr($data,-1).$src[$ptr+1]) ||
									($ext[0]=='css' && $ptr+2<strlen($src) &&
									preg_match('/:\w/',substr($src,$ptr+1,2))))
									$data.=' ';
								$ptr++;
								continue;
							}
							$data.=$src[$ptr];
							$ptr++;
						}
						if ($ext[0]=='css')
							$data=str_replace(';}','}',$data);
						if ($fw->CACHE)
							$cache->set($hash,$data);
						$dst.=$data;
					}
				}
		if (PHP_SAPI!='cli' && $header)
			header('Content-Type: '.$mime.'; charset='.$fw->ENCODING);
		return $dst;
	}
494121
private function writeEndereco (
        $t, $l, $w, $titulo, $nomeDestinatario, $logradouro, $numero1, $complemento, $bairro,
        $cidade, $uf, $cep = null, $destinatario = false
    ) {
        //$this->pdf->SetTextColor(51,51,51);
        if ($destinatario === true) {
            $addressPadding = 5;

            $t = $t-2;
            $this->pdf->SetDrawColor(0,0,0);
            $this->pdf->Line(0, $t, 106.36, $t);

            // Titulo do bloco: destinatario
            $this->pdf->setFillColor(0,0,0);
            $this->pdf->SetDrawColor(0,0,0);
            $this->pdf->Rect(0, $t, 36, 5, 'F');

            $this->pdf->SetFont('', 'B');
            $this->pdf->SetFontSize(11);
            $this->pdf->SetTextColor(255,255,255);
            $this->pdf->SetXY($l + 3, $t);
            $this->t($w, $titulo, 2, '');

            $this->pdf->SetTextColor(0,0,0);

            $this->pdf->Image(realpath(dirname(__FILE__)) . '/logo-correios.png', 84, $t+1, 20, 4);

            // Nome da pessoa
            $this->pdf->SetFont('', '', 11);
            $this->setFillColor(190, 190, 190);
            $this->pdf->SetX($l + $addressPadding);
            $this->multiLines($w, $nomeDestinatario, 'L');

        } else {
            $addressPadding = 2;
            $t = $t -1;
            $this->pdf->SetDrawColor(0,0,0);
            $this->pdf->Line(0, $t, 106.36, $t);

            $t++;

            // Titulo do bloco: destinatario ou remetente
            $this->pdf->SetFont('', 'B');
            $this->setFillColor(60, 60, 60);
            $this->pdf->SetFontSize(10);
            $this->pdf->SetXY(2, $t);
            $this->t($w, $titulo, 2, '');

            // Nome da pessoa
            $this->pdf->SetFont('', '', 10);
            $this->setFillColor(190, 190, 190);
            $this->pdf->SetXY(22, $t);
            $this->multiLines($w, trim($nomeDestinatario), 'L');
        }

        $w = $w - $addressPadding;
        $l = $l + $addressPadding;

        //Primeria parte do endereco
        $address1 = $logradouro;
        $numero = $numero1;
        if (!$numero || strtolower($numero) == 'sn') {
            $address1 .= ', s/ nº';
        } else {
            $address1 .= ', ' . $numero;
        }
        if ($complemento) {
            $complemento = $complemento . ' ';
        }
        $this->setFillColor(100, 190, 190);
        $this->pdf->SetX($l);
        $this->multiLines($w, $address1, 'L');

        //Segunda parte do endereco
        $this->pdf->SetX($l);

        $this->setFillColor(100, 130, 190);
        $this->multiLines($w, $complemento . $bairro, 'L');

        $this->setFillColor(100, 30, 210);
        $this->pdf->SetX($l);
        $this->pdf->SetFont('', 'B');
        $this->t($l, ($cep ? $cep . '  ' : ''), 0, 'L');

        $this->pdf->SetFont('');
        $this->pdf->SetX($l + 20);
        $this->t(15, ucfirst(trim($cidade)) . '/' . strtoupper(trim($uf)), 2, 'L');

        return $this->pdf->GetY();
    }
903230
public function cmdGetLibrary()
    {
        $list = $this->getListLibrary();
        $this->outputFormat($list);
        $this->outputFormatTableLibrary($list);
        $this->output();
    }
1208495
protected function setupComposer()
    {
        $composer_file = $this->getComposerJsonFile();
        $contents = json_decode(file_get_contents($composer_file), true);
        if (!isset($contents['autoload']['files'])) {
            // Cria a seção files
            $contents['autoload']['files'] = [];
        }

        $autoloader_file = $this->getAutoloaderFile();
        if (array_search($autoloader_file, $contents['autoload']['files']) === false) {
            // Adiciona o arquivo com prioridade
            $contents['autoload']['files'] = array_merge(
                [$autoloader_file],
                $contents['autoload']['files']
            );
        }

        $json_contents = str_replace("\\/", "/", json_encode($contents, JSON_PRETTY_PRINT));
        if (file_put_contents($composer_file, $json_contents) === false) {
            $this->getObfuscator()->addErrorMessage("Could not update composer.json file");
            return false;
        }

        $this->getObfuscator()->addErrorMessage("O arquivo composer.json foi configurado com sucesso.");

        return true;
    }
889093
public function render(array $options = array())
    {
        $options = $this->optionsTratament($options);
        $this->_pdf = new ZfPdf\PdfDocument();
        $this->_font = ZfPdf\Font::fontWithName(ZfPdf\Font::FONT_HELVETICA);

        //$options['colors'] = array_merge($colors, (array) $options['colors']);

        $this->_la = '';
        $larg = $this->calculateCellSize();
        $this->_cellFontSize = 8;

        // Define os estilos do documento
        $this->defineStyles($options);

        // Pega o total de páginas
        $this->getTotalPages($options);

        // Adiciona página ao documento PDF
        $this->addPage($options);

        // Adicionar logomarca se definido nas opções
        $this->addLogo($options);

        // Adiciona Titulo e Subtitulo de acordo com as opções definidas
        $this->addTitle($options);

        //Iniciar a contagem de paginas
        $pagina = 1;

        // Desenha o rodapé do documento
        $this->drawFooter($pagina, $options);

        $this->_page->setFont($this->_font, $this->_cellFontSize);

        $iLarg = 0;
        foreach ($larg as $final) {
            $this->_cell[$iLarg] = round($final * ($this->_page->getWidth() - 80) / array_sum($larg));
            $iLarg++;
        }

        $cellsCount = count($this->_arrayForm['gridfieldsconfig']);
        $this->_largura = ($this->_page->getWidth() - 80) / $cellsCount;
        $this->_altura = $this->_page->getHeight() - 120;

        // Desenha os nomes dos campos
        $this->drawFieldName($this->_topo, $this->_styleText);

        $this->_page->setStyle($this->_style);

        if (is_array($this->_arrayData) and !empty($this->_arrayData)) {

            $ia = 0;
            $aa = 0;
            foreach ($this->_arrayData as $value) {
                if ($this->_altura <= 80) {

                    // Adiciona página ao documento PDF
                    $this->addPage($options);

                    $pagina++;

                    // Adicionar logomarca se definido nas opções
                    $this->addLogo($options);

                    // Adiciona Titulo e Subtitulo de acordo com as opções definidas
                    $this->addTitle($options);

                    //set font
                    $this->_altura = $this->_page->getHeight() - 120;

                    // Desenha o rodapé do documento
                    $this->drawFooter($pagina, $options);

                    //
                    $this->_largura1 = 40;
                    $this->_page->setFont($this->_font, $this->_cellFontSize + 1);

                    // Desenha os nomes dos campos
                    $this->drawFieldName($this->_topo, $this->_styleText);
                }

                $this->_la = 0;
                $this->_altura = $this->_altura - 16;
                $i = 0;
                $tdf = $ia % 2 ? $this->td : $this->td2;
                $a = 1;

                //A linha horizontal
                //$centrar = round(($this->_page->getWidth() - 80) / 2) + 30;
                if ((int) $this->_la == 0) {
                    $this->_largura1 = 40;
                } else {
                    $this->_largura1 = $this->_cell[$i - 1] + $this->_largura1;
                }
                $this->_la = 0;

                ////////////
                //Vamos saber quantas linhas tem este registo
                $nlines = array();
                $nl = 0;
                foreach ($value as $value2) {
                    $line = $this->widthForStringUsingFontSize(strip_tags(trim($value2)), $this->_font, 8);
                    $nlines[] = ceil($line / $this->_cell[$nl]);
                    $nl++;
                }

                sort($nlines);
                foreach ($value as $value1) {
                    $value1 = strip_tags(trim($value1));
                    if ((int) $this->_la == 0) {
                        $this->_largura1 = 40;
                    } else {
                        $this->_largura1 = $this->_cell[$i - 1] + $this->_largura1;
                    }

                    $this->_page->setStyle($tdf);
                    $this->_page->drawRectangle($this->_largura1, $this->_altura - 4, $this->_largura1 + $this->_cell[$i] + 1, $this->_altura + 12);
                    $this->_page->setStyle($this->_styleText);
                    $this->_page->drawText($value1, $this->_largura1 + 2, $this->_altura, 'UTF-8');
                    $this->_la = $this->_largura1;
                    $i++;
                    $a++;
                }

                $aa++;
                $ia++;
            }
        }
        header('Content-Description: File Transfer');
        header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
        header('Pragma: public');
        header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header("Content-Type: application/pdf");
        header('Content-Disposition: attachment; filename="' . $options['name'] . '.pdf"');
        header('Content-Transfer-Encoding: binary');

        echo $this->_pdf->render();
        die();
    }
249589
private function saveLibraries() {
    // Keep track of the number of libraries that have been saved
    $newOnes = 0;
    $oldOnes = 0;

    // Go through libraries that came with this package
    foreach ($this->h5pC->librariesJsonData as $libString => &$library) {
      // Find local library identifier
      $libraryId = $this->h5pC->getLibraryId($library, $libString);

      // Assume new library
      $new = TRUE;
      if ($libraryId) {
        // Found old library
        $library['libraryId'] = $libraryId;

        if ($this->h5pF->isPatchedLibrary($library)) {
          // This is a newer version than ours. Upgrade!
          $new = FALSE;
        }
        else {
          $library['saveDependencies'] = FALSE;
          // This is an older version, no need to save.
          continue;
        }
      }

      // Indicate that the dependencies of this library should be saved.
      $library['saveDependencies'] = TRUE;

      // Convert metadataSettings values to boolean & json_encode it before saving
      $library['metadataSettings'] = isset($library['metadataSettings']) ?
        H5PMetadata::boolifyAndEncodeSettings($library['metadataSettings']) :
        NULL;

      $this->h5pF->saveLibraryData($library, $new);

      // Save library folder
      $this->h5pC->fs->saveLibrary($library);

      // Remove cached assets that uses this library
      if ($this->h5pC->aggregateAssets && isset($library['libraryId'])) {
        $removedKeys = $this->h5pF->deleteCachedAssets($library['libraryId']);
        $this->h5pC->fs->deleteCachedAssets($removedKeys);
      }

      // Remove tmp folder
      H5PCore::deleteFileTree($library['uploadDirectory']);

      if ($new) {
        $newOnes++;
      }
      else {
        $oldOnes++;
      }
    }

    // Go through the libraries again to save dependencies.
    foreach ($this->h5pC->librariesJsonData as &$library) {
      if (!$library['saveDependencies']) {
        continue;
      }

      // TODO: Should the table be locked for this operation?

      // Remove any old dependencies
      $this->h5pF->deleteLibraryDependencies($library['libraryId']);

      // Insert the different new ones
      if (isset($library['preloadedDependencies'])) {
        $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['preloadedDependencies'], 'preloaded');
      }
      if (isset($library['dynamicDependencies'])) {
        $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['dynamicDependencies'], 'dynamic');
      }
      if (isset($library['editorDependencies'])) {
        $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['editorDependencies'], 'editor');
      }

      // Make sure libraries dependencies, parameter filtering and export files gets regenerated for all content who uses this library.
      $this->h5pF->clearFilteredParameters($library['libraryId']);
    }

    // Tell the user what we've done.
    if ($newOnes && $oldOnes) {
      if ($newOnes === 1)  {
        if ($oldOnes === 1)  {
          // Singular Singular
          $message = $this->h5pF->t('Added %new new H5P library and updated %old old one.', array('%new' => $newOnes, '%old' => $oldOnes));
        }
        else {
          // Singular Plural
          $message = $this->h5pF->t('Added %new new H5P library and updated %old old ones.', array('%new' => $newOnes, '%old' => $oldOnes));
        }
      }
      else {
        // Plural
        if ($oldOnes === 1)  {
          // Plural Singular
          $message = $this->h5pF->t('Added %new new H5P libraries and updated %old old one.', array('%new' => $newOnes, '%old' => $oldOnes));
        }
        else {
          // Plural Plural
          $message = $this->h5pF->t('Added %new new H5P libraries and updated %old old ones.', array('%new' => $newOnes, '%old' => $oldOnes));
        }
      }
    }
    elseif ($newOnes) {
      if ($newOnes === 1)  {
        // Singular
        $message = $this->h5pF->t('Added %new new H5P library.', array('%new' => $newOnes));
      }
      else {
        // Plural
        $message = $this->h5pF->t('Added %new new H5P libraries.', array('%new' => $newOnes));
      }
    }
    elseif ($oldOnes) {
      if ($oldOnes === 1)  {
        // Singular
        $message = $this->h5pF->t('Updated %old H5P library.', array('%old' => $oldOnes));
      }
      else {
        // Plural
        $message = $this->h5pF->t('Updated %old H5P libraries.', array('%old' => $oldOnes));
      }
    }

    if (isset($message)) {
      $this->h5pF->setInfoMessage($message);
    }
  }
372418
public function create()
    {
        $fs = new Filesystem();

        if (!$this->sourceDir) {
            throw new \Exception('O diretório de código fonte "singular.directory.src" da aplicação não foi definido!');
        }

        $migrationDir = $this->getMigrationDir();

        if (!$fs->exists($migrationDir)) {
            throw new \Exception(sprintf('O diretório de migration não existe!'));
        }

        $timestamp = time();

        $aplicacoes = $this->getAplicacoesToMigration();

        if (count($aplicacoes) > 0) {
            $template = file_get_contents(
                __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."app_migration.tpl"
            );

            $template = str_replace('$TIMESTAMP',$timestamp, $template);
            $template = str_replace('$APLICACOES', $this->arrayToString($aplicacoes, $timestamp) , $template);

            $dt = new \DateTime('now', new \DateTimeZone('UTC'));
            $date = $dt->format('YmdHis');

            file_put_contents($migrationDir.DIRECTORY_SEPARATOR.$date.'_insere_registros_aplicacoes_'.$timestamp.'.php', $template);
        }

        $modulos = $this->getModulosToMigration();

        if (count($modulos) > 0) {
            $template = file_get_contents(
                __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."mod_migration.tpl"
            );

            $template = str_replace('$TIMESTAMP',$timestamp, $template);
            $template = str_replace('$MODULOS', $this->arrayToString($modulos, $timestamp) , $template);

            sleep(1);

            $dt = new \DateTime('now', new \DateTimeZone('UTC'));
            $date = $dt->format('YmdHis');

            file_put_contents($migrationDir.DIRECTORY_SEPARATOR.$date.'_insere_registros_modulos_'.$timestamp.'.php', $template);
        }

        $this->clearMigrations();

        return count($modulos) + count($aplicacoes);
    }