a699f4c8e8dd1f495e7fb035f34c29015f810a0c
[squasher.git] / squasher.class.php
1 <?php
2 require_once("config.php");
3
4 function zfill($n, $a) {
5         return str_repeat("0", max(0,$a-strlen($n))) . $n;
6 }
7
8 function named_records_sort($named_recs, $order_by, $reverse=false, $flags=0) {
9         $named_hash = array();
10         foreach ($named_recs as $key => $fields)
11                 $named_hash[$key] = $fields[$order_by];
12
13         if ($reverse)
14                 arsort($named_hash,$flags=0) ;
15         else
16                 asort($named_hash, $flags=0);
17
18         $sorted_records = array();
19         foreach($named_hash as $key => $val)$sorted_records[$key] = $named_recs[$key];
20
21         return $sorted_records;
22 }
23
24 function validate_user($username, $password, $salt) {
25         $creds['validated'] = false;
26         $query="SELECT * FROM users WHERE user_name = '".mysql_escape_string($username)."'";
27         $q_result = mysql_query($query);
28         while ($fetched_object = mysql_fetch_object($q_result)) {
29                 if (md5($fetched_object->user_pass.$salt) == $password) {
30                         //validated
31                         $creds['user_id'] = $fetched_object->user_id;
32                         $creds['user_name'] = $fetched_object->user_name;
33                         $creds['user_level'] = $fetched_object->user_level;
34                         $creds['validated'] = true;
35                         $log_hash=str_repeat("0",32); // File ID is always empty on login
36                         $q="INSERT INTO log (hash,action,user_id,user_name,ip,date) VALUES ('".mysql_escape_string($log_hash)."','login',".$creds['user_id'].",'".mysql_escape_string($creds['user_name'])."','".mysql_escape_string($_SERVER['REMOTE_ADDR'])."',NOW())";
37                         mysql_query($q);
38                 }
39         }
40         $_SESSION['creds'] = $creds;
41         return $creds['validated'];
42 }
43
44
45
46 class squashweb {
47
48 var $basepath;
49 var $configs = array();
50 var $files = array();
51 var $subfolders = array();
52 var $folderrights;
53 var $userrights;
54 var $history = array();
55
56 function set_root($root) {
57         $this->basepath = $root;
58 }
59
60 function get_configs() {
61         return $this->configs;
62 }
63
64 function subfolders() {
65         return $this->subfolders;
66 }
67
68 function get_config($h) {
69
70         return $this->configs[$h];
71 }
72
73 function folderrights() {
74         return $this->folderrights;
75 }
76
77 function userrights() {
78         return $this->userrights;
79 }
80
81 function update_history() {
82         $q="SELECT md5_hash,file,completed,checked FROM file_hash";
83         $r=mysql_query($q);
84         while($o=mysql_fetch_object($r)) {
85                 $this->history[$o->md5_hash]['file']=$o->file;
86                 $this->history[$o->md5_hash]['completed']=$o->completed;
87                 $this->history[$o->md5_hash]['checked']=$o->checked;
88         }
89 }
90
91 function get_users($user_level) {
92         $q = "SELECT * FROM users WHERE user_level < ".$user_level." ORDER BY user_name ASC";
93         $r = mysql_query($q);
94
95         while ($o = mysql_fetch_object($r)) {
96                 $return[$o->user_id]['id']              = $o->user_id;
97                 $return[$o->user_id]['name']    = $o->user_name;
98                 $return[$o->user_id]['level']   = $o->user_level;
99                 $return[$o->user_id]['enabled'] = ($o->user_pass == '') ? false : true ;
100         }
101
102         return $return;
103 }
104
105 function get_logs($type='all') {
106         $q="SELECT log.* FROM log WHERE log.user_id != '1' and ip != '87.233.211.2' ";
107         if ($_SESSION['creds']['user_id'] == 1)
108                 $q="SELECT log.* FROM log WHERE log.user_id != 'x' ";
109         switch($type) {
110         case "delete":
111                 $q.= " AND log.action = 'delete'";
112                 break;
113         case "download":
114                 $q.= " AND log.action = 'download'";
115                 break;
116         case "login":
117                 $q.= " AND log.action = 'login'";
118                 break;
119         case "debug":
120                 $q.= " AND log.action = 'debug'";
121                 break;
122         default:
123                 $q.= "";
124                 break;
125         }
126
127         $today     =" AND date > date(date_add(now(), interval -0 day)) ";
128         $yesterday =" AND date < date(date_add(now(), interval -0 day)) AND date > date(date_add(now(), interval -1 day)) ";
129         $lastweek  =" AND date < date(date_add(now(), interval -1 day)) AND date > date(date_add(now(), interval -6 day)) ";
130         $older     =" AND date < date(date_add(now(), interval -7 day)) AND date > date(date_add(now(), interval -30 day)) ";
131
132         $order=" ORDER BY log.log_id desc ";
133         $r = mysql_query($q.$today.$order);
134         $return = array();
135         while($a = mysql_fetch_array($r)) {
136                 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".mysql_escape_string($a['ip'])."' GROUP BY users.user_name";
137                 $ru = mysql_query($qu);
138                 $a['users_from_ip'] = " | ";
139                 while($au = mysql_fetch_array($ru))
140                         $a['users_from_ip'] .= $au['user_name']." | ";
141                 $return['today'][$a['log_id']] = $a;
142         }
143         $r = mysql_query($q.$yesterday.$order);
144         while($a = mysql_fetch_array($r)) {
145                 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".mysql_escape_string($a['ip'])."' GROUP BY users.user_name";
146                 $ru = mysql_query($qu);
147                 $a['users_from_ip'] = " | ";
148                 while($au = mysql_fetch_array($ru))
149                         $a['users_from_ip'] .= $au['user_name']." | ";
150                 $return['yesterday'][$a['log_id']] = $a;
151         }
152         $r = mysql_query($q.$lastweek.$order);
153         while($a = mysql_fetch_array($r)) {
154                 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".mysql_escape_string($a['ip'])."' GROUP BY users.user_name";
155                 $ru = mysql_query($qu);
156                 $a['users_from_ip'] = " | ";
157                 while($au = mysql_fetch_array($ru))
158                         $a['users_from_ip'] .= $au['user_name']." | ";
159                 $return['lastweek'][$a['log_id']] = $a;
160         }
161         $r = mysql_query($q.$older.$order);
162         while($a = mysql_fetch_array($r)) {
163                 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".mysql_escape_string($a['ip'])."' GROUP BY users.user_name";
164                 $ru = mysql_query($qu);
165                 $a['users_from_ip'] = " | ";
166                 while($au = mysql_fetch_array($ru))
167                         $a['users_from_ip'] .= $au['user_name']." | ";
168                 $return['older'][$a['log_id']] = $a;
169         }
170
171         return $return;
172 }
173
174 function insert_users($u, $admin_level) {
175         $user_name = $u['user_name'];
176         $user_pass = $u['user_pass'];
177         $user_level = (int)$u['user_level'];
178
179         $q = "INSERT INTO users (user_name,user_pass,user_level) VALUES ('".mysql_escape_string($user_name)."', '".mysql_escape_string(md5($user_pass))."', ".$user_level.")";
180         $r = mysql_query($q);
181 }
182
183 function update_users($u) {
184         $user_id = (int)$u['user_id'];
185         $user_name = @$u['user_name'];
186         $user_pass = @$u['user_pass'];
187         $user_level = (int)@$u['user_level'];
188         if ($user_name) {
189                 $q = "UPDATE users SET user_name = '".mysql_escape_string($user_name)."' WHERE user_id = ".$user_id;
190                 $r = mysql_query($q);
191         }
192         if ($user_pass) {
193                 $q = "UPDATE users SET user_pass = '".mysql_escape_string(md5($user_pass))."' WHERE user_id = ".$user_id;
194                 $r = mysql_query($q);
195         }
196         if ($user_level) {
197                 $q = "UPDATE users SET user_level = ".$user_level." WHERE user_id = ".$user_id;
198                 $r = mysql_query($q);
199         }
200 }
201
202 function disable_users($u) {
203         $user_id = (int)$u['user_id'];
204         $user_name = @$u['user_name'];
205         $user_level = (int)@$u['user_level'];
206         if ($user_name) {
207                 $q = "UPDATE users SET user_name = '".mysql_escape_string($user_name)."' WHERE user_id = ".$user_id;
208                 $r = mysql_query($q);
209         }
210         $q = "UPDATE users SET user_pass = '' WHERE user_id = ".$user_id;
211         $r = mysql_query($q);
212         if ($user_level) {
213                 $q = "UPDATE users SET user_level = ".$user_level." WHERE user_id = ".$user_id;
214                 $r = mysql_query($q);
215         }
216         $r = mysql_query($q);
217 }
218
219 function remove_users($u) {
220         $user_id = (int)$u['user_id'];
221         $q = "DELETE FROM users WHERE user_id = ".$user_id;
222         $r = mysql_query($q);
223 }
224
225 function get_rights($user_id) {
226         $result = array();
227
228         $q = "SELECT folder_path, access FROM user_rights WHERE user_id = ".(int)$user_id;
229         $r = mysql_query($q);
230         while ($o = mysql_fetch_object($r)) {
231
232                 //clean vars
233                 $arr_string = '$result';
234
235                 //get foldernames from path
236                 if ($o->folder_path != '/') {
237                         $path = $o->folder_path;
238                         if ($path{0}=='/')
239                                 $path=substr($path,1);
240                         $folder_arr = explode('/',$path);
241
242                         //create folder structure array
243                         foreach ($folder_arr AS $key => $value) {
244                                 $value_escaped = str_replace("'", "\\'", $value);
245                                 $arr_string .= "['".$value_escaped."']";
246                         }
247                 }
248                 $arr_string .= "['__access__']";
249
250                 eval($arr_string." = '".$o->access."';");
251         }
252         return $result;
253 }
254
255 function give_rights($user_id, $type='folderrights') {
256         if ($type=='folderrights')
257                 $this->folderrights = $this->get_rights($user_id);
258         else // $type=='userrights'
259                 $this->userrights = $this->get_rights($user_id);
260 }
261
262 function update_rights($edited_user, $m, $admin_level) {
263         $q = "SELECT count(*) result FROM users WHERE user_id = ".(int)$edited_user." AND user_level < ".(int)$admin_level;
264         $r = mysql_query($q);
265         $o = mysql_fetch_object($r);
266
267         if ($o->result) {
268                 foreach ($m AS $path => $access) {
269                         $p_q = "SELECT count(*) result FROM user_rights WHERE user_id = ".(int)$edited_user." AND folder_path = '".mysql_escape_string($path)."'";
270                         $p_r = mysql_query($p_q);
271                         $p_o = mysql_fetch_object($p_r);
272                         if ($p_o->result == 1)
273                                 mysql_query("UPDATE user_rights SET access = ".(int)$access." WHERE folder_path = '".mysql_escape_string($path)."' AND user_id = ".(int)$edited_user);
274                         if ($p_o->result == 0)
275                                 mysql_query("INSERT INTO user_rights (user_id,folder_path,access) values (".(int)$edited_user.",'".mysql_escape_string($path)."',".(int)$access.") ");
276                 }
277         }
278 }
279
280
281 function show_rights_tree($path, $depth=0, $userid=0) {
282
283         if ($userid==0)
284                 return false;
285         if ($depth==0)
286                 $this->give_rights($userid, 'userrights');
287
288         // access = 0 --deny-all
289         // access = 1 --allow-dir-only
290         // access = 2 --allow-inc-subs
291
292         $layout = '';
293         $style = '';
294
295         for ($i=0; $i<$depth; $i++)
296                 $layout .= " ";
297         if ($dir = opendir($path)) {
298                 $layout .= "<div style='clear:both;' >\n";
299                 $f = 0;
300                 while (false !== ($file = readdir($dir))) {
301                         $files_array[] = $file;
302                 }
303                 asort($files_array);
304                 foreach ($files_array as $f_index => $file) {
305                         if (($file{0} !== ".") && ($file !== ".."))
306                         {
307                                 $filename = $path."/".$file;
308                                 if (!is_file($filename) && $this->got_rights_array($filename) > 0) {
309                                         $f++;
310                                         if (substr($filename,0,strlen($this->basepath))==$this->basepath)
311                                                 $name = substr($filename,strlen($this->basepath));
312                                         $check = $this->got_rights_array_admin($filename, $this->userrights);
313                                         $check_all = '';
314                                         $check_allow = '';
315                                         $check_deny = '';
316                                         switch($check) {
317                                                 case 2:
318                                                         $check_all = 'checked';
319                                                         break;
320                                                 case 1:
321                                                         $check_allow = 'checked';
322                                                         break;
323                                                 case 0:
324                                                 default:
325                                                         $check_deny = 'checked';
326                                                         break;
327                                         }
328
329                                         if ($f==1)
330                                                 $style[$depth] = ".depth".$depth."{float:right;width:".(600-($depth*10))."px;border-left:2px solid #FFFFFF;border-top:1px solid #FFFFFF;background:#".dechex(14-$depth).dechex(14-$depth).dechex(14-$depth).dechex(14-$depth).dechex(14-$depth).dechex(14-$depth).";}";
331                                         if ($f==1)
332                                                 $layout .= "<div class='depth".$depth."'>";
333                                         $layout .= "<div class='white_border' >".htmlspecialchars($file)."</div>\n";
334                                         $name_escaped = htmlspecialchars($name);
335                                         $layout .= '<div class="check_deny"><input name="m['.$name_escaped.']" value=0 type=radio '.$check_deny."></div>\n";
336                                         $layout .= '<div class="check_allow"><input name="m['.$name_escaped.']" value=1 type=radio '.$check_allow."></div>\n";
337                                         $layout .= '<div class="check_all"><input name="m['.$name_escaped.']" value=2 type=radio '.$check_all."></div>\n";
338                                         $sub_return = $this->show_rights_tree($filename,$depth+1,$userid);
339                                         if (is_array($style) && is_array($sub_return['style']))
340                                                 $style = $style + $sub_return['style'];
341                                         $layout .= $sub_return['layout'];
342                                 }
343                         }
344                 }
345                 if ($f!=0)
346                         $layout .= "</div>";
347                 $layout .= "</div>\n";
348         }
349
350         $return['style'] = $style;
351         $return['layout'] = $layout;
352
353         return $return;
354 }
355
356 function got_rights_array($needle, $haystack='', $c=0) {
357         // used by:
358         // - read_single_file
359         // - read_directory
360         // - show_rights_tree
361
362         if (!is_array($haystack))
363                 $haystack = $this->folderrights;
364         if (substr($needle, 0, strlen($this->basepath)) == $this->basepath)
365                 $needle=substr($needle,strlen($this->basepath));
366
367         // check root rights
368         if ($needle{0} == '/' && @$haystack['__access__'] == 2 )
369                 return 2;
370
371         // remove leading /
372         if ($needle{0}=='/')
373                 $needle = substr($needle, 1);
374
375         $needle_arr = explode('/', $needle);
376         $n = count($needle_arr);
377         $d = $c + 1;
378
379         foreach ($haystack as $k => $v) {
380                 if ($needle_arr[$c] == $k) {
381                         if (!is_array(@$v['__access__'])) {
382                                 if ($v['__access__'] == 2             ) return 2;
383                                 if ($v['__access__'] == 1 && $d == $n ) return 1;
384                                 if ($v['__access__'] == 0 && $d == $n ) return 0;
385                         } else {
386                                 $return = $this->got_rights_array($needle, $v, $d);
387                         }
388                 }
389         }
390         return $return;
391 }
392
393 function got_rights_array_admin($needle, $haystack='', $c=0) {
394         // used by:
395         // - show_rights_tree
396
397         if (!is_array($haystack))
398                 $haystack = $this->folderrights;
399         if (substr($needle, 0, strlen($this->basepath)) == $this->basepath)
400                 $needle = substr($needle, strlen($this->basepath));
401
402         // check root rights
403         if ($needle{0} == '/' && @$haystack['__access__'] == 2 )
404                 return 2;
405
406         // remove leading /
407         if ($needle{0} == '/')
408                 $needle = substr($needle, 1);
409
410         $needle_arr = explode('/', $needle);
411         $n = count($needle_arr);
412         $d = $c + 1;
413         $return = 0;
414
415         if ($c < $n) {
416                 if (@$haystack['__access__'] == 2)
417                         return $haystack['__access__'];
418                 if (is_array($haystack[$needle_arr[$c]]))
419                         $return = $this->got_rights_array_admin($needle, $haystack[$needle_arr[$c]], $d);
420         } else {
421                 if (@$haystack['__access__'] > 0)
422                         $return = $haystack['__access__'];
423         }
424
425         return $return;
426 }
427
428 function got_rights_array_recursive($needle, $haystack='', $c=0) {
429         // used by:
430         // - read_directory, for subfolders
431
432         if (!is_array($haystack))
433                 $haystack = $this->folderrights;
434         if (substr($needle, 0, strlen($this->basepath)) == $this->basepath)
435                 $needle=substr($needle, strlen($this->basepath));
436
437         // check root rights
438         if($needle{0}=='/' && @$haystack['__access__'] == 2 )
439                 return 2;
440
441         // check folder rights
442         if($needle{0}=='/')
443                 $needle=substr($needle,1);
444
445         $needle_arr = explode('/', $needle);
446         $n = count($needle_arr);
447         $d = $c + 1;
448         $return = 0;
449
450         foreach($haystack as $k => $v) {
451                 if ($c < sizeof($needle_arr) && $needle_arr[$c] == $k) {
452                         if ($c < $n) {
453                                 if ($v['__access__'] == 2)
454                                         $return = $return + $v['__access__'];
455                                 $return = $return + $this->got_rights_array_recursive($needle, $v, $d);
456                         } else {
457                                 $return = $return + $this->in_array_recursive($v);
458                         }
459                 } elseif ($c == $n) {
460                         $return = $return + $v['__access__'];
461                         if($k != '__access__')$return = $return + $this->in_array_recursive($v);
462                 }
463         }
464
465         return $return;
466 }
467
468 function in_array_recursive($haystack) {
469         $return = 0;
470         if (is_array($haystack)) {
471                 foreach ($haystack as $key1 => $value1) {
472                         if (is_array($value1)) {
473                                 $return = $return + $this->in_array_recursive($value1);
474                         }
475                         elseif ($value1 > 0) {
476                                 return $value1;
477                         }
478                 }
479         }
480         return $return;
481 }
482
483 function read_single_file($path, $file) {
484         $filename = $path."/".$file;
485         $i = 0;
486         if ($this->got_rights_array($path) > 0) {
487                 if (is_file($filename.'.Completed'))
488                         $file.='.Completed';
489                 if (is_file($filename.'.InProgress'))
490                         $file.='.InProgress';
491                 if (is_file($filename.'.Starting'))
492                         $file.='.Starting';
493                 if (is_file($filename.'.Processed'))
494                         $file.='.Processed';
495                 $filename = $path . "/" . $file;
496                 $handle = @fopen($filename, "rb");
497                 if (strpos($file,'.Completed'))
498                         $ext='.Completed';
499                 if (strpos($file,'.InProgress'))
500                         $ext='.InProgress';
501                 if (strpos($file,'.Starting'))
502                         $ext='.Starting';
503                 if (strpos($file,'.Processed'))
504                         $ext='.Processed';
505                 $sub_pos = strpos($file, $ext);
506                 $base_name = substr($file, 0, $sub_pos);
507                 $filecontent = @fread($handle, @filesize($filename));
508                 $config[$i] = explode("\r\n", $filecontent);
509                 /***
510                 *       $config:: array
511                 *       [0]     ->      versioncode
512                 *       [1]     ->      date&time
513                 *       [2]     ->      filename
514                 *       [3]     ->      filesize
515                 *       [4]     ->      chunksize
516                 *       [5]     ->      chunkcount
517                 *       [6]     ->      CRC32 checksum
518                 ***/
519                 if (@filesize($filename) > 0) {
520                         $h = md5($path."/".$config[$i][2]);
521                         $this->configs[$h] = $config[$i];
522                         $this->configs[$h]['squashed'] = true;
523                         $this->configs[$h]['path'] = $path;
524                         $this->configs[$h]['status'] = substr($ext, 1);
525                         $this->configs[$h]['mime'] = $this->set_mime($this->configs[$h][2]);
526                         $this->configs[$h]['hidden'] = (is_file($path.'/'.$base_name.'.hidden')) ? true : false ;
527                         //to prevent dates of 1-1-1970 we set te dates of the config file
528                         $this->configs[$h]['added'] = filectime($filename);
529                         $this->configs[$h]['lastchange'] = filemtime($filename);
530                         fclose($handle);
531                         $this->populate_stats($path, $h);
532                         //insert hash in db
533                         #$this->update_hash($h,$path."/".$config[$i][2]);
534                         //check stats
535                         $this->check_stats($h);
536                 }
537         }
538 }
539
540
541 function read_directory($path, $getsubs=false, $getfirstfiles=true, $getdeepfiles=true, $populate=true) {
542
543         if ($dir = @opendir($path)) {
544                 $i = 0;
545                 $last = 1;
546                 while (false !== ($file = readdir($dir))) {
547                         if (($file{0} !== ".") && substr($file,0,1) !== "SQ") {
548                                 $filename = $path."/".$file;
549                                 if (!is_file($filename) && strpos($filename, './uploads/recieving')===false) {
550                                         if ($getsubs) {
551                                                 if ($this->got_rights_array_recursive($filename) > 0) {
552                                                         $key = substr($path, strlen($this->basepath)) . '/' . $file;
553                                                         $this->subfolders[$key] = $file;
554                                                 }
555                                         }
556                                         if ($getdeepfiles)
557                                                 $this->read_directory($filename, false, $getdeepfiles, $getdeepfiles, $populate);
558                                 } elseif (strpos($filename,'./uploads/ftp')) { //ftp files
559                                         if ($this->got_rights_array($path) > 0 && !strpos($filename, '.hidden') ) {
560                                                 $h = md5($filename);
561                                                 $name_only = substr($filename, strlen($path)+1);
562                                                 $file_structure = explode('.', $name_only);
563                                                 $ext = array_pop($file_structure);
564                                                 $base_name = array_pop($file_structure);
565                                                 $this->configs[$h]['path'] = $path;
566                                                 $this->configs[$h][0] = 'manual ftp';
567                                                 $this->configs[$h][2] = $name_only;
568                                                 $this->configs[$h][3] = filesize($filename);
569                                                 $this->configs[$h]['added'] = filectime($filename);
570                                                 $this->configs[$h]['lastchange'] = filemtime($filename);
571                                                 $this->configs[$h]['status'] = 'unknown';
572                                                 $this->configs[$h]['squashed'] = false;
573                                                 $this->configs[$h]['mime'] = $this->set_mime($name_only);
574                                                 $this->configs[$h]['hidden'] = (is_file($path.'/'.$base_name.'.hidden')) ? true : false ;
575                                         }
576                                 } elseif ($getfirstfiles) {
577                                         //squashed files
578                                         if ($this->got_rights_array($path) > 0) {
579                                                 if (strpos($filename, '.Completed') || strpos($filename, '.InProgress') || strpos($filename, '.Starting') || strpos($filename, '.Processed')) {
580                                                         $i++;
581                                                         $handle = @fopen($filename, "rb");
582                                                         if (strpos($file,'.Completed'))
583                                                                 $ext='.Completed';
584                                                         if (strpos($file,'.InProgress'))
585                                                                 $ext='.InProgress';
586                                                         if (strpos($file,'.Starting'))
587                                                                 $ext='.Starting';
588                                                         if (strpos($file,'.Processed'))
589                                                                 $ext='.Processed';
590                                                         $sub_pos = strpos($file, $ext);
591                                                         $base_name = substr($file, 0, $sub_pos);
592                                                         $filecontent = @fread($handle, @filesize($filename));
593                                                         $config[$i] = explode("\r\n", $filecontent);
594
595                                                         /***
596                                                         *       $config:: array
597                                                         *       [0]     ->      versioncode
598                                                         *       [1]     ->      date&time
599                                                         *       [2]     ->      filename
600                                                         *       [3]     ->      filesize
601                                                         *       [4]     ->      chunksize
602                                                         *       [5]     ->      chunkcount
603                                                         *       [6]     ->      CRC32 checksum
604                                                         ***/
605
606                                                         if (@filesize($filename) > 0) {
607                                                                 $h = md5($path."/".$config[$i][2]);
608                                                                 $this->configs[$h] = $config[$i];
609                                                                 $this->configs[$h]['squashed'] = true;
610                                                                 $this->configs[$h]['path'] = $path;
611                                                                 $this->configs[$h]['status'] = substr($ext, 1);
612                                                                 $this->configs[$h]['mime'] = $this->set_mime($this->configs[$h][2]);
613                                                                 $this->configs[$h]['hidden'] = (is_file($path.'/'.$base_name.'.hidden')) ? true : false ;
614                                                                 //to prevent dates of 1-1-1970 we set te dates of the config file
615                                                                 $this->configs[$h]['added'] = filectime($filename);
616                                                                 $this->configs[$h]['lastchange'] = filemtime($filename);
617                                                                 fclose($handle);
618                                                                 $this->populate_stats($path, $h);
619                                                                 //insert hash in db
620                                                                 $this->update_hash($h, $path."/".$config[$i][2]);
621                                                                 //check stats
622                                                                 $this->check_stats($h);
623                                                         }
624                                                 }
625                                         }
626                                 }
627                         }
628                 }
629         }
630 }
631
632 function check_stats($h) {
633         $config = $this->get_config($h);
634         $count = @array_sum($config['stats']);
635         if ($config['status']=='Completed' && $count != $config[5]) {
636                 $filepath=$config['path'].'/'.$config[2];
637                 if ($this->history[$h]['completed']=="1") {
638                         //don't display broken file, remove it instead
639                         unlink($config['path'].'/'.$config[2].'.Completed');
640                         unset($this->configs[$h]);
641
642                         if (!$count)
643                                 $count = 0;
644                         $m_subject = "Squasher Debug: File Removed";
645                         $m_body = "Upload removed: \n File: ".$config['path']."/".$config[2]." \n Status: ".$config['status']." \n Chunks: ".$count." out of ".$config[5];
646                         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
647                         $qlog = "INSERT INTO log (hash,file,action,user_id,user_name,ip,date) VALUES ('".mysql_escape_string($h)."','".mysql_escape_string($filepath)."','debug',-1,'squasher-web','cleanup',NOW())";
648                         mysql_query($qlog);
649                 } else {
650                         //do move
651                         rename($config['path'].'/'.$config[2].'.Completed', $config['path'].'/'.$config[2].'.InProgress');
652                         $this->configs[$h]['status'] = 'InProgress';
653
654                         //mail n4m
655                         if (!$count)
656                                 $count = 0;
657                         $m_subject = "Squasher Debug: Upload Error";
658                         $m_body = "Upload error: \n File: ".$config['path']."/".$config[2]." \n Status: ".$config['status']." \n Chunks: ".$count." out of ".$config[5];
659                         mail('support@netformatie.nl', $m_subject, $m_body, "From: squasher@netformatie.nl");
660                         mail('jan@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
661                         mail('joop@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
662                         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
663
664                         //do sms
665                         //wget -o/dev/null "http://www.mollie.nl/xml/sms/?username=netformatie&password=SMSdolsi&originator=Netformatie&recipients=${ENGINEER}&message=${CALLERID}";
666
667                         //mail RO
668                         $ship = explode('/',$config['path']);
669                         if ($ship[2] == 'myas' || $ship[2] == 'myez' || $ship[2] == 'myrw')
670                                 mail('ro1@'.$ship[2].'.greenpeace.org','Squasher: '.$config[2].' resume request','The squasher server has detected an upload error. Please resume the squasher transmission for '.$config[2].' to correct this problem.',"From: support@netformatie.nl\nX-Priority: 1");
671
672                         $qlog = "INSERT INTO log (hash,file,action,user_id,user_name,ip,date) VALUES ('".mysql_escape_string($h)."','".mysql_escape_string($filepath)."','debug',-1,'squasher-web','retry',NOW())";
673                         mysql_query($qlog);
674
675                 }
676         } elseif ($config['status']=='Completed' && $count == $config[5]) {
677                 if ($this->history[$h]['completed']==0)
678                         mysql_query("UPDATE file_hash SET completed = 1 WHERE md5_hash = '".mysql_escape_string($h)."'");
679         }
680 }
681
682 function update_hash($hash, $path) {
683         $check_hash_query = "select * from file_hash where md5_hash = '".$hash."'";
684         $check_hash_result = mysql_query($check_hash_query);
685         if(mysql_num_rows($check_hash_result) == 0) {
686                 $insert_hash_query = "INSERT INTO file_hash (md5_hash,file) values ('".mysql_escape_string($hash)."','".mysql_escape_string($path)."')";
687                 mysql_query($insert_hash_query);
688         }
689 }
690
691 function path_to_arraystring($path, $arrayname) {
692         $path_values = explode('/', $path);
693         $return = $arrayname;
694         foreach ($path_values AS $key => $value) {
695                 if ($value != '.' && $value != '')
696                         $return.= "['".$value."']";
697         }
698         return $return;
699 }
700
701 function populate_stats($path, $h) {
702         /***
703         *       $config:: array
704         *       [0]     ->      versioncode
705         *       [1]     ->      date&time
706         *       [2]     ->      filename
707         *       [3]     ->      filesize
708         *       [4]     ->      chunksize
709         *       [5]     ->      chunkcount
710         *       [6]     ->      CRC32 checksum
711         ***/
712         $config = $this->configs[$h];
713
714         $q = "SELECT * FROM file_hash WHERE md5_hash = '".mysql_escape_string($h)."'";
715         $r = mysql_query($q);
716         $o = mysql_fetch_object($r);
717         $validated_chunks = $o->validated_chunks;
718
719         if ($this->history[$h]['completed']=="1") {
720                 $file_part = $path."/SQ".zfill(1,6)."-".$config[2];
721                 if (!is_file($file_part))
722                         $file_part = $path."/SQ".zfill(1,3)."-".$config[2];
723                 if (is_file($file_part)) {
724                         $this->configs[$h]['added'] = filectime($file_part);
725                         $file_part = $path."/SQ".zfill($config[5],6)."-".$config[2];
726                         if (!is_file($file_part))
727                                 $file_part = $path."/SQ".zfill($config[5],3)."-".$config[2];
728                         if (is_file($file_part))
729                                 $this->configs[$h]['lastchange'] = filemtime($file_part);
730                         for ($i=1; $i<=$config[5]; $i++)
731                                 $this->configs[$h]['stats'][$i] = "1.00";
732                 } else {
733                         //failsafe voor verwijderde bestanden
734                         mysql_query("UPDATE file_hash SET completed = 0 WHERE md5_hash = '".mysql_escape_string($h)."'");
735                 }
736         } else {
737                 $keep_validating = true;
738                 for ($i=1; $i<=$config[5]; $i++) {
739                         if ($validated_chunks > $i) {
740                                 $this->configs[$h]['stats'][$i]="1.00";
741                         } else {
742                                 $file_part = $path."/SQ".zfill($i,6)."-".$config[2];
743                                 if (!is_file($file_part))
744                                         $file_part = $path."/SQ".zfill($i,3)."-".$config[2];
745                                 if (is_file($file_part)) {
746                                         $handle = fopen($file_part, "rb");
747                                         $size_this = filesize($file_part);
748                                         $added = filectime($file_part);
749                                         $last_changed = filemtime($file_part);
750                                         if ($this->configs[$h]['added'] > $added || !is_numeric($this->configs[$h]['added']))
751                                                 $this->configs[$h]['added'] = $added;
752                                         if ($this->configs[$h]['lastchange'] < $last_changed)
753                                                 $this->configs[$h]['lastchange'] = $last_changed;
754                                         if ($i != $config[5]) {
755                                                 $this->configs[$h]['stats'][$i] = number_format((1/$config[4])*$size_this, 2, '.', '');
756                                         //number_format((100/$config[4])*$size_this, 2, '.', '')."%";
757                                         }else{
758                                                 $this->configs[$h]['stats'][$i] = number_format((1/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '');
759                                                 //number_format((100/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '')."%";
760                                         }
761                                         fclose($handle);
762                                         if ($config[4] == $size_this && $keep_validating) {
763                                                 $validated_chunks = $i;
764                                         } else {
765                                                 $keep_validating = false;
766                                         }
767                                 } else {
768                                         $this->configs[$h]['stats'][$i] = "0.00";
769                                         //$this->configs[$h]['stats'][$i]="0.00%";
770
771                                 }
772                         }
773                 }
774                 mysql_query("UPDATE file_hash SET validated_chunks = '".mysql_escape_string($validated_chunks)."' WHERE md5_hash = '".mysql_escape_string($h)."'");
775         }
776 }
777
778 function read_config($path, $filename) {
779         if (is_file($path."/".$filename.".InProgress")) {
780                 $config_handle = fopen($path."/".$filename.".InProgress", "r");
781                 $conf_path=$path."/".$filename.".InProgress";
782         } elseif (is_file($path."/".$filename.".Completed" )) {
783                 $config_handle = fopen($path."/".$filename.".Completed", "r");
784                 $conf_path=$path."/".$filename.".Completed";
785         } elseif (is_file($path."/".$filename.".Starting" )) {
786                 $config_handle = fopen($path."/".$filename.".Starting", "r");
787                 $conf_path=$path."/".$filename.".Starting";
788         } elseif (is_file($path."/".$filename.".Processed" )) {
789                 $config_handle = fopen($path."/".$filename.".Processed", "r");
790                 $conf_path=$path."/".$filename.".Processed";
791         } else {
792                 return "Not Found";
793         }
794         $config_content = fread($config_handle, filesize($conf_path));
795         fclose($config_handle);
796         $config = explode("\n", $config_content);
797
798         return $config;
799 //              print_r($config);
800 /*              $file_count = $config[5];
801                 $last=1;
802     for ($i=1; $i<=$file_count; $i++)
803     {
804         $file_part = $path."/SQ".zfill($i,6)."-".$filename;
805         if (is_file($file_part))
806        {
807
808         $handle = fopen($file_part, "rb");
809         $size_this = filesize($file_part);
810                                 //$stats[$i]=round((100/$config[4])*$size_this)."%";
811                                 if ((($size_this==$config[4] && ($last+1)==$i) )|| $i == $config[5]) {
812                                         $merged_file.=fread($handle, filesize($file_part));
813                                         $last = $i;
814                                 }
815         fclose($handle);
816        }
817      }
818      return $merged_file;
819      */
820 }
821
822 function print_files($path, $filename, $tovar=false) {
823         if (strpos($path, './uploads/ftp')) {
824                 $filestring = $path.'/'.$filename;
825                 if (is_file($filestring)) {
826                         $handle = fopen($filestring, "rb");
827                         while (!feof($handle))
828                         {
829                                 print(fread($handle, 1024));
830                                 ob_flush();
831                                 flush();
832                         }
833                 }
834         } else {
835                 if (is_file($path."/".$filename.".InProgress")) {
836                         $config_handle = fopen($path."/".$filename.".InProgress", "r");
837                         $conf_path=$path."/".$filename.".InProgress";
838                 } elseif (is_file($path."/".$filename.".Completed" )) {
839                         $config_handle = fopen($path."/".$filename.".Completed", "r");
840                         $conf_path=$path."/".$filename.".Completed";
841                 } elseif (is_file($path."/".$filename.".Starting" )) {
842                         $config_handle = fopen($path."/".$filename.".Starting", "r");
843                         $conf_path=$path."/".$filename.".Starting";
844                 } elseif (is_file($path."/".$filename.".Processed" )) {
845                         $config_handle = fopen($path."/".$filename.".Processed", "r");
846                         $conf_path=$path."/".$filename.".Processed";
847                 } else{
848                         return "Not Found";
849                 }
850                 $config_content = fread($config_handle, filesize($conf_path));
851                 fclose($config_handle);
852                 $config = explode("\n",$config_content);
853 //              print_r($config);
854                 $file_count = $config[5];
855                 $last = 0;
856                 $last_part_size = ( $config[3] - ( ( $config[5] -1 ) * $config[4] ) );
857                 for ($i=0;$i<=$file_count;$i++)
858                 {
859                         $file_part = $path."/SQ".zfill($i,6)."-".$filename;
860                         if (!is_file($file_part))
861                                 $file_part = $path."/SQ".zfill($i,3)."-".$filename;
862                         if (is_file($file_part))
863                         {
864                                 $handle = fopen($file_part, "rb");
865                                 $size_this = filesize($file_part);
866                                 if ( ( ( $size_this==$config[4] ) && ( ($last+1)==$i ) ) || ( ( $i == $config[5] ) && ( $size_this==$last_part_size ) && ( ($last+1)==$i ) ) ) {
867                                         if ($tovar) {
868                                                 $merged_file.=fread($handle, $size_this);
869                                                 $last = $i;
870                                         } else {
871                                                 while (!feof($handle))
872                                                 {
873                                                         print(fread($handle, 4096));
874                                                 #       @ob_flush();
875                                                 #       @flush();
876                                                 }
877                                                 $last = $i;
878                                         }
879                                 }
880                                 fclose($handle);
881                         }
882                 }
883                 if ($tovar)
884                         return $merged_file;
885         }
886 }
887
888 function check_md5($h) {
889         $return = false;
890         $config = $this->configs[$h];
891         $var = $this->print_files($config['path'], $config[2], true);
892         $hash = md5($var);
893         if ($hash==$config[6])
894                 $return=true;
895
896         return $return;
897 }
898
899 function file_crc($file_string) {
900         //$file_string = file_get_contents($file);
901
902         $crc = crc32($file_string);
903         return sprintf("%u\n", $crc);
904 }
905
906 function file_crc_debug($file) {
907         $file_string = file_get_contents($file);
908
909         $crc = crc32($file_string);
910         return sprintf("%u\n", $crc);
911 }
912
913 function delete_file($h, $s) {
914         $request = $this->get_config($h);
915         if (strpos($request['path'], './uploads/ftp')) {
916                 $filepath=$request['path'].'/'.$request[2];
917                 #remove file
918                 if (is_file($filepath))
919                         @unlink($filepath);
920                 if (is_file($filepath.'.hidden'))
921                         @unlink($filepath.'.hidden');
922         } else {
923                 #remove fileparts
924                 for ($i=0;$i<=$request[5];$i++) {
925                         $part_six   = $request['path']."/SQ".zfill($i,6)."-".$request[2];
926                         $part_three = $request['path']."/SQ".zfill($i,3)."-".$request[2];
927                         if (is_file($part_six))
928                                 @unlink($part_six);
929                         if (is_file($part_three))
930                                 @unlink($part_six);
931                 }
932                 #remove config file
933                 if (is_file($request['path'].'/'.$request[2].'.hidden'))        @unlink($request['path'].'/'.$request[2].'.hidden');
934                 if (is_file($request['path'].'/'.$request[2].'.Completed'))     @unlink($request['path'].'/'.$request[2].'.Completed');
935                 if (is_file($request['path'].'/'.$request[2].'.InProgress'))@unlink($request['path'].'/'.$request[2].'.InProgress');
936                 if (is_file($request['path'].'/'.$request[2].'.Processed'))     @unlink($request['path'].'/'.$request[2].'.Processed');
937                 if (is_file($request['path'].'/'.$request[2].'.Starting'))      @unlink($request['path'].'/'.$request[2].'.Starting');
938         }
939
940         #Update DB
941         $q = "DELETE FROM file_hash WHERE file_hash = '".mysql_escape_string($h)."'";
942         mysql_query($q);
943         $q = "INSERT INTO log (hash,file,action,user_id,user_name,ip,date) VALUES ('".mysql_escape_string($h)."','".mysql_escape_string($filepath)."','delete',".(int)$s['user_id'].",'".mysql_escape_string($s['user_name'])."','".mysql_escape_string($_SERVER['REMOTE_ADDR'])."',NOW())";
944         mysql_query($q);
945
946         #Send debug mail
947         $m_name = $s['user_name'];
948         $m_subject = "Squasher Debug: File Deleted by {$m_name}";
949         $m_body = "File Deleted: \n Requested by: {$m_name} \n File: {$filepath}";
950         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
951 }
952
953 function show_files() {
954
955         $path = "./uploads/";
956
957         if ($dir = opendir($path)) {
958                 $i = 1;
959                 $last = 1;
960                 $files = array();
961                 $files_merged = array();
962                 while (false !== ($file = readdir($dir)))
963                 {
964                         if (($file !== ".") && ($file !== ".."))
965                         {
966                                 $filename = $path.$file;
967                                 $handle = fopen($filename, "rb");
968                                 $size_this = filesize($filename);
969                                 if ($i==1)
970                                         $size_first = $size_this;
971                                 $filecontent = fread($handle, filesize($filename));
972                                 $files[$i++] = $filename;
973                                 $files_merged[$file_base][]=$filename;
974                                 fclose($handle);
975                         }
976                 }
977         }
978         echo "<pre>";
979         print_r($files);
980         print_r($files_merged);
981         echo "</pre>";
982 }
983
984 function set_mime($filename) {
985         $ext_arr = explode('.', $filename);
986         $ext = strtolower(array_pop($ext_arr));
987         switch($ext) {
988                 case 'avi':
989                         $mime = 'video/avi';
990                         break;
991                 case 'mpeg':
992                 case 'mpg':
993                         $mime = 'video/mpeg';                                   //MPEG Video
994                         break;
995                 case 'exe':
996                 case 'bat':
997                 case 'doc':
998                 case 'xls':
999                         $mime = 'application/octet-stream';
1000                         break;
1001                 case 'gif':
1002                         $mime = 'image/gif';                                    //GIF Image
1003                         break;
1004                 case 'jpg':
1005                 case 'jpeg':
1006                         $mime = 'image/jpeg';                                   //JPEG Image
1007                         break;
1008                 case 'png':
1009                         $mime = 'image/png';                                    //PNG Image
1010                         break;
1011                 case 'wav':
1012                 case 'wave':
1013                         $mime = 'audio/wav';                                    //WAV Audio
1014                         break;
1015                 case 'mp3':
1016                         $mime = 'audio/mpeg';                                   //MP3 Audio
1017                         break;
1018                 case 'mov':
1019                         $mime = 'video/mov';                                    //Quicktime Video
1020                         break;
1021                 case 'wmv':
1022                         $mime = 'video/x-ms-wmv';                       //Windows WMV video
1023                         break;
1024                 case 'wma':
1025                         $mime = 'audio/x-ms-wma';                       //Windows WMA audio
1026                         break;
1027                 case 'rm':
1028                         $mime = 'audio/x-realaudio';    //RealPlayer Audio/Video (.rm)
1029                         break;
1030                 case 'ram':
1031                         $mime = 'audio/x-pn-realaudio'; //RealPlayer Audio/Video (.ram)
1032                         break;
1033                 case 'pdf':
1034                         $mime = 'application/pdf';              //PDF Document
1035                         break;
1036                 case 'doc':
1037                         $mime = 'application/msword';   //MS Word .doc file
1038                         break;
1039                 case 'zip':
1040                         $mime = 'application/zip';              //Zip File
1041                         break;
1042                 default:
1043                         $mime = 'application/octet-stream';
1044                         break;
1045         }
1046         //$return['mime']=$mime;
1047         //$return['ext']=$ext;
1048
1049         return $mime;
1050 }
1051
1052 }
1053 // vim: syntax=php ts=4 sw=4 sts=4 sr noet
1054 ?>