123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807 |
- <?php
- /** IMPORT / IMPORT **/
- //Récuperation d'une liste de import
- Action::register('import_search',function(&$response){
- global $_;
- User::check_access('import','read');
- require_once(__DIR__.SLASH.'Import.class.php');
-
- // OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
- $query = 'SELECT main.* FROM '.Import::tableName().' main WHERE 1';
- $data = array();
- //Recherche simple
- if(!empty($_['filters']['keyword'])){
- $query .= ' AND main.label LIKE ?';
- $data[] = '%'.$_['filters']['keyword'].'%';
- }
- //Recherche avancée
- if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('main.label','main.entity','main.startLine','main.startColumn','main.hasheader','main.file','main.beforeCode','main.afterCode'),$query,$data);
- //Tri des colonnes
- if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.label','main.entity','main.startLine','main.startColumn','main.hasheader','main.file','main.beforeCode','main.afterCode'),$query,$data);
- //Pagination
- //Par défaut pour une recherche, 20 items, pour un export 5000 max
- $itemPerPage = !empty($_['itemPerPage']) ? $_['itemPerPage'] : 20;
- //force le nombre de page max a 50 coté serveur
- $itemPerPage = $itemPerPage>50 ? 50 : $itemPerPage;
- if($_['export'] == 'true') $itemPerPage = 5000;
- $response['pagination'] = Import::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');
- $imports = Import::staticQuery($query,$data,true,0);
-
- $response['rows'] = array();
- foreach($imports as $import){
- $row = $import->toArray();
- $row['entity'] = basename(dirname($row['entity'])).' > '.str_replace('.class.php','',basename($row['entity']));
-
- if($_['export'] == 'true'){
- $row['created'] = date('d-m-Y',$row['created']);
- $row['updated'] = date('d-m-Y',$row['updated']);
- }
-
- $response['rows'][] = $row;
- }
-
- /* Mode export */
- if($_['export'] == 'true'){
- if(empty($response['rows'])) $response['rows'][] = array('Vide'=>'Aucune données');
- $fieldsMapping = array();
- foreach (Import::fields(false) as $key => $value)
- $fieldsMapping[$value['label']] = $key;
- $stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
- File::downloadStream($stream,'export-import-'.date('d-m-Y').'.xlsx');
- exit();
- }
-
- });
-
-
- //Ajout ou modification d'élément import
- Action::register('import_save',function(&$response){
- global $_,$myUser;
- require_once(__DIR__.SLASH.'Import.class.php');
- $item = Import::provide();
- if($myUser->can('import','configure')){
-
-
- $oldItem = clone $item;
- $item->label = $_['label'];
- $item->entity = $_['entity'];
- $item->startLine = $_['startLine'];
- $item->headerLine = $_['headerLine'];
- $item->hasheader = $_['hasheader'];
- if(isset($_['meta'])) $item->meta = json_encode($_['meta']);
- //verification des droits sur le plugin de l'entitée ciblée
- if(!empty($_['entity'])){
- $plugin = dirname($item->entity);
- $plugin = $plugin == 'class' ? 'core':$plugin;
- $plugin = Plugin::parseManifest($plugin.SLASH.'app.json');
- if(!$myUser->can($plugin,'edit')) throw new Exception("Vousz n'avez pas la permission d'edition nécessaire sur le module ".$plugin->name." pour sauvegarder cet import");
- }
- $item->save();
- }
- if($myUser->can('import','read')){
- //Ajout upload Excel
- if(!empty($_['file']))
- File::save_component('file', 'import/'.$item->id.'/{{label}}');
- }
- $response = $item->toArray();
- });
-
-
- //Suppression d'élement import
- Action::register('import_delete',function(&$response){
- global $_;
- User::check_access('import','configure');
- require_once(__DIR__.SLASH.'Import.class.php');
- if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
- Import::remove($_['id']);
- });
-
- //Import : Gestion upload Excel
- Action::register('import_file',function(&$response){
- require_once(__DIR__.SLASH.'Import.class.php');
- $allowedExtensions = array();
- foreach(Import::templates() as $template)
- $allowedExtensions[] = $template->extension;
- File::handle_component(array(
- 'namespace' => 'import', //stockés dans file/import/
- 'access' => 'import',
- 'extension' => implode(',',$allowedExtensions),
- 'limit' => 1,
- 'size' => '1000000000', // taille max
- 'storage' => 'import/{{data.id}}/*.*' //chemin complet vers le fichier stocké
- ),$response);
- });
- Action::register('import_mapping_deduction',function(&$response){
- global $_;
- User::check_access('import','read');
- require_once(__DIR__.SLASH.'ImportMapping.class.php');
- require_once(__ROOT__.SLASH.'plugin/import/Import.class.php');
-
-
- $import = Import::provide();
- $importmappings = ImportMapping::loadAll(array('import'=>$import->id));
- require_once($import->entity);
- $class = str_replace('.class.php','',basename($import->entity));
- $instance = new $class();
- $entityFields = $instance->fields(false);
- $entityLinks = property_exists($instance,'links') ? $instance->links : array();
- $files = glob(File::dir().'import/'.$import->id.'/*.*');
- if(count($files)==0) return;
- $excel = $files[0];
-
- $template = Import::templates(getExt($excel));
- if(!$template) throw new Exception('Cette extension n\'est pas prise en charge par le module import');
- $template->meta = json_decode($import->meta,true);
- $excel = $template->toArray($excel);
- $header = array();
-
- if(count($excel)==0) throw new Exception("L'excel est vide");
-
- //récuperation des en-têtes nominatives (A,B ...)
- $columns = array();
- $maxColumn = 0;
- //calcul du nombre max de colonnes
- foreach($excel as $line){
- $columnCount = count($line);
- $maxColumn = $columnCount>$maxColumn ? $columnCount: $maxColumn;
- }
- for($i=0;$i<$maxColumn+1;$i++){
- $columns[]= array('value'=>import_column_letter($i));
- }
-
- //SI un header existe, on récupere les libellés liés aux entete nominatives (ex: A = "Référence")
- if($import->hasheader){
- $columnsNames = $excel[$import->headerLine-1];
- foreach ($columnsNames as $i => $name) {
- $columns[$i]['label']= $name['value'];
- }
- }
- $dataColumns = isset($excel[$import->startLine]) ? $excel[$import->startLine] : array();
- $response['excelCount'] = count($columns);
- $response['entityCount'] = 0;
-
- foreach($columns as $i=>$cell){
-
- //si la cellule est vide, on continue
- if($template->emptyCell($cell)) continue;
- $importmapping = new ImportMapping();
- $importmapping->import = $import->id;
- $sample = isset($dataColumns[$i]) ? $dataColumns[$i] : array('value'=>'');
- //Déduction du type de valeur en fonction du nom de colonne ou de la valeur
- $deductedType = $template->cellType($cell,$sample);
- $deductedColumn = array();
- //déduction de l'attribut entité en fonction du nom de colonne (si existant)
- if(isset($cell['label'])){
- $cell['label'] = str_replace('<br>',' ',$cell['label']);
- $slugValue = slugify($cell['label']);
- foreach($entityFields as $entityField){
- $levenshtein = levenshtein(slugify($entityField['label']),$slugValue );
- //correspondance parfaite
- if($levenshtein == 0){
- $deductedColumn = $entityField;
- break;
- }
- //correspondance a 2 lettres près
- if( $levenshtein < 2 && strlen($slugValue)> 4 ){
- $deductedColumn = $entityField;
- break;
- }
- //si la colonne excel commence par le nom de la colonne courante
- if(strpos($slugValue,slugify($entityField['label']))===0){
- $deductedColumn = $entityField;
- }
- }
- if(isset($deductedColumn['column'])){
- $importmapping->entityField = $deductedColumn['column'];
- $deductedType = $deductedColumn['fieldtype'];
- if(isset($entityLinks[$importmapping->entityField])){
- $subClassFile = __ROOT__.SLASH.$entityLinks[$importmapping->entityField];
- //par defaut on lie a l'id de la sous classes
- $importmapping->entitySubField = 'id';
- //si un attribut label existe sur la sous classe on utilise celui la
- if(file_exists($subClassFile)){
- require_once($subClassFile);
- $subClass = str_replace('.class.php','',basename($subClassFile));
- if(property_exists($subClass,'label')) $importmapping->entitySubField = 'label';
- }
-
- }
- $response['entityCount']++;
- }
- }
- $importmapping->excelColumn = $cell['value'];
- if(isset($cell['label'])) $importmapping->excelColumnName = $cell['label'];
-
- $macro = Import::macros($deductedType);
- if($macro != false) $importmapping->modifier = $macro['slug'];
-
-
- $importmapping->save();
- }
-
- });
- /** IMPORTMAPPING / LINE D\'IMPORT MAPPéE **/
- //Récuperation d'une liste de line d\'import mappée
- Action::register('import_mapping_search',function(&$response){
- global $_;
- User::check_access('import','read');
- require_once(__DIR__.SLASH.'ImportMapping.class.php');
- require_once(__ROOT__.SLASH.'plugin/import/Import.class.php');
-
-
- $import = Import::provide();
- $importmappings = ImportMapping::loadAll(array('import'=>$import->id),array('id'));
- require_once($import->entity);
- $class = str_replace('.class.php','',basename($import->entity));
- $instance = new $class();
- $entityFields = $instance->fields(false);
- $response['rows'] = array();
- $fieldTypes = FieldType::available();
- foreach($importmappings as $importmapping){
- $row = $importmapping->toArray();
- if( isset($entityFields[$row['entityField']]) ){
- $field = $entityFields[$row['entityField']];
- $row['entityField'] = $field['column'];
- $row['entityFieldType'] = isset($fieldTypes[$field['fieldtype']]) ? $fieldTypes[$field['fieldtype']] : '';
- }
-
- $response['rows'][] = $row;
- }
-
- });
-
- Action::register('import_execute',function(&$response){
- global $_,$myUser;
- User::check_access('import','read');
- require_once(__DIR__.SLASH.'Import.class.php');
- require_once(__DIR__.SLASH.'ImportMapping.class.php');
- $import = Import::provide();
- if(empty($import->id)) throw new Exception('Id import manquant');
- //verification des droits sur le plugin de l'entitée ciblée
- $plugin = dirname($import->entity);
- $plugin = $plugin == 'class' ? 'core':$plugin;
- $plugin = Plugin::parseManifest($plugin.SLASH.'app.json');
-
- if(!$myUser->can($plugin->folder,'edit')){
-
- throw new Exception("Vous n'avez pas la permission d'edition nécessaire sur le module ".$plugin->name." ('".$plugin->folder."') pour utiliser cet import");
- }
- $mapping = array();
- $fixedValues = array();
- //contient les colonnes qui doivent rester uniques et leurs valeurs
- $uniqueColumns = array();
- foreach(ImportMapping::loadAll(array('import'=>$import->id)) as $importmapping){
- $mapping[$importmapping->excelColumn] = $importmapping;
- if(!empty($importmapping->unique)) $uniqueColumns[$importmapping->entityField] = array();
- //remplissage d'un tableau des valeurs fixes (non présentes dans l'excel)
- if(!empty($importmapping->excelColumnFixedValue) ) $fixedValues[$importmapping->entityField] = $importmapping->excelColumnFixedValue;
- }
-
- require_once($import->entity);
- $class = str_replace('.class.php','',basename($import->entity));
- $instance = new $class();
- $entityFields = $instance->fields(false);
- $entityLinks = $instance->links;
- $files = glob(File::dir().'import/'.$_['id'].'/*.*');
- if(count($files)==0) throw new Exception('Excel inexistant');
- $excelPath = $files[0];
- $response['fileName'] = basename($excelPath);
- $template = Import::templates(getExt($excelPath));
- if(!$template) throw new Exception('Extension de fichier non prise en charge');
- $template->meta = json_decode($import->meta,true);
- $excel = $template->toArray($excelPath);
-
- $headers = array();
- //récuperation des en-têtes (si non existantes on genere des en-êtes A,B ...)
-
- $response['columns'] = array();
- $maxColumn = 0;
- //calcul du nombre max de colonnes
- foreach($excel as $line){
- $columnCount = count($line);
- $maxColumn = $columnCount>$maxColumn ? $columnCount: $maxColumn;
- }
- for($i=0;$i!=$maxColumn;$i++){
- $letter = import_column_letter($i);
- $headers[]= array('value'=>$letter);
- $response['columns'][] = $letter;
- }
-
-
- $entityLabel = $class;
- if(property_exists($instance,'entityLabel') && !empty($instance->entityLabel)) $entityLabel = $instance->entityLabel;
- $context = array(
- 'excel' => $excel,
- 'import' => $import,
- 'columns' => $response['columns'],
- 'plugin' => basename(dirname($import->entity)),
- 'entity' => $class,
- 'entityLabel' => $entityLabel,
- 'headers' => $headers
- );
-
- $linkCache = array();
- $excelCount = count($excel);
- History::put('import',$import->id,'lancement de l\'import ('.$excelCount.' lignes)',History::TYPE_EDIT);
-
- $response['stats'] = array(
- 'total' => array('label'=>'Total','slug'=>'total','value'=>$excelCount),
- 'imported' => array('label'=>'Importé','slug'=>'imported','value'=>0),
- 'error' => array('label'=>'Erreur','slug'=>'error','value'=>0)
- );
- foreach(ImportMapping::uniqueness() as $slug=>$unique){
- if(empty($slug)) continue;
- $response['stats'][$slug] = array('label'=>$unique['label'],'slug'=>$slug,'value'=>0);
- }
-
- if(!empty($uniqueColumns)){
- foreach($class::loadAll() as $item){
- foreach($uniqueColumns as $attribute=>$values){
- if(!empty($item->$attribute)) $uniqueColumns[$attribute][] = $item->$attribute;
- }
- }
- }
-
- //tableau de cache des classes tierces des relations n-n
- $subRelatedCache = array();
- foreach($excel as $i => $line){
- if($i<$import->startLine -1){
- $response['stats']['total']['value']--;
- continue;
- }
- $relatedInstances = array();
- $lineNumber = $i+($import->hasheader?2:1) -1;
-
- $context['lineNumber'] = $lineNumber;
- $context['i'] = $i;
- $context['line'] = $line;
- $instance = new $class();
-
- if($template->emptyLine($line)){
- $response['stats']['total']['value']--;
- continue;
- }
- foreach($line as $u=>$cell){
-
-
- $columnName = isset($headers[$u])? $headers[$u]['value'] : $u;
- $context['columnNumber'] = $u;
- $context['columnName'] = $columnName;
- try{
- if($template->emptyCell($cell)) continue;
- if(!isset($mapping[$columnName])) continue;
-
- $importmapping = $mapping[$columnName];
- if(empty($importmapping->entityField))continue;
-
- $entityField = isset($entityFields[$importmapping->entityField]) ? $entityFields[$importmapping->entityField] : null;
- $context['entityField'] = $entityField;
- if(!empty($importmapping->modifier)){
- $macro = Import::macros($importmapping->modifier);
- $mutator = $macro['mutator'];
- $cell['value'] = $mutator($cell['value'],$context);
- }
- $attribute = $importmapping->entityField;
-
- //Si le champ est lié a une autre entité en n-1 (un champs de l'entité courante point vers l'id d'une autre entité)
- if(isset($entityLinks[$importmapping->entityField]) && basename($entityLinks[$importmapping->entityField])!='Dictionary.class.php'){
-
- $file = $entityLinks[$importmapping->entityField];
- require_once(__ROOT__.SLASH.$file);
- $subClass = str_replace('.class.php','',basename($file));
- if(!isset($linkCache[$file])) $linkCache[$file] = array();
- if(!isset($linkCache[$file][$cell['value']])){
- //on recherche l'entrée ciblé en base ayant le libellé de la valeur excel
- $subInstance = $subClass::load(array($importmapping->entitySubField=>$cell['value']));
- if(is_object($subInstance) && $subInstance->id!=0) $linkCache[$file][$cell['value']] = $subInstance->id;
-
- }
- //on remplace la valeur par l'id de l'objet trouvé
- if( isset($linkCache[$file][$cell['value']]) && is_numeric($linkCache[$file][$cell['value']])) $cell['value'] = $linkCache[$file][$cell['value']];
- }
- //Si le champ est lié a une autre entité
- if(!empty($importmapping->entityRelatedField)){
- //On récupere le chemin de la classe de l'autre entité
- $relatedFile = $importmapping->entityRelated;
- //on vérifie que le fichier de classe existe
- if(file_exists($relatedFile)){
- //on inclus le fichier de classe
- require_once($relatedFile);
- //on récupere le nom de la classe
- $relatedClass = str_replace('.class.php','',basename($relatedFile));
- //on l'instancie
- $relatedManager = new $relatedClass();
- //on récupere les champs de la classe en questions
- $relatedManagerFields = $relatedManager->fields(false);
- //Pour chaques champs
- foreach($relatedManagerFields as $relatedInstanceField){
- //Si une classe tierce est liée (attribut 'link') est qu'elle a le même nom que la classe
- //principale qui est importée on la stock en tant que colonne de relation
- if(isset($relatedInstanceField['link']) && basename($relatedInstanceField['link']) == basename($import->entity) ){
- $relationColumn = $relatedInstanceField['column'];
- }
- }
- $attribute = $importmapping->entityRelatedField;
- $attributePath = explode('.',$attribute);
- //si le champ est en relation 1-n (une autre entité point vers l'id de l'entitée courante)
- if(count($attributePath)==1){
- $relatedInstance = isset($relatedInstances[$relationColumn]) ? $relatedInstances[$relationColumn] : array('instance'=> new $relatedClass(),'childs'=>array());
- $relatedInstance['instance']->$attribute = $cell['value'];
- if(isset($relationColumn)) $relatedInstances[$relationColumn] = $relatedInstance;
- continue;
- }else if(count($attributePath)>1){
- //relations n-n (une autre entité pointe vers l'id de l'entitée courante elle même pointée par une troisieme entitée)
- // pour le moment ne gère pas en recursive, un seul niveau de n-n pris en charge
- /*
- $relatedInstance = isset($relatedInstances['tender']) ? $relatedInstances['tender'] : array('instance'=> new Assigment(),'childs'=>array());
- */
- $relatedInstance = isset($relatedInstances[$relationColumn]) ? $relatedInstances[$relationColumn] : array('instance'=> new $relatedClass(),'childs'=>array());
-
- //$relatedManagerField = $relatedManagerFields['assignee'];
- $relatedManagerField = $relatedManagerFields[$attributePath[0]];
- //requie_once(__ROOT__.SLASH.'/plugin/publictender/Assignee.class.php')
- require_once(__ROOT__.SLASH.$relatedManagerField['link']);
- //$childClass = Assignee;
- $childClass = str_replace('.class.php','',basename($relatedManagerField['link']));
- if(isset($relatedInstance['childs'][$attributePath[0]]['instance'])){
- $childInstance = $relatedInstance['childs'][$attributePath[0]]['instance'];
- }else{
- $childInstance = new $childClass();
- }
-
- $property = $attributePath[1];
- $childInstance->$property = $cell['value'];
- $relatedInstance['childs'][$attributePath[0]] = array('instance'=>$childInstance);
-
- if(isset($relationColumn)) $relatedInstances[$relationColumn] = $relatedInstance;
- continue;
- }else{
- continue;
- }
-
- }
- }
- //Vérification de l'unicité si activée
- if(!empty($importmapping->unique)){
- $uniqueExistingValues = $uniqueColumns[$importmapping->entityField];
- //Si la valeur existe déja
- if(in_array($cell['value'],$uniqueExistingValues)){
- switch($importmapping->unique){
- //si on a configuré le skip, on ignore la nouvelle ligne importée
- case ImportMapping::UNIQUE_SKIP:
- import_report_line($response,$context,ImportMapping::UNIQUE_SKIP,'Ignoré','Ligne non unique, ligne d\'import ignorée');
- $response['stats'][ImportMapping::UNIQUE_SKIP]['value']++;
- //on utilise 3 car le switch est lui même considéré comme une boucle par php
- continue 3;
- break;
- //si on a configuré le erase, on supprime la ligne existante en base
- case ImportMapping::UNIQUE_ERASE:
- $class::delete(array($importmapping->entityField => $cell['value']));
- import_report_line($response,$context,ImportMapping::UNIQUE_ERASE,'Écrasé','Ligne non unique, correspondance en base ecrasée');
- $response['stats'][ImportMapping::UNIQUE_ERASE]['value']++;
- break;
- }
- }
- //on ajoute la nouvelle valeur unique dans le tableau de gestion des unicités
- $uniqueColumns[$importmapping->entityField][] = $cell['value'];
- }
- $instance->$attribute = $cell['value'];
- }catch(Exception $e){
- import_report_line($response,$context,'error','Erreur',$e->getMessage().' L'.$e->getLine());
- $response['stats']['error']['value']++;
- History::put('import',$import->id,'L'.$lineNumber.' colonne '.($context['columnNumber']+1).' : '.$e->getMessage().' ('.$e->getLine().')','error');
- continue;
- }
- }
- //remplissage des valeurs fixes pour l'objet
- foreach($fixedValues as $enfityField=>$value){
- $instance->$enfityField = $value;
- }
- $response['stats']['imported']['value']++;
- $instance->save();
-
-
- foreach($relatedInstances as $property=>$relatedInstance){
-
- //n-n
- if(!empty($relatedInstance['childs'])){
- foreach($relatedInstance['childs'] as $subProperty => $subRelatedInstance){
-
- //On verifie si l'entité tierce est existante en base
- $filters = array();
- $subRelatedClass = get_class($subRelatedInstance['instance']);
-
- foreach($subRelatedInstance['instance']->fields() as $field){
- if(in_array($field,array('created','id','updated','updater','creator'))) continue;
- $filters[$field] = $subRelatedInstance['instance']->$field;
- }
- $filterChain = sha1(json_encode($filters));
- if(isset($subRelatedCache[$filterChain])){
- $existing = $subRelatedCache[$filterChain];
- }else{
- $existing = $subRelatedClass::load($filters);
- if($existing != false) $subRelatedCache[$filterChain] = $existing;
- }
-
- //si l'entité tierce n'est pas existante, on la créé
- if(!$existing){
- $subRelatedInstance['instance']->save();
- //si l'entité tierce existe, on la prend comme référence
- }else{
- $subRelatedInstance['instance'] = $existing;
- }
- $subRelatedCache[$filterChain] = $subRelatedInstance['instance'];
- $relatedInstance['instance']->$subProperty = $subRelatedInstance['instance']->id;
- $relatedInstance['instance']->$property = $instance->id;
- $relatedInstance['instance']->save();
- }
- //1-n
- }else{
- $relatedInstance['instance']->$property = $instance->id;
- $relatedInstance['instance']->save();
- }
- }
- }
- if(file_exists($excelPath)) unlink($excelPath);
- History::put('import',$import->id,'Fin de l\'import, '.$response['stats']['imported']['value'].'/'.$response['stats']['total']['value'].' importés',History::TYPE_EDIT);
-
- });
- //Ajout ou modification d'élément line d\'import mappée
- Action::register('import_template_setting',function(&$response){
- global $_;
- User::check_access('import','configure');
- require_once(__DIR__.SLASH.'Import.class.php');
- require_once(__DIR__.SLASH.'ImportMapping.class.php');
- $import = Import::provide('import');
- $files = glob(File::dir().'import/'.$import->id.'/*.*');
- if(count($files)==0) return $response['form'] = '';
- $excel = $files[0];
- $template = Import::templates(getExt($excel));
- $meta = json_decode($import->meta,true);
- $template->meta = $meta;
- $excel = $template->toArray($excel);
- $response['headers'] = array();
- $maxColumn = 0;
- //calcul du nombre max de colonnes
- foreach($excel as $line){
- $columnCount = count($line);
- $maxColumn = $columnCount>$maxColumn ? $columnCount: $maxColumn;
- }
- for($i=0;$i!=$maxColumn;$i++){
- $letter = import_column_letter($i);
- $response['headers'][$letter]= array('value'=>$letter);
- }
-
- $response['form'] = '';
- foreach($template->settings() as $slug=>$field){
-
- $field['id'] = $slug;
- if(isset($meta[$field['id']])) $field['value'] = $meta[$field['id']];
- $field['attributes']['onchange'] = '"import_save()"';
- $field = FieldType::toHtml($field,null,array('allowCustomLabel'=>true));
- $response['form'] .= $field['label'].' '.(!empty($field['legend'])?'<small class="text-muted">'.$field['legend'].'</small>':'').' '.$field['input'];
- }
- });
-
- //Ajout ou modification d'élément line d\'import mappée
- Action::register('import_mapping_save',function(&$response){
- global $_;
- User::check_access('import','configure');
- require_once(__DIR__.SLASH.'Import.class.php');
- require_once(__DIR__.SLASH.'ImportMapping.class.php');
- $item = ImportMapping::provide();
- $item->excelColumn = isset($_['excelColumn']) ? $_['excelColumn'] : 'Sans titre';
- $item->excelColumnFixedValue = isset($_['excelColumnFixedValue']) ? $_['excelColumnFixedValue'] : '';
- $item->modifier = isset($_['modifier']) ? $_['modifier']: '';
- $item->entityField = isset($_['entityField']) ? $_['entityField']: '';
- $item->entitySubField = isset($_['entitySubField']) ? $_['entitySubField']: '';
- $item->entityRelated = isset($_['entityRelated']) ? $_['entityRelated']: '';
- $item->entityRelatedField = isset($_['entityRelatedField']) ? $_['entityRelatedField']: '';
- $item->unique = isset($_['unique']) ? $_['unique']: '';
- $item->import = $_['import'];
- $item->save();
- $response = $item->toArray();
- });
- //Récuperation ou edition d'élément line d\'import mappée
- Action::register('import_mapping_edit',function(&$response){
- global $_;
- User::check_access('import','configure');
- require_once(__DIR__.SLASH.'ImportMapping.class.php');
- $response = ImportMapping::getById($_['id'])->toArray();
- if(!isset($response['modifier'])) $response['modifier'] = '';
- });
- //Suppression d'élement line d\'import mappée
- Action::register('import_mapping_delete',function(&$response){
- global $_;
- User::check_access('import','configure');
- require_once(__DIR__.SLASH.'ImportMapping.class.php');
- if(empty($_['id'])) throw new Exception("Identifiant incorrect");
-
- if($_['id'] == 'all'){
- ImportMapping::delete(array('import'=>$_['import']));
- }else{
- ImportMapping::deleteById($_['id']);
- }
-
-
- });
- /* COMPOSANT*/
- //recherche autocomplete
- Action::register('import_autocomplete',function(&$response){
- global $myUser,$_;
- require_once(__DIR__.SLASH.'Import.class.php');
- if (!$myUser->connected()) throw new Exception("Vous devez être connecté", 401);
- $response['rows'] = array();
- $data = array("%".$_['keyword']."%");
- //retourne en priorité les matchs à 100%, pour les match keyword%, puis les autres
- $query = 'SELECT c.* FROM '.Import::tableName().' c WHERE (c.label LIKE ?) ';
- $query .= ' LIMIT 10';
-
- $devices = Import::staticQuery($query,$data,true);
- foreach($devices as $item){
- $response['rows'][] = array(
- 'label'=>html_entity_decode($item->label, ENT_QUOTES),
- 'id'=>$item->id,
- );
- }
- });
-
- //Récuperation valeur composant depuis l'uid
- Action::register('import_by_uid',function(&$response){
- global $myUser,$_;
- if (!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
- require_once(__DIR__.SLASH.'Import.class.php');
-
- $response['items'] = array();
-
- $query = 'SELECT main.* FROM '.Import::tableName().' main WHERE main.id IN(';
- $query .= implode(',', array_fill(0, count($_['items']), '?'));
- $query .= ')';
-
- foreach(Import::staticQuery($query,$_['items'],true) as $item) {
- $row = $item->toArray();
- $row['label'] = html_entity_decode($row['label'], ENT_QUOTES);
- $response['items'][$row['id']] = $row;
- }
-
- });
-
- //Sauvegarde des configurations de Import
- Action::register('import_setting_save',function(&$response){
- global $_,$conf;
- User::check_access('import','configure');
- //Si input file "multiple", possibilité de normaliser le
- //tableau $_FILES récupéré avec la fonction => normalize_php_files();
- foreach(Configuration::setting('import') as $key=>$value){
- if(!is_array($value)) continue;
- $allowed[] = $key;
- }
- foreach ($_['fields'] as $key => $value) {
- if(in_array($key, $allowed))
- $conf->put($key,$value);
- }
- });
-
-
-
- ?>
|