]> git.sur5r.net Git - bacula/bacula/blob - gui/baculum/protected/Common/Class/Miscellaneous.php
baculum: New Baculum API and Baculum Web
[bacula/bacula] / gui / baculum / protected / Common / Class / Miscellaneous.php
1 <?php
2
3 /*
4  * Small sorting callback function to sort files and directories by name.
5  * Function keeps '.' and '..' names always in the beginning of array.
6  * Used to sort files and directories from Bvfs.
7  */
8 function sortFilesListByName($a, $b) {
9         $firstLeft = substr($a['name'], 0, 1);
10         $firstRight = substr($b['name'], 0, 1);
11         if ($firstLeft == '.' && $firstRight != '.') {
12                 return -1;
13         } else if ($firstRight == '.' && $firstLeft != '.') {
14                 return 1;
15         }
16         return strcasecmp($a['name'], $b['name']);
17 }
18
19 class Miscellaneous extends TModule {
20
21         const LICENCE_FILE = 'LICENSE';
22
23         const RPATH_PATTERN = '/^b2\d+$/';
24
25         private $jobTypes = array(
26                 'B' => 'Backup',
27                 'M' => 'Migrated',
28                 'V' => 'Verify',
29                 'R' => 'Restore',
30                 'I' => 'Internal',
31                 'D' => 'Admin',
32                 'A' => 'Archive',
33                 'C' => 'Copy',
34                 'c' => 'Copy Job',
35                 'g' => 'Migration'
36         );
37
38         private $jobLevels = array(
39                 'F' => 'Full',
40                 'I' => 'Incremental',
41                 'D' => 'Differential',
42                 'B' => 'Base',
43                 'f' => 'VirtualFull',
44                 'V' => 'InitCatalog',
45                 'C' => 'Catalog',
46                 'O' => 'VolumeToCatalog',
47                 'd' => 'DiskToCatalog'
48         );
49
50         private $jobStates =  array(
51                 'C' => array('value' => 'Created', 'description' =>'Created but not yet running'),
52                 'R' => array('value' => 'Running', 'description' => 'Running'),
53                 'B' => array('value' => 'Blocked', 'description' => 'Blocked'),
54                 'T' => array('value' => 'Terminated', 'description' =>'Terminated normally'),
55                 'W' => array('value' => 'Terminated', 'description' =>'Terminated normally with warnings'),
56                 'E' => array('value' => 'Error', 'description' =>'Terminated in Error'),
57                 'e' => array('value' => 'Non-fatal error', 'description' =>'Non-fatal error'),
58                 'f' => array('value' => 'Fatal error', 'description' =>'Fatal error'),
59                 'D' => array('value' => 'Verify Diff.', 'description' =>'Verify Differences'),
60                 'A' => array('value' => 'Canceled', 'description' =>'Canceled by the user'),
61                 'I' => array('value' => 'Incomplete', 'description' =>'Incomplete Job'),
62                 'F' => array('value' => 'Waiting on FD', 'description' =>'Waiting on the File daemon'),
63                 'S' => array('value' => 'Waiting on SD', 'description' =>'Waiting on the Storage daemon'),
64                 'm' => array('value' => 'Waiting for new vol.', 'description' =>'Waiting for a new Volume to be mounted'),
65                 'M' => array('value' => 'Waiting for mount', 'description' =>'Waiting for a Mount'),
66                 's' => array('value' => 'Waiting for storage', 'description' =>'Waiting for Storage resource'),
67                 'j' => array('value' => 'Waiting for job', 'description' =>'Waiting for Job resource'),
68                 'c' => array('value' => 'Waiting for client', 'description' =>'Waiting for Client resource'),
69                 'd' => array('value' => 'Waiting for Max. jobs', 'description' =>'Wating for Maximum jobs'),
70                 't' => array('value' => 'Waiting for start', 'description' =>'Waiting for Start Time'),
71                 'p' => array('value' => 'Waiting for higher priority', 'description' =>'Waiting for higher priority job to finish'),
72                 'i' => array('value' => 'Batch insert', 'description' =>'Doing batch insert file records'),
73                 'a' => array('value' => 'Despooling attributes', 'description' =>'SD despooling attributes'),
74                 'l' => array('value' => 'Data despooling', 'description' =>'Doing data despooling'),
75                 'L' => array('value' => 'Commiting data', 'description' =>'Committing data (last despool)')
76         );
77
78         private $jobStatesOK = array('T', 'D');
79         private $jobStatesWarning = array('W');
80         private $jobStatesError = array('E', 'e', 'f', 'I');
81         private $jobStatesCancel = array('A');
82         private $jobStatesRunning = array('C', 'R', 'B', 'F', 'S', 'm', 'M', 's', 'j', 'c', 'd','t', 'p', 'i', 'a', 'l', 'L');
83
84         private $runningJobStates = array('C', 'R');
85
86         private $components = array(
87                 'dir' => array('full_name' => 'Director', 'main_resource' => 'Director'),
88                 'sd' => array('full_name' => 'Storage Daemon', 'main_resource' => 'Storage'),
89                 'fd' => array('full_name' => 'File Daemon', 'main_resource' => 'FileDaemon'),
90                 'bcons' => array('full_name' => 'Console', 'main_resource' => 'Director')
91         );
92
93         /**
94          * Getting the licence from file.
95          * 
96          * @access public
97          * @return string licence text
98          */
99         public function getLicence() {
100                 return nl2br(htmlspecialchars(file_get_contents(self::LICENCE_FILE)));
101         }
102
103         public function getJobLevels() {
104                 return $this->jobLevels;
105         }
106
107         public function getJobState($jobStateLetter = null) {
108                 $state;
109                 if(is_null($jobStateLetter)) {
110                         $state = $this->jobStates;
111                 } else {
112                         $state = array_key_exists($jobStateLetter, $this->jobStates) ? $this->jobStates[$jobStateLetter] : null;
113                 }
114                 return $state;
115         }
116
117         public function getRunningJobStates() {
118                 return $this->runningJobStates;
119         }
120
121         public function getComponents() {
122                 $components = array_keys($this->components);
123         }
124
125         public function getMainComponentResource($type) {
126                 $resource = null;
127                 if (array_key_exists($type, $this->components)) {
128                         $resource = $this->components[$type]['main_resource'];
129                 }
130                 return $resource;
131         }
132
133         public function getComponentFullName($type) {
134                 $name = '';
135                 if (array_key_exists($type, $this->components)) {
136                         $name = $this->components[$type]['full_name'];
137                 }
138                 return $name;
139         }
140
141         public function getJobType($jobTypeLetter = null) {
142                 $type;
143                 if(is_null($jobTypeLetter)) {
144                         $type = $this->jobTypes;
145                 } else {
146                         $type = array_key_exists($jobTypeLetter, $this->jobTypes) ? $this->jobTypes[$jobTypeLetter] : null;
147                 }
148                 return $type;
149
150         }
151
152         public function getJobStatesByType($type) {
153                 $statesByType = array();
154                 $states = array();
155                 switch($type) {
156                         case 'ok':
157                                 $states = $this->jobStatesOK;
158                                 break;
159                         case 'warning':
160                                 $states = $this->jobStatesWarning;
161                                 break;
162                         case 'error':
163                                 $states = $this->jobStatesError;
164                                 break;
165                         case 'cancel':
166                                 $states = $this->jobStatesCancel;
167                                 break;
168                         case 'running':
169                                 $states = $this->jobStatesRunning;
170                                 break;
171                 }
172
173                 for ($i = 0; $i < count($states); $i++) {
174                         $statesByType[$states[$i]] = $this->getJobState($states[$i]);
175                 }
176
177                 return $statesByType;
178         }
179
180         public function isValidJobLevel($jobLevel) {
181                 return array_key_exists($jobLevel, $this->getJobLevels());
182         }
183
184         /**
185          * Writing INI-style configuration file.
186          * 
187          * Functions has been got from StackOverflow.com service (http://stackoverflow.com/questions/4082626/save-ini-file-with-comments).
188          * 
189          * @access public
190          * @param string $file file localization
191          * @param array $options structure of config file params
192          * @return mixed if success then returns the number of bytes that were written to the file as the integer type, if failure then returns false
193          */
194         public function writeINIFile($file, array $options){
195                 $tmp = '';
196                 foreach($options as $section => $values){
197                         $tmp .= "[$section]\n";
198                                 foreach($values as $key => $val){
199                                         if(is_array($val)){
200                                                 foreach($val as $k => $v) {
201                                                         $v = $this->escapeINIVal($v);
202                                                         $tmp .= "{$key}[$k] = \"$v\"\n";
203                                                 }
204                                         } else {
205                                                 $val = $this->escapeINIVal($val);
206                                                 $tmp .= "$key = \"$val\"\n";
207                                         }
208                                 }
209                         $tmp .= "\n";
210                 }
211                 $old_umask = umask(0);
212                 umask(0077);
213                 $result = file_put_contents($file, $tmp);
214                 umask($old_umask);
215                 return $result;
216         }
217
218         /**
219          * Escape text written to INI-style file.
220          *
221          * @access private
222          * @param string $value text to escape
223          * @return string escaped text
224          */
225         private function escapeINIVal($value) {
226                 $esc_value = str_replace('"', '\"', $value);
227                 return $esc_value;
228         }
229
230         /**
231          * Parse INI-style configuration file.
232          * 
233          * @access public
234          * @param string $file file localization
235          * @return array data of configuration file
236          */
237         public static function parseINIFile($file) {
238                 $content = array();
239                 if (file_exists($file)) {
240                         $content = parse_ini_file($file, true);
241                         if (!is_array($content)) {
242                                 $content = array();
243                         }
244                 }
245                 return $content;
246         }
247
248
249         /**
250          * This method is copied from http://stackoverflow.com/questions/4345554/convert-php-object-to-associative-array
251          */
252         public function objectToArray($data) {
253                 if (is_array($data) || is_object($data)) {
254                         $result = array();
255                         foreach ($data as $key => $value) {
256                                 $result[$key] = $this->objectToArray($value);
257                         }
258                         return $result;
259                 }
260                 return $data;
261         }
262
263         public function decode_bacula_lstat($lstat) {
264                 $base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
265                 $lstat = trim($lstat);
266                 $lstat_fields = explode(' ', $lstat);
267
268                 if(count($lstat_fields) !== 16) {
269                         die('Błąd! Niepoprawna ilość pól wartości LStat. Proszę upewnić się, że podany ciąg znaków jest poprawną wartością LStat');
270                 }
271
272                 list($dev, $inode, $mode, $nlink, $uid, $gid, $rdev, $size, $blocksize, $blocks, $atime, $mtime, $ctime, $linkfi, $flags, $data) = $lstat_fields;
273                 $encoded_values = array('dev' => $dev, 'inode' => $inode, 'mode' => $mode, 'nlink' => $nlink, 'uid' => $uid, 'gid' => $gid, 'rdev' => $rdev, 'size' => $size, 'blocksize' => $blocksize, 'blocks' => $blocks, 'atime' => $atime, 'mtime' => $mtime, 'ctime' => $ctime, 'linkfi' => $linkfi, 'flags' => $flags, 'data' => $data);
274
275                 $ret = array();
276                 foreach($encoded_values as $key => $val) {
277                         $result = 0;
278                         $is_minus = false;
279                         $start = 0;
280
281                         if(substr($val, 0, 1) === '-') {
282                                 $is_minus = true;
283                                 $start++;
284                         }
285
286                         for($i = $start; $i < strlen($val); $i++) {
287                                 $result = bcmul($result, bcpow(2,6));
288                                 $result +=  strpos($base64, substr($val, $i , 1));
289                         }
290                         $ret[$key] = ($is_minus === true) ? -$result : $result;
291                 }
292                 return $ret;
293         }
294
295         public function parseBvfsList($list) {
296                 $elements = array();
297                 for($i = 0; $i < count($list); $i++) {
298                         if(preg_match('/^(?P<pathid>\d+)\t(?P<filenameid>\d+)\t(?P<fileid>\d+)\t(?P<jobid>\d+)\t(?P<lstat>[a-zA-z0-9\+\/\ ]+)\t(?P<name>.*)\/$/', $list[$i], $match) == 1 || preg_match('/^(?P<pathid>\d+)\t(?P<filenameid>\d+)\t(?P<fileid>\d+)\t(?P<jobid>\d+)\t(?P<lstat>[a-zA-z0-9\+\/\ ]+)\t(?P<name>\.{2})$/', $list[$i], $match) == 1) {
299                                 if($match['name'] == '.') {
300                                         continue;
301                                 } elseif($match['name'] != '..') {
302                                         $match['name'] .= '/';
303                                 }
304                                 $elements[] = array('pathid' => $match['pathid'], 'filenameid' => $match['filenameid'], 'fileid' => $match['fileid'], 'jobid' => $match['jobid'], 'lstat' => $match['lstat'], 'name' => $match['name'], 'type' => 'dir');
305                         } elseif(preg_match('/^(?P<pathid>\d+)\t(?P<filenameid>\d+)\t(?P<fileid>\d+)\t(?P<jobid>\d+)\t(?P<lstat>[a-zA-z0-9\+\/\ ]+)\t(?P<name>[^\/]+)$/', $list[$i], $match) == 1) {
306                                 if($match['name'] == '.') {
307                                         continue;
308                                 }
309                                 $elements[] = array('pathid' => $match['pathid'], 'filenameid' => $match['filenameid'], 'fileid' => $match['fileid'], 'jobid' => $match['jobid'], 'lstat' => $match['lstat'], 'name' => $match['name'], 'type' => 'file'); 
310                         }
311                 }
312                 usort($elements, 'sortFilesListByName');
313                 return $elements;
314         }
315
316         public function parseFileVersions($filename, $list) {
317                 $elements = array();
318                 for($i = 0; $i < count($list); $i++) {
319                         if(preg_match('/^(?P<pathid>\d+)\t(?P<filenameid>\d+)\t(?P<fileid>\d+)\t(?P<jobid>\d+)\t(?P<lstat>[a-zA-z0-9\+\/\ ]+)\t(?P<md5>.+)\t(?P<volname>.+)\t(?P<inchanger>\d+)$/', $list[$i], $match) == 1) {
320                                 $elements[$match['fileid']] = array('name' => $filename, 'pathid' => $match['pathid'], 'filenameid' => $match['filenameid'], 'fileid' => $match['fileid'], 'jobid' => $match['jobid'], 'lstat' => $this->decode_bacula_lstat($match['lstat']), 'md5' => $match['md5'], 'volname' => $match['volname'], 'inchanger' => $match['inchanger'], 'type' => 'file');
321                         }
322                 }
323                 return $elements;
324         }
325
326         public function findJobIdStartedJob($output) {
327                 $jobid = null;
328                 $output = array_reverse($output); // jobid is ussually at the end of output
329                 for ($i = 0; $i < count($output); $i++) {
330                         if (preg_match('/^Job queued\.\sJobId=(?P<jobid>\d+)$/', $output[$i], $match) === 1) {
331                                 $jobid = $match['jobid'];
332                                 break;
333                         }
334                 }
335                 return $jobid;
336         }
337
338         /**
339          * Get (pseudo)random string.
340          *
341          * Useful for log out user from HTTP Basic auth by providing random password.
342          *
343          * @access public
344          * @return string random 62 characters string from range [a-zA-Z0-9]
345          */
346         public function getRandomString($length = null) {
347                 $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
348                 $rand_string = str_shuffle($characters);
349                 if (is_int($length) && $length <= 62) {
350                         $rand_string = substr($rand_string, 0, $length);
351                 }
352                 return $rand_string;
353         }
354
355         /**
356          * Get encrypted password to use in HTTP Basic auth.
357          *
358          * @access public
359          * @param string $password plain text password
360          * @return string encrypted password
361          */
362         public function getCryptedPassword($password) {
363                 $enc_pwd = crypt($password, base64_encode($password));
364                 return $enc_pwd;
365         }
366 }
367 ?>