NxTIC/manager/module/upload.php

492 lines
16 KiB
PHP
Raw Normal View History

<?php
namespace manager\module;
use \manager\Database;
use \manager\ResourceDispatcher;
use \manager\sessionManager;
use \manager\ModuleRequest;
use \manager\ManagerError;
use \manager\Repo;
class upload{
/* RENVOIE LE CHEMIN D'UN fichier
*
* @prefix<String> Préfixe (dossier parent) du fichier
* @extension<String> Extension du fichier
*
* @return response<Array> Renvoie le chemin du fichier, ainsi qu'une erreur de 'ManagerError'
*
*/
private static function getPath($prefix, $extension){
// Si on est pas connecté, on retourne une erreur -> impossible via token
if( !connected() ) return array( 'error' => ManagerError::PermissionError );
/* [1] Chargement du fichier de config
=========================================================*/
/* (1) On récupère le fichier */
$uploadAuth = ResourceDispatcher::getResource('f/json/upload-auth/conf');
/* (2) Si une erreur pour le fichier de conf */
if( $uploadAuth === false )
return array( 'error' => ManagerError::UnreachableResource );
/* (3) On récupère la config sous forme de tableau */
$uploadAuth = json_decode( $uploadAuth, true );
/* (4) Si erreur de PARSAGE */
if( !is_array($uploadAuth) )
return array( 'error' => ManagerError::ParsingFailed );
/* [2] Vérification du préfixe
=========================================================*/
// Si le préfixe n'est pas dans la config -> erreur
if( !in_array($prefix, $uploadAuth['directories']) )
return array( 'error' => ManagerError::UploadError );
/* [3] Construction du chemin
=========================================================*/
/* (1) On construit le chemin */
$path = __ROOT__.$uploadAuth['root'].'/'.$prefix.'/';
/* (2) On crée le dossier s'il n'existe pas */
if ( !file_exists($path) ) mkdir($path, 0775, true);
/* (3) On construit le nom du fichier */
$fileName = $_SESSION['username'].'.'.$extension;
/* (4) On se place dans le dossier */
chdir( $path );
/* [4] Gestion du retour
=========================================================*/
return array(
'error' => ManagerError::Success,
'path' => $path.$fileName
);
}
/* EFFECTUE UN UPLOAD D'UN fichier
*
* @prefix<String> Préfixe (dossier parent) du fichier
* @extension<String> Extension du fichier
* @file<FILE> Pointeur vers $_FILES['']
* @tester<Function> Fonction qui renvoie TRUE si le format est correct (en prenant le contenu du fichier en paramètre)
*
* @return error<ManagerError> Retourne l'erreur attestant de l'état de l'upload
*
*/
private static function simpleFile($prefix, $extension, $file, $tester){
// Si on est pas connecté, on retourne une erreur -> impossible via token
if( !connected() ) return array( 'error' => ManagerError::PermissionError );
/* [1] On récupère le chemin du fichier à créer et vérifie le dossier
=========================================================*/
$pathResponse = self::getPath($prefix, $extension);
// Si une erreur est intervenue, on la retourne
if( $pathResponse['error'] != ManagerError::Success )
return $pathResponse['error'];
/* [2] Vérification du format (via la fonction $tester)
=========================================================*/
/* (1) Si $tester est une fonction, on effectue le test */
if( is_callable($tester) ){
/* (2) Sinon, on vérifie le format */
$file_content = file_get_contents($file['tmp_name']);
/* (3) On retourne 'FormatError' si erreur de format */
if( !$tester($file_content) ) return ManagerError::FormatError;
}
/* [3] Création du fichier (temporaire->permanent)
=========================================================*/
/* (1) On déplace le fichier avec le nom formel */
if( move_uploaded_file($file['tmp_name'], $pathResponse['path']) ){
// on modifie les droits du fichier
chmod($pathResponse['path'], 0774);
return ManagerError::Success;
/* (2) Si une erreur occure -> 'UploadError' */
}else
return ManagerError::UploadError;
}
/* IMPORT D'UN JOURNAL D'APPEL
*
* @file<FILE> Pointeur vers $_FILES['']
*
*/
public static function call_log($params){
extract($params);
/* [1] Gestion de l'upload du fichier et de la vžérification du format
=========================================================*/
$uploadError = self::simpleFile(
'call_log', // nom du dossier d'upload
'xml', // format du fichier
$file, // Fichier lui-même
function($content){ // Vérification du format du fichier
/* (1) Vérification du format XML */
$xml = simplexml_load_string($content);
if( $xml === false ) return false; // Si erreur de parsage, on retourne une erreur
/* (2) Vérification du contenu (balises) */
// Doit avoir des Item(s)
if( !isset($xml->Item) )
return false;
// Vérification de tous les champs
foreach($xml->Item as $log){
$checkAttributes = isset($log['Number']);
$checkAttributes = $checkAttributes && isset($log['Name']);
$checkAttributes = $checkAttributes && isset($log['Date']);
$checkAttributes = $checkAttributes && isset($log['Duration']);
$checkAttributes = $checkAttributes && isset($log['Direction']);
$checkAttributes = $checkAttributes && isset($log['Type']);
// Si on a pas tout les champs, on retourne une erreur
if( !$checkAttributes )
return false;
}
/* (3) Si tout s'est bien passé, le format est bon */
return true;
}
);
/* [2] Gestion du retour (unserialize)
=========================================================*/
/* (1) Si erreur d'upload, on la renvoie */
if( $uploadError != ManagerError::Success )
return array( 'ModuleError' => $uploadError );
/* (2) Gestion du parsage (unserialize) du journal d'appel */
$request = new ModuleRequest('call_log/unserialize', array( 'phone_number' => $phone_number ) );
$response = $request->dispatch();
/* (3) Restitution du retour de `unserialize` */
return array_merge(
array( 'ModuleError' => $response->error ),
$response->getAll()
);
}
/* IMPORT D'UNE SAUVEGARDE DE FORMULAIRE LOCAL
*
* @file<FILE> Pointeur vers $_FILES['']
*
*/
public static function local_data($params){
extract($params);
/* [1] Upload et vérifiaction du format du fichier
=========================================================*/
$uploadError = self::simpleFile(
'local_data', // nom du dossier d'upload
'json', // format du fichier
$file, // Fichier lui-même
function($content){ // Vérification du format du fichier
/* (1) Vérification du format JSON */
$json = json_decode($content, true);
if( $json == null )
return false; // Si erreur de parsage, on retourne une erreur
/* (2) Vérification du contenu de premier niveau */
$checkLevel0 = isset($json['subject']) && is_array($json['subject']);
$checkLevel0 = $checkLevel0 && isset($json['contacts']) && is_array($json['contacts']);
$checkLevel0 = $checkLevel0 && isset($json['mini']) && is_array($json['mini']);
$checkLevel0 = $checkLevel0 && isset($json['fiches']) && is_array($json['fiches']);
$checkLevel0 = $checkLevel0 && isset($json['matrice']) && is_array($json['matrice']);
// Erreur si level 0 incorrect
if( !$checkLevel0 )
return false;
/* (3) Vérification du sujet */
$checkSubject = isset($json['subject']['tmp_id']) && ( is_string($json['subject']['tmp_id']) || is_null($json['subject']['tmp_id']) );
$checkSubject = $checkSubject && isset($json['subject']['username']) && is_string($json['subject']['username']);
// Erreur des attributs du sujet incorrects ou manquants
if( !$checkSubject )
return false;
/* (4) Vérification des contacts */
foreach($json['contacts'] as $contact){
$checkContact = isset($contact['uid']) && is_numeric($contact['uid']);
$checkContact = $checkContact && isset($contact['username']) && is_string($contact['username']);
$checkContact = $checkContact && isset($contact['sms']) && is_numeric($contact['sms']);
$checkContact = $checkContact && isset($contact['call']) && is_numeric($contact['call']);
$checkContact = $checkContact && isset($contact['countsms']) && is_numeric($contact['countsms']);
$checkContact = $checkContact && isset($contact['countcall']) && is_numeric($contact['countcall']);
// Si erreur des attributs du contact incorrects ou manquants
if( !$checkContact )
return false;
}
/* (5) Vérification des mini-fiches */
foreach($json['mini'] as $mini){
$checkMini = isset($mini['uid']) && is_numeric($mini['uid']);
$checkMini = $checkMini && isset($mini['sexe']) && is_string($mini['sexe']);
$checkMini = $checkMini && isset($mini['age']) && is_string($mini['age']);
$checkMini = $checkMini && isset($mini['studies']) && is_string($mini['studies']);
$checkMini = $checkMini && isset($mini['loc']) && is_numeric($mini['loc']);
// Si erreur des attributs des mini-fiches incorrects ou manquants
if( !$checkMini )
return false;
}
/* (6) Vérification des fiches */
foreach($json['fiches'] as $fiches){
$checkFiche = isset($fiches['uid']) && is_numeric($fiches['uid']);
$checkFiche = $checkFiche && isset($fiches['contact']) && is_numeric($fiches['contact']);
$checkFiche = $checkFiche && isset($fiches['sexe']) && is_string($fiches['sexe']);
$checkFiche = $checkFiche && isset($fiches['age']) && is_string($fiches['age']);
$checkFiche = $checkFiche && isset($fiches['job']) && is_string($fiches['job']);
$checkFiche = $checkFiche && isset($fiches['loc']) && is_numeric($fiches['loc']);
$checkFiche = $checkFiche && isset($fiches['studies']) && is_string($fiches['studies']);
$checkFiche = $checkFiche && isset($fiches['famsit']) && is_numeric($fiches['famsit']);
$checkFiche = $checkFiche && isset($fiches['reltype']) && is_numeric($fiches['reltype']);
$checkFiche = $checkFiche && isset($fiches['reltypeSpecial']) && is_string($fiches['reltypeSpecial']);
$checkFiche = $checkFiche && isset($fiches['city']) && is_string($fiches['city']);
$checkFiche = $checkFiche && isset($fiches['cp']) && is_string($fiches['cp']);
$checkFiche = $checkFiche && isset($fiches['duration']) && is_array($fiches['duration']);
$checkFiche = $checkFiche && isset($fiches['context']) && is_numeric($fiches['context']);
$checkFiche = $checkFiche && isset($fiches['contextSpecial']) && is_array($fiches['contextSpecial']);
$checkFiche = $checkFiche && isset($fiches['freq']) && is_array($fiches['freq']);
$checkFiche = $checkFiche && isset($fiches['connect']) && is_array($fiches['connect']);
$checkFiche = $checkFiche && isset($fiches['connectSpecial']) && is_array($fiches['connectSpecial']);
// Si erreur des attributs des fiches incorrects ou manquants
if( !$checkFiche )
return false;
}
/* (7) Vérification de la matrice */
foreach($json['matrice'] as $idA=>$Bs){
$checkMatrice = is_numeric($idA);
if( !is_array($Bs) )
return false;
// Pour chaque relation entre le sujet d'id @idA et le sujet d'id $B
foreach($Bs as $B)
$checkMatrice = $checkMatrice && is_numeric($B);
if( !$checkMatrice )
return false;
}
return true;
}
);
/* [2] Renvoi du contenu du fichier
=========================================================*/
/* (1) Si erreur d'upload, on la renvoie */
if( $uploadError != ManagerError::Success )
return array( 'ModuleError' => $uploadError );
/* (2) On récupère le fichier */
$responsePath = self::getPath('local_data', 'json');
// Si erreur, on la renvoie
if( $responsePath['error'] != ManagerError::Success )
return array( 'ModuleError' => $responsePath['error'] );
// On lit le fichier
$json = json_decode( file_get_contents($responsePath['path']), true );
// Si erreur de parsage, on le retourne
if( $json === false )
return ManagerError::ParsingFailed;
/* (3) On renvoie le contenu du fichier */
return array(
'ModuleError' => ManagerError::Success,
'local_data' => $json
);
}
2016-05-24 07:01:16 +00:00
/* CONVERTISSEUR .txt de iExplorer vers .xml de Call Log
*
* @file<FILE> Pointeur vers $_FILES['']
*
*/
public static function iexplorer_convert($params){
extract($params);
/* [1] Gestion de l'upload du fichier et de la vžérification du format
=========================================================*/
$uploadError = self::simpleFile(
'convert_iexplorer',// nom du dossier d'upload
'txt', // format du fichier
$file, // Fichier lui-même
function($content){
$lines = explode("\n", $content);
foreach($lines as $l=>$line)
if( strlen($line) > 0 && !preg_match('/^([\w\(\):\.@-]+(?: {1,3}[\w\(\):\.@-]+)*) +([\w\(\):\.@-]+(?: {1,3}[\w\(\):\.@-]+)*) +([\w\(\):\.@-]+(?: {1,3}[\w\(\):\.@-]+)*) +([\w\(\):\.@-]+(?: {1,3}[\w\(\):\.@-]+)*) *$/u', $line) )
return false;
return true;
}
);
/* (1) Si erreur d'upload, on la renvoie */
if( $uploadError != ManagerError::Success )
return array( 'ModuleError' => $uploadError );
/* [2] On récupère les colonnes avec la premiére ligne
=========================================================*/
/* (1) On met un handler sur le fichier pour le lire */
$path = __ROOT__."/src/upload/convert_iexplorer/".$_SESSION['username'].".txt";
$handler = new \SplFileObject($path, 'r');
/* (2) On récupère pour chaque colonne, la position dans le chaine, et la valeur */
$data = array();
$lineCount = 0;
while( !$handler->eof() ){
$line = $handler->fgets();
/* (1) Si première ligne, c'est les intitulés */
if( $lineCount == 0 ){
// Si erreur dans les intitulés, on retourne une erreur
if( !preg_match('/^([\w\(\):\.@-]+(?: [\w\(\):\.@-]+)*) +([\w\(\):\.@-]+(?: [\w\(\):\.@-]+)*) +([\w\(\):\.@-]+(?: [\w\(\):\.@-]+)*) +([\w\(\):\.@-]+(?: [\w\(\):\.@-]+)*) *$/u', $line, $matches) )
return array( 'ModuleError' => ManagerError::FormatError );
// On récupère les colonnes
$columns = array_slice($matches, 1);
// On récupére les positions des colonnes
$colpos = array();
foreach($columns as $column)
array_push($colpos, strpos($line, $column));
}
/* (2) S'il reconnait pas la ligne, on passe à la suivante */
if( !preg_match('/^([\w\(\):\.@-]+(?: {1,3}[\w\(\):\.@-]+)*) +([\w\(\):\.@-]+(?: {1,3}[\w\(\):\.@-]+)*) +([\w\(\):\.@-]+(?: {1,3}[\w\(\):\.@-]+)*) +([\w\(\):\.@-]+(?: {1,3}[\w\(\):\.@-]+)*) *$/u', $line, $matches) )
continue;
/* (3) On enregistre les données sinon */
$cur = array();
foreach($columns as $c=>$column)
$cur[$column] = $matches[$c+1];
array_push($data, $cur);
$lineCount++;
}
$handler = null;
/* (3) Restitution du retour de `unserialize` */
return array(
'ModuleError' => ManagerError::Success,
'data' => $data
);
}
}
?>