class.tx_nG6_utils.php 16.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2009 PF bioinformatique de Toulouse <>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * Plugin 'nG6' for the 'nG6' extension.
 *
 * @author	PF bioinformatique de Toulouse <>
 */

30
//require_once(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('saltedpasswords').'/classes/salts/class.tx_saltedpasswords_salts_factory.php');
31
32
33

class tx_nG6_utils {

Jerome Mariette's avatar
Jerome Mariette committed
34
35
36
37
38
39
40
	/**
	 * Describe all links between analyzes (and their ancestor) and build a tree. The main Array is the root.  
	 * Example of result : Array( [a] => Array( ["data"] => Array(), ["child"] => Array( ... ) ) )
	 * 
	 * @param Array $analyzes_map analyze array (for example, result of tx_nG6_db::get_project_analysis(...))
	 * @return a tree describing the links children-parents of all analyzes
	 */
41
	static function trace_hierarchy($analyzes_map) {
Jerome Mariette's avatar
Jerome Mariette committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

		$base_tree = array();
		foreach(array_values($analyzes_map) as $id => $analyze) {
			$base_tree[$analyze['id']] = $analyze['parent_id'];
			//$tree_analyze[$analyze['id']] = $analyze;
			$tree_analyze[$analyze['id']] = array("data" => $analyze, "child" => array()); 
		}
		
		// Create relationships
		$h_analysis = array();
		foreach($tree_analyze as $analyze_id => $analyze_infos) {
			if ($analyze_infos["data"]["parent_id"] == 0) {
				$h_analysis[$analyze_id] = &$tree_analyze[$analyze_id];
			} else {
				$tree_analyze[$analyze_infos["data"]["parent_id"]]["child"][$analyze_id] = &$tree_analyze[$analyze_id]; 
			}
		}
		
		return $h_analysis;
	}

63
64
65
66
67
68
69
    /**
    * Test if the substring ends the string
    * 
    * @param $str : the string to test
    * @param $sub : the substring that may ends $str
    * @return boolean
    */ 
70
	static function ends_with($str, $sub) {
71
72
73
74
75
76
77
78
79
		return ( substr( $str, strlen( $str ) - strlen( $sub ) ) == $sub );
	} 

    /**
    * Returns a string generated randomly
    * 
    * @param $size : the random key size
    * @return string
    */ 
80
   	static function create_random_key($size) {
81
82
83
84
85
86
87
		$keyset = "abcdefghijklmABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   		$randkey = "";
   		for ($i=0; $i<$size; $i++)
	   		$randkey .= substr($keyset, rand(0, strlen($keyset)-1), 1);
   		return $randkey;
   	}

88
89
90
91
92
93
94
95
	/**
	 * Delete directories
	 * 
	 * @param 	string 	$user_login		
	 * @param 	string 	$user_pwd		
	 * @param 	string 	$directory		
	 * @return	0=>everything ok, 1=>user right problem, 2=>wrong authentification, 3=>connection error
	 */
96
    static function delete_directory($user_login, $user_pwd, $directory) {
97
98
99
100
101
102
103
		// First try to connect the specified user using ssh
		$connection = ssh2_connect('127.0.0.1', 22);
		if (!$connection) return 3;
		if (!ssh2_auth_password($connection, $user_login, $user_pwd)) return 2;		

		if ($directory != 'undefined' && $directory != '') {
			// And process the directories structure
Celine Noirot's avatar
Celine Noirot committed
104
            //TODO BUG NE RETOURNE PAS D'ERREUR si pas supprimer
Gerald Salin's avatar
#21    
Gerald Salin committed
105
106
107
108
109
110
111
112
113
114
115
116
	   		$stream = ssh2_exec($connection, 'rm -rf '.$directory."/");
			$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
			// Enable blocking for both streams
			stream_set_blocking($errorStream, true);
			stream_set_blocking($stream, true);
				
			// Whichever of the two below commands is listed first will receive its appropriate output.  The second command receives nothing
			
			if(stream_get_contents($errorStream)) {
				// Close the streams
				fclose($errorStream);
				fclose($stream);
117
				return 1;
Gerald Salin's avatar
#21    
Gerald Salin committed
118
119
120
121
122
			}else{
				// Close the streams
				fclose($errorStream);
				fclose($stream);
				return 0;
123
124
125
126
127
			}
		}
		return 0;
    }

128
129
130
131
132
133
134
135
    /**
	 * Purge directories
	 * 
	 * @param 	string 	$user_login		
	 * @param 	string 	$user_pwd		
	 * @param 	string 	$directory		
	 * @return	0=>everything ok, 1=>user right problem, 2=>wrong authentification, 3=>connection error
	 */
136
    
137
    static function purge_directory($user_login, $user_pwd, $directory) {
138
        if ($directory != 'undefined' && $directory != '') {
Celine Noirot's avatar
Celine Noirot committed
139
    		// And process the directories structure, remove all files except .html ans .png
140
     		$connection = ssh2_connect('127.0.0.1', 22);
141
142
    		if (!$connection) {
    			return 3;
Gerald Salin's avatar
#21    
Gerald Salin committed
143
144
145
146
147
    		}
    			
    		if (!ssh2_auth_password($connection, $user_login,$user_pwd )){
    			return 2;
    		}
148
    		$stream = ssh2_exec($connection, 'ls -d '.$directory.'/' );
149
150
151
152
153
154
155
156
157
158
159
160
161
    		$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
    		// Enable blocking for both streams
    		stream_set_blocking($errorStream, true);
    		stream_set_blocking($stream, true);
    			
    		//if error is raised, $directory does not exist>no problem (in case of an analysis which do not have associated files 
    		
    		if(stream_get_contents($errorStream)) {
    			// Close the streams
    			fclose($errorStream);
    			fclose($stream);
    			return 0;
    		}
Gerald Salin's avatar
#21    
Gerald Salin committed
162
    		
163
    		#Exclusion of the log files from the purge process
164
    		$stream = ssh2_exec($connection, 'find '.$directory.' -maxdepth 1 -not -name "*.html" -not -name "*.png" -not -name "*.log" -not -name "*.log.gz" -not -name "*.pdf" -not -name "md5sum.txt" -not -name "*GXB02039*" -not -name "*PCT0078*" -type f -exec rm -f {} \;');
Gerald Salin's avatar
#21    
Gerald Salin committed
165
166
167
168
    		$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
    		// Enable blocking for both streams
    		stream_set_blocking($errorStream, true);
    		stream_set_blocking($stream, true);
Celine Noirot's avatar
Celine Noirot committed
169
    				 
170
    		//if error is raised, connected user does not have the right to delete the files
Gerald Salin's avatar
#21    
Gerald Salin committed
171
172
173
174
175
176
177
178
179
180
    		if(stream_get_contents($errorStream)) {
    			// Close the streams
    			fclose($errorStream);
    			fclose($stream);
    			return 1;
    		}else{
    			// Close the streams
    			fclose($errorStream);
    			fclose($stream);
    			return 0;
181
182
    		}
    	}
183
    }
184

185
    
186
187
188
189
190
	/**
	 * Return the string representation of a byte
	 * 
	 * @param 	string 	$size		
	 */
191
    static function get_octet_string_representation($size) {
192
		$octets_link = array("Bytes", "kB", "MB", "GB", "TB", "PB", "EB", "ZB");
193
194
195
196
197
198
199
200
201
		$p = (int)(ceil((float)(strlen(strval($size)))/(float)(3) - (float)(1)));
		$pow_needed = $p * 10;
	    $pow_needed = pow(2, $pow_needed);
	    $value = (float)($size)/(float)($pow_needed);
	    $tmp = explode(".", $value);
	   	$value = $tmp[0].".".substr($tmp[1], 0, 2);
	    $value = $value." ".$octets_link[$p];
	    return $value;
    }
202
    
203
    static function get_purge_mail($project_name, $project_id, $nb_run_purgeable,$nb_analyse_purgeable, $demand_id, 
204
        $purgeable_size, $project_size, $purge_delay, $url_price, $min_extention_duration, 
Romain Therville's avatar
Romain Therville committed
205
        $min_extention_size, $emails, $runs_list, $analyse_list, $with_extension) {
206
    
Romain Therville's avatar
Romain Therville committed
207
    	$template_mail='
208
209
210
211
    			<html>
      <head>
       <title>Data Purge on nG6</title>
      </head>
212
      <body>
213
214
<p>Dear user,</p>

Romain Therville's avatar
Romain Therville committed
215
<p>The data storage period of part or whole ###PROJECT_NAME### project (###nb_run### run(s) and ###nb_analyse### analyse(s)) is ended.</p>
216
217
218

<p>This purge alert No ###DEMAND_ID### corresponds to ###SIZE_STR### see list of impacted files below.</p>

Romain Therville's avatar
Romain Therville committed
219
<p>In ###PURGE_DELAY### days, your data will be deleted.</p>';
220

Romain Therville's avatar
Romain Therville committed
221
222
223
224
225
226
227
228
229
		if($with_extension){
			$template_mail .= '<p>Keep us informed if you wish to extend the storage period, 
			please have a look at our storage fees (<a href="###URL_PRICE###">###URL_PRICE###</a>) and reply to this email with the following information:</p>
			<p>----------------------------------------------</p>
			<ul><li>Demand number:  ###DEMAND_ID###</li>
			<li>Request for extension term:  XXX (minimal unit: ###EXTENSION_DURATION###)</li>
			<li>Request for extension size: XXX (mininal unit: ###EXTENSION_SIZE###)</li>
			<li>Laboratory name/Institution: </li></ul>
			<p>----------------------------------------------</p>
230

Romain Therville's avatar
Romain Therville committed
231
232
233
234
			<p>###EMAILS###We would appreciate if you could group your demands by laboratory.</p>';
		}else{
			$template_mail .= '<p>###EMAILS###</p>';
		}
235
236
237
		
$template_mail.='The nG6 purge process is undergoing an important overhaul.</br>
You can visit our FAQ at the following address : https://ng6.toulouse.inra.fr/index.php?id=57 .</br>
238
If you have any question or demand, do not hesitate to contact our support team at ng6-support@groupes.renater.fr.</br>';
239

Romain Therville's avatar
Romain Therville committed
240
$template_mail.='<p>Yours sincerely</p>
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
<p>nG6 team (for GeT-Genotoul and Bioinfo-Genotoul facilities)</p>

<p>Files impacted of:</p>
<ul>
<li>Runs : 	###RUNS_LIST###
<li>Analyzes :	###ANALYSES_LIST###</li>
</ul>
    			</body>
    			</html>
';
        
        $size_str = $purgeable_size . " purgeable data on ". $project_size ." of whole project";
        if ($purgeable_size == $project_size) {
            $size_str = "whole project (".$purgeable_size . ")";
        }
        $search=array("###nb_run###","###nb_analyse###","###PROJECT_NAME###","###PROJET_ID###","###DEMAND_ID###",
                                                "###EMAILS###","###RUNS_LIST###","###ANALYSES_LIST###","###SIZE_STR###", 
                                                "###EXTENSION_DURATION###","###EXTENSION_SIZE###","###URL_PRICE###","###PURGE_DELAY###");
                                             
        $replace=array($nb_run_purgeable,$nb_analyse_purgeable,$project_name,$project_id, $demand_id ,
                                                 $emails, $runs_list,  $analyse_list, $size_str,
                                                 $min_extention_duration, $min_extention_size, $url_price, $purge_delay);
                                                 
        $mail=str_replace($search, $replace, $template_mail);
        
        return $mail;
    }
    
269
270
271
272
273
	/**
	 * hash password (using default encryption method)
	 * @param string $password
	 * @return hashed password
	 */    
274
    static function hash_password($password){
Gerald Salin's avatar
Gerald Salin committed
275
276
277
278
279
280
281
    if (\TYPO3\CMS\Saltedpasswords\Utility\SaltedPasswordsUtility::isUsageEnabled('FE')) {
            $objSalt = \TYPO3\CMS\Saltedpasswords\Salt\SaltFactory::getSaltingInstance(NULL);
            if (is_object($objSalt)) {
                    $saltedPassword = $objSalt->getHashedPassword($password);
            }
    }
			return $saltedPassword;
282
    }
283
    
284
    static function get_ssh_connection($user_login, $user_pwd){
Celine Noirot's avatar
Celine Noirot committed
285
286
287
288
289
290
291
        $connection = ssh2_connect('127.0.0.1', 22);
		if (!$connection) return NULL;
		
        if (!ssh2_auth_password($connection, $user_login, $user_pwd)) return NULL;		
        
        return $connection ;
    }
292
293
294
295
296
297
298
299
    
    static function get_config_content(){
    	$config_file_path = __DIR__."/../../../application.properties";
    	$config_file_content = file_get_contents($config_file_path);
    	
    	return($config_file_content);
    }
    
300
    //Return a php array containing the section relative to the given space_id
301
    static function get_retention_policy_from_space_id($space_id = "default"){
Romain Therville's avatar
Romain Therville committed
302
    	$config_file_content = tx_nG6_utils::get_config_content();
303
		
304
305
    	//To explode the file content by line, we use PHP_EOL
    	$array_config_content = explode(PHP_EOL, $config_file_content);
306
		
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
    	$space_id_retention_config = array();
    	$pattern_to_find = "[space_".$space_id."]";
    	$is_space_id_found = FALSE;
    	
    	//We want to return the space id config as an array
    	foreach($array_config_content as $line_id => $line_content){
    		//if we found the right section
    		if($line_content == $pattern_to_find){
    			$is_space_id_found = TRUE;
    		}
    		
    		//If we enter a new section, we stop the line copying
    		if($is_space_id_found && $line_content != $pattern_to_find && strpos($line_content,'[')===0 ){
    			$is_space_id_found = FALSE;
    		}
    		
    		if($is_space_id_found){
    			$space_id_retention_config[] = $line_content;
    		}
    	}
    	return($space_id_retention_config);
    }
    
    static function get_project_retention_policy( $project_id ){

    	$space_id = tx_nG6_db::get_project_space_id($project_id);
    	$retention_policy = tx_nG6_utils::get_retention_policy_from_space_id($space_id);
    	
    	$retention_line = "";
    	$policy = "";
    	$retention_value = "";
    	$return_text = "";
    	
    	foreach($retention_policy as $line => $line_content){
    		if( strpos($line_content,"retention") === 0 ){
    			$retention_line = $line_content;
    		}
    	}
    	
    	if( is_numeric(strpos($retention_line,"date"))){
    		$policy = "date";
    	}elseif( is_numeric(strpos($retention_line,"period"))){
    		$policy = "period";
    	}
    	
    	$split_retention_line = explode('=',$retention_line);
    	$retention_value = $split_retention_line[1];
    	
    	if($policy == "date"){
Romain Therville's avatar
Romain Therville committed
356
357
    		$date = date_create_from_format("d/m/Y", $retention_value);
    		$nice_date = date_format($date, 'l jS \of F Y');
358
359
360
361
362
363
364
365
366
    		
    		$return_text = " until ".$nice_date;
    	}elseif($policy == "period"){
    		$return_text = " for ".$retention_value." months";
    	}
    	
    	return($return_text);
    }
    
Romain Therville's avatar
Romain Therville committed
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
    //Return a php array with array[space_name]=space_name, containing all available space_ids
    static function get_available_space_ids (){
    	$config_file_content = tx_nG6_utils::get_config_content();
		
    	//To explode the file content by line, we use PHP_EOL
    	$array_config_content = explode(PHP_EOL, $config_file_content);
		
    	$ret = array();
    	
    	foreach($array_config_content as $line => $line_content){
    		//If the current line starts with "[space_"
    		if( strpos($line_content,'[space_') === 0 ){
    			$space_id = str_replace('[space_','',$line_content);
    			$space_id = str_replace(']','',$space_id);
    			$space_id = trim($space_id);
    			
    			$ret[$space_id]=$space_id;
    		}
    	}
    	
    	return($ret);
Romain Therville's avatar
Romain Therville committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
	}

	static function get_project_data_save_dir($project_id){
    	$space_id = tx_nG6_db::get_project_space_id($project_id);
    	$space_config = tx_nG6_utils::get_retention_policy_from_space_id($space_id);
    	$path_to_space_save_dir = '';
    	
    	foreach($space_config as $line_id => $line_content){
    		if(strpos($line_content, 'dir_name') === 0){
    			//We get the value in the "dir_name = " line
    			$space_save_dir = trim( substr( $line_content, strpos( $line_content, '=')+1 ) );
    		}
    		
    	}
    	
    	$save_dir = tx_nG6_utils::get_save_dir();
    	$path_to_space_save_dir = $save_dir.'/'.$space_save_dir;
    	
    	return($path_to_space_save_dir);
    }
    
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
    static function get_project_purge_msg($project_id){
    	$space_id = tx_nG6_db::get_project_space_id($project_id);
    	$space_config = tx_nG6_utils::get_retention_policy_from_space_id($space_id);
    	$project_purge_msg = '';
    	
    	foreach($space_config as $line_id => $line_content){
    		if(strpos($line_content, 'purge_msg') === 0){
    			//We get the value in the "purge_msg = " line
    			$project_purge_msg = trim( substr( $line_content, strpos( $line_content, '=')+1 ) );
    		}
    		
    	}
    	
    	return($project_purge_msg);
    }
Romain Therville's avatar
Romain Therville committed
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
    
    static function get_save_dir(){
    	$config_file_content = tx_nG6_utils::get_config_content($space_id);
    	$pattern_to_find = 'save_directory';
    	$array_config_content = explode(PHP_EOL, $config_file_content);
    	$path_to_save_dir='';
    	
    	foreach($array_config_content as $line_id => $line_content){
    		//if we found the right section
    		if( strpos($line_content,$pattern_to_find)===0 && ! $is_pattern_found){
    			//We copy the line from the first '/'
    			$path_to_save_dir = substr($line_content, strpos( $line_content, '/'))   ; 			
    			
    		}
    		
    	}
    	return($path_to_save_dir);
Romain Therville's avatar
Romain Therville committed
441
442
    }
    
443
444
445
446
447
448
449
    static function convert_epoch_timestamp_to_nice_date( $epoch_date ){
		//return(gmdate('D, d M Y', $epoch_date));
		return(gmdate('l jS \of F Y', $epoch_date));
		
		
    }
    
450
451
    
    
452
453

    
454
455
456
457
458
459
}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/nG6/class.tx_nG6_utils.php']) {
    include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/nG6/class.tx_nG6_utils.php']);
}

460
461
462
463
if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/nG6/class.tx_nG6_db.php']) {
    include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/nG6/class.tx_nG6_db.php']);
}

464
?>