eefe829ddbdefd5409e28f6d44605af37178ffb1
[squasher.git] / squasher.class.php
1 <?php
2 require_once("include/connect.inc.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                                 $arr_string .= "['".$value."']";
245                         }
246                 }
247                 $arr_string .= "['__access__']";
248
249                 eval($arr_string." = '".$o->access."';");
250         }
251         return $result;
252 }
253
254 function give_rights($user_id, $type='folderrights') {
255         if ($type=='folderrights')
256                 $this->folderrights = $this->get_rights($user_id);
257         else // $type=='userrights'
258                 $this->userrights = $this->get_rights($user_id);
259 }
260
261 function update_rights($edited_user, $m, $admin_level) {
262         $q = "SELECT count(*) result FROM users WHERE user_id = ".(int)$edited_user." AND user_level < ".(int)$admin_level;
263         $r = mysql_query($q);
264         $o = mysql_fetch_object($r);
265
266         if ($o->result) {
267                 foreach ($m AS $path => $access) {
268                         $p_q = "SELECT count(*) result FROM user_rights WHERE user_id = ".(int)$edited_user." AND folder_path = '".mysql_escape_string($path)."'";
269                         $p_r = mysql_query($p_q);
270                         $p_o = mysql_fetch_object($p_r);
271                         if ($p_o->result == 1)
272                                 mysql_query("UPDATE user_rights SET access = ".(int)$access." WHERE folder_path = '".mysql_escape_string($path)."' AND user_id = ".(int)$edited_user);
273                         if ($p_o->result == 0)
274                                 mysql_query("INSERT INTO user_rights (user_id,folder_path,access) values (".(int)$edited_user.",'".mysql_escape_string($path)."',".(int)$access.") ");
275                 }
276         }
277 }
278
279
280 function show_rights_tree($path, $depth=0, $userid=0) {
281
282         if ($userid==0)
283                 return false;
284         if ($depth==0)
285                 $this->give_rights($userid, 'userrights');
286
287         // access = 0 --deny-all
288         // access = 1 --allow-dir-only
289         // access = 2 --allow-inc-subs
290
291         $layout = '';
292         $style = '';
293
294         for ($i=0; $i<$depth; $i++)
295                 $layout .= " ";
296         if ($dir = opendir($path)) {
297                 $layout .= "<div style='clear:both;' >\n";
298                 $f = 0;
299                 while (false !== ($file = readdir($dir))) {
300                         $files_array[] = $file;
301                 }
302                 asort($files_array);
303                 foreach ($files_array as $f_index => $file) {
304                         if (($file{0} !== ".") && ($file !== ".."))
305                         {
306                                 $filename = $path."/".$file;
307                                 if (!is_file($filename) && $this->got_rights_array($filename) > 0) {
308                                         $f++;
309                                         if (substr($filename,0,strlen($this->basepath))==$this->basepath)
310                                                 $name = substr($filename,strlen($this->basepath));
311                                         $check = $this->got_rights_array_admin($filename, $this->userrights);
312                                         $check_all = '';
313                                         $check_allow = '';
314                                         $check_deny = '';
315                                         switch($check) {
316                                                 case 2:
317                                                         $check_all = 'checked';
318                                                         break;
319                                                 case 1:
320                                                         $check_allow = 'checked';
321                                                         break;
322                                                 case 0:
323                                                 default:
324                                                         $check_deny = 'checked';
325                                                         break;
326                                         }
327
328                                         if ($f==1)
329                                                 $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).";}";
330                                         if ($f==1)
331                                                 $layout .= "<div class='depth".$depth."'>";
332                                         $layout .= "<div class='white_border' >".$file."</div>\n";
333                                         $layout .= "<div class='check_deny'><input name='m[".$name."]' value=0 type=radio ".$check_deny."></div>\n";
334                                         $layout .= "<div class='check_allow'><input name='m[".$name."]' value=1 type=radio ".$check_allow."></div>\n";
335                                         $layout .= "<div class='check_all'><input name='m[".$name."]' value=2 type=radio ".$check_all."></div>\n";
336                                         $sub_return = $this->show_rights_tree($filename,$depth+1,$userid);
337                                         if (is_array($style) && is_array($sub_return['style']))
338                                                 $style = $style + $sub_return['style'];
339                                         $layout .= $sub_return['layout'];
340                                 }
341                         }
342                 }
343                 if ($f!=0)
344                         $layout .= "</div>";
345                 $layout .= "</div>\n";
346         }
347
348         $return['style'] = $style;
349         $return['layout'] = $layout;
350
351         return $return;
352 }
353
354 function got_rights_array($needle, $haystack='', $c=0) {
355         // used by:
356         // - read_single_file
357         // - read_directory
358         // - show_rights_tree
359
360         if (!is_array($haystack))
361                 $haystack = $this->folderrights;
362         if (substr($needle, 0, strlen($this->basepath)) == $this->basepath)
363                 $needle=substr($needle,strlen($this->basepath));
364
365         // check root rights
366         if ($needle{0} == '/' && @$haystack['__access__'] == 2 )
367                 return 2;
368
369         // remove leading /
370         if ($needle{0}=='/')
371                 $needle = substr($needle, 1);
372
373         $needle_arr = explode('/', $needle);
374         $n = count($needle_arr);
375         $d = $c + 1;
376
377         foreach ($haystack as $k => $v) {
378                 if ($needle_arr[$c] == $k) {
379                         if (!is_array(@$v['__access__'])) {
380                                 if ($v['__access__'] == 2             ) return 2;
381                                 if ($v['__access__'] == 1 && $d == $n ) return 1;
382                                 if ($v['__access__'] == 0 && $d == $n ) return 0;
383                         } else {
384                                 $return = $this->got_rights_array($needle, $v, $d);
385                         }
386                 }
387         }
388         return $return;
389 }
390
391 function got_rights_array_admin($needle, $haystack='', $c=0) {
392         // used by:
393         // - show_rights_tree
394
395         if (!is_array($haystack))
396                 $haystack = $this->folderrights;
397         if (substr($needle, 0, strlen($this->basepath)) == $this->basepath)
398                 $needle = substr($needle, strlen($this->basepath));
399
400         // check root rights
401         if ($needle{0} == '/' && @$haystack['__access__'] == 2 )
402                 return 2;
403
404         // remove leading /
405         if ($needle{0} == '/')
406                 $needle = substr($needle, 1);
407
408         $needle_arr = explode('/', $needle);
409         $n = count($needle_arr);
410         $d = $c + 1;
411         $return = 0;
412
413         if ($c < $n) {
414                 if (@$haystack['__access__'] == 2)
415                         return $haystack['__access__'];
416                 if (is_array($haystack[$needle_arr[$c]]))
417                         $return = $this->got_rights_array_admin($needle, $haystack[$needle_arr[$c]], $d);
418         } else {
419                 if (@$haystack['__access__'] > 0)
420                         $return = $haystack['__access__'];
421         }
422
423         return $return;
424 }
425
426 function got_rights_array_recursive($needle, $haystack='', $c=0) {
427         // used by:
428         // - read_directory, for subfolders
429
430         if (!is_array($haystack))
431                 $haystack = $this->folderrights;
432         if (substr($needle, 0, strlen($this->basepath)) == $this->basepath)
433                 $needle=substr($needle, strlen($this->basepath));
434
435         // check root rights
436         if($needle{0}=='/' && @$haystack['__access__'] == 2 )
437                 return 2;
438
439         // check folder rights
440         if($needle{0}=='/')
441                 $needle=substr($needle,1);
442
443         $needle_arr = explode('/', $needle);
444         $n = count($needle_arr);
445         $d = $c + 1;
446         $return = 0;
447
448         foreach($haystack as $k => $v) {
449                 if ($c < sizeof($needle_arr) && $needle_arr[$c] == $k) {
450                         if ($c < $n) {
451                                 if ($v['__access__'] == 2)
452                                         $return = $return + $v['__access__'];
453                                 $return = $return + $this->got_rights_array_recursive($needle, $v, $d);
454                         } else {
455                                 $return = $return + $this->in_array_recursive($v);
456                         }
457                 } elseif ($c == $n) {
458                         $return = $return + $v['__access__'];
459                         if($k != '__access__')$return = $return + $this->in_array_recursive($v);
460                 }
461         }
462
463         return $return;
464 }
465
466 function in_array_recursive($haystack) {
467         $return = 0;
468         if (is_array($haystack)) {
469                 foreach ($haystack as $key1 => $value1) {
470                         if (is_array($value1)) {
471                                 $return = $return + $this->in_array_recursive($value1);
472                         }
473                         elseif ($value1 > 0) {
474                                 return $value1;
475                         }
476                 }
477         }
478         return $return;
479 }
480
481 function read_single_file($path, $file) {
482         $filename = $path."/".$file;
483         $i = 0;
484         if ($this->got_rights_array($path) > 0) {
485                 if (is_file($filename.'.Completed'))
486                         $file.='.Completed';
487                 if (is_file($filename.'.InProgress'))
488                         $file.='.InProgress';
489                 if (is_file($filename.'.Starting'))
490                         $file.='.Starting';
491                 if (is_file($filename.'.Processed'))
492                         $file.='.Processed';
493                 $filename = $path . "/" . $file;
494                 $handle = @fopen($filename, "rb");
495                 if (strpos($file,'.Completed'))
496                         $ext='.Completed';
497                 if (strpos($file,'.InProgress'))
498                         $ext='.InProgress';
499                 if (strpos($file,'.Starting'))
500                         $ext='.Starting';
501                 if (strpos($file,'.Processed'))
502                         $ext='.Processed';
503                 $sub_pos = strpos($file, $ext);
504                 $base_name = substr($file, 0, $sub_pos);
505                 $filecontent = @fread($handle, @filesize($filename));
506                 $config[$i] = explode("\r\n", $filecontent);
507                 /***
508                 *       $config:: array
509                 *       [0]     ->      versioncode
510                 *       [1]     ->      date&time
511                 *       [2]     ->      filename
512                 *       [3]     ->      filesize
513                 *       [4]     ->      chunksize
514                 *       [5]     ->      chunkcount
515                 *       [6]     ->      CRC32 checksum
516                 ***/
517                 if (@filesize($filename) > 0) {
518                         $h = md5($path."/".$config[$i][2]);
519                         $this->configs[$h] = $config[$i];
520                         $this->configs[$h]['squashed'] = true;
521                         $this->configs[$h]['path'] = $path;
522                         $this->configs[$h]['status'] = substr($ext, 1);
523                         $this->configs[$h]['mime'] = $this->set_mime($this->configs[$h][2]);
524                         $this->configs[$h]['hidden'] = (is_file($path.'/'.$base_name.'.hidden')) ? true : false ;
525                         //to prevent dates of 1-1-1970 we set te dates of the config file
526                         $this->configs[$h]['added'] = filectime($filename);
527                         $this->configs[$h]['lastchange'] = filemtime($filename);
528                         fclose($handle);
529                         $this->populate_stats($path, $h);
530                         //insert hash in db
531                         #$this->update_hash($h,$path."/".$config[$i][2]);
532                         //check stats
533                         $this->check_stats($h);
534                 }
535         }
536 }
537
538
539 function read_directory($path, $getsubs=false, $getfirstfiles=true, $getdeepfiles=true, $populate=true) {
540
541         if ($dir = @opendir($path)) {
542                 $i = 0;
543                 $last = 1;
544                 while (false !== ($file = readdir($dir))) {
545                         if (($file{0} !== ".") && substr($file,0,1) !== "SQ") {
546                                 $filename = $path."/".$file;
547                                 if (!is_file($filename) && strpos($filename, './uploads/recieving')===false) {
548                                         if ($getsubs) {
549                                                 if ($this->got_rights_array_recursive($filename) > 0) {
550                                                         $key = substr($path, strlen($this->basepath)) . '/' . $file;
551                                                         $this->subfolders[$key] = $file;
552                                                 }
553                                         }
554                                         if ($getdeepfiles)
555                                                 $this->read_directory($filename, false, $getdeepfiles, $getdeepfiles, $populate);
556                                 } elseif (strpos($filename,'./uploads/ftp')) { //ftp files
557                                         if ($this->got_rights_array($path) > 0 && !strpos($filename, '.hidden') ) {
558                                                 $h = md5($filename);
559                                                 $name_only = substr($filename, strlen($path)+1);
560                                                 $file_structure = explode('.', $name_only);
561                                                 $ext = array_pop($file_structure);
562                                                 $base_name = array_pop($file_structure);
563                                                 $this->configs[$h]['path'] = $path;
564                                                 $this->configs[$h][0] = 'manual ftp';
565                                                 $this->configs[$h][2] = $name_only;
566                                                 $this->configs[$h][3] = filesize($filename);
567                                                 $this->configs[$h]['added'] = filectime($filename);
568                                                 $this->configs[$h]['lastchange'] = filemtime($filename);
569                                                 $this->configs[$h]['status'] = 'unknown';
570                                                 $this->configs[$h]['squashed'] = false;
571                                                 $this->configs[$h]['mime'] = $this->set_mime($name_only);
572                                                 $this->configs[$h]['hidden'] = (is_file($path.'/'.$base_name.'.hidden')) ? true : false ;
573                                         }
574                                 } elseif ($getfirstfiles) {
575                                         //squashed files
576                                         if ($this->got_rights_array($path) > 0) {
577                                                 if (strpos($filename, '.Completed') || strpos($filename, '.InProgress') || strpos($filename, '.Starting') || strpos($filename, '.Processed')) {
578                                                         $i++;
579                                                         $handle = @fopen($filename, "rb");
580                                                         if (strpos($file,'.Completed'))
581                                                                 $ext='.Completed';
582                                                         if (strpos($file,'.InProgress'))
583                                                                 $ext='.InProgress';
584                                                         if (strpos($file,'.Starting'))
585                                                                 $ext='.Starting';
586                                                         if (strpos($file,'.Processed'))
587                                                                 $ext='.Processed';
588                                                         $sub_pos = strpos($file, $ext);
589                                                         $base_name = substr($file, 0, $sub_pos);
590                                                         $filecontent = @fread($handle, @filesize($filename));
591                                                         $config[$i] = explode("\r\n", $filecontent);
592
593                                                         /***
594                                                         *       $config:: array
595                                                         *       [0]     ->      versioncode
596                                                         *       [1]     ->      date&time
597                                                         *       [2]     ->      filename
598                                                         *       [3]     ->      filesize
599                                                         *       [4]     ->      chunksize
600                                                         *       [5]     ->      chunkcount
601                                                         *       [6]     ->      CRC32 checksum
602                                                         ***/
603
604                                                         if (@filesize($filename) > 0) {
605                                                                 $h = md5($path."/".$config[$i][2]);
606                                                                 $this->configs[$h] = $config[$i];
607                                                                 $this->configs[$h]['squashed'] = true;
608                                                                 $this->configs[$h]['path'] = $path;
609                                                                 $this->configs[$h]['status'] = substr($ext, 1);
610                                                                 $this->configs[$h]['mime'] = $this->set_mime($this->configs[$h][2]);
611                                                                 $this->configs[$h]['hidden'] = (is_file($path.'/'.$base_name.'.hidden')) ? true : false ;
612                                                                 //to prevent dates of 1-1-1970 we set te dates of the config file
613                                                                 $this->configs[$h]['added'] = filectime($filename);
614                                                                 $this->configs[$h]['lastchange'] = filemtime($filename);
615                                                                 fclose($handle);
616                                                                 $this->populate_stats($path, $h);
617                                                                 //insert hash in db
618                                                                 $this->update_hash($h, $path."/".$config[$i][2]);
619                                                                 //check stats
620                                                                 $this->check_stats($h);
621                                                         }
622                                                 }
623                                         }
624                                 }
625                         }
626                 }
627         }
628 }
629
630 function check_stats($h) {
631         $config = $this->get_config($h);
632         $count = @array_sum($config['stats']);
633         if ($config['status']=='Completed' && $count != $config[5]) {
634                 $filepath=$config['path'].'/'.$config[2];
635                 if ($this->history[$h]['completed']=="1") {
636                         //don't display broken file, remove it instead
637                         unlink($config['path'].'/'.$config[2].'.Completed');
638                         unset($this->configs[$h]);
639
640                         if (!$count)
641                                 $count = 0;
642                         $m_subject = "Squasher Debug: File Removed";
643                         $m_body = "Upload removed: \n File: ".$config['path']."/".$config[2]." \n Status: ".$config['status']." \n Chunks: ".$count." out of ".$config[5];
644                         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
645                         $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())";
646                         mysql_query($qlog);
647                 } else {
648                         //do move
649                         rename($config['path'].'/'.$config[2].'.Completed', $config['path'].'/'.$config[2].'.InProgress');
650                         $this->configs[$h]['status'] = 'InProgress';
651
652                         //mail n4m
653                         if (!$count)
654                                 $count = 0;
655                         $m_subject = "Squasher Debug: Upload Error";
656                         $m_body = "Upload error: \n File: ".$config['path']."/".$config[2]." \n Status: ".$config['status']." \n Chunks: ".$count." out of ".$config[5];
657                         mail('support@netformatie.nl', $m_subject, $m_body, "From: squasher@netformatie.nl");
658                         mail('jan@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
659                         mail('joop@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
660                         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
661
662                         //do sms
663                         //wget -o/dev/null "http://www.mollie.nl/xml/sms/?username=netformatie&password=SMSdolsi&originator=Netformatie&recipients=${ENGINEER}&message=${CALLERID}";
664
665                         //mail RO
666                         $ship = explode('/',$config['path']);
667                         if ($ship[2] == 'myas' || $ship[2] == 'myez' || $ship[2] == 'myrw')
668                                 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");
669
670                         $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())";
671                         mysql_query($qlog);
672
673                 }
674         } elseif ($config['status']=='Completed' && $count == $config[5]) {
675                 if ($this->history[$h]['completed']==0)
676                         mysql_query("UPDATE file_hash SET completed = 1 WHERE md5_hash = '".mysql_escape_string($h)."'");
677         }
678 }
679
680 function update_hash($hash, $path) {
681         $check_hash_query = "select * from file_hash where md5_hash = '".$hash."'";
682         $check_hash_result = mysql_query($check_hash_query);
683         if(mysql_num_rows($check_hash_result) == 0) {
684                 $insert_hash_query = "INSERT INTO file_hash (md5_hash,file) values ('".mysql_escape_string($hash)."','".mysql_escape_string($path)."')";
685                 mysql_query($insert_hash_query);
686         }
687 }
688
689 function path_to_arraystring($path, $arrayname) {
690         $path_values = explode('/', $path);
691         $return = $arrayname;
692         foreach ($path_values AS $key => $value) {
693                 if ($value != '.' && $value != '')
694                         $return.= "['".$value."']";
695         }
696         return $return;
697 }
698
699 function populate_stats($path, $h) {
700         /***
701         *       $config:: array
702         *       [0]     ->      versioncode
703         *       [1]     ->      date&time
704         *       [2]     ->      filename
705         *       [3]     ->      filesize
706         *       [4]     ->      chunksize
707         *       [5]     ->      chunkcount
708         *       [6]     ->      CRC32 checksum
709         ***/
710         $config = $this->configs[$h];
711
712         $q = "SELECT * FROM file_hash WHERE md5_hash = '".mysql_escape_string($h)."'";
713         $r = mysql_query($q);
714         $o = mysql_fetch_object($r);
715         $validated_chunks = $o->validated_chunks;
716
717         if ($this->history[$h]['completed']=="1") {
718                 $file_part = $path."/SQ".zfill(1,6)."-".$config[2];
719                 if (!is_file($file_part))
720                         $file_part = $path."/SQ".zfill(1,3)."-".$config[2];
721                 if (is_file($file_part)) {
722                         $this->configs[$h]['added'] = filectime($file_part);
723                         $file_part = $path."/SQ".zfill($config[5],6)."-".$config[2];
724                         if (!is_file($file_part))
725                                 $file_part = $path."/SQ".zfill($config[5],3)."-".$config[2];
726                         if (is_file($file_part))
727                                 $this->configs[$h]['lastchange'] = filemtime($file_part);
728                         for ($i=1; $i<=$config[5]; $i++)
729                                 $this->configs[$h]['stats'][$i] = "1.00";
730                 } else {
731                         //failsafe voor verwijderde bestanden
732                         mysql_query("UPDATE file_hash SET completed = 0 WHERE md5_hash = '".mysql_escape_string($h)."'");
733                 }
734         } else {
735                 $keep_validating = true;
736                 for ($i=1; $i<=$config[5]; $i++) {
737                         if ($validated_chunks > $i) {
738                                 $this->configs[$h]['stats'][$i]="1.00";
739                         } else {
740                                 $file_part = $path."/SQ".zfill($i,6)."-".$config[2];
741                                 if (!is_file($file_part))
742                                         $file_part = $path."/SQ".zfill($i,3)."-".$config[2];
743                                 if (is_file($file_part)) {
744                                         $handle = fopen($file_part, "rb");
745                                         $size_this = filesize($file_part);
746                                         $added = filectime($file_part);
747                                         $last_changed = filemtime($file_part);
748                                         if ($this->configs[$h]['added'] > $added || !is_numeric($this->configs[$h]['added']))
749                                                 $this->configs[$h]['added'] = $added;
750                                         if ($this->configs[$h]['lastchange'] < $last_changed)
751                                                 $this->configs[$h]['lastchange'] = $last_changed;
752                                         if ($i != $config[5]) {
753                                                 $this->configs[$h]['stats'][$i] = number_format((1/$config[4])*$size_this, 2, '.', '');
754                                         //number_format((100/$config[4])*$size_this, 2, '.', '')."%";
755                                         }else{
756                                                 $this->configs[$h]['stats'][$i] = number_format((1/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '');
757                                                 //number_format((100/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '')."%";
758                                         }
759                                         fclose($handle);
760                                         if ($config[4] == $size_this && $keep_validating) {
761                                                 $validated_chunks = $i;
762                                         } else {
763                                                 $keep_validating = false;
764                                         }
765                                 } else {
766                                         $this->configs[$h]['stats'][$i] = "0.00";
767                                         //$this->configs[$h]['stats'][$i]="0.00%";
768
769                                 }
770                         }
771                 }
772                 mysql_query("UPDATE file_hash SET validated_chunks = '".mysql_escape_string($validated_chunks)."' WHERE md5_hash = '".mysql_escape_string($h)."'");
773         }
774 }
775
776 function read_config($path, $filename) {
777         if (is_file($path."/".$filename.".InProgress")) {
778                 $config_handle = fopen($path."/".$filename.".InProgress", "r");
779                 $conf_path=$path."/".$filename.".InProgress";
780         } elseif (is_file($path."/".$filename.".Completed" )) {
781                 $config_handle = fopen($path."/".$filename.".Completed", "r");
782                 $conf_path=$path."/".$filename.".Completed";
783         } elseif (is_file($path."/".$filename.".Starting" )) {
784                 $config_handle = fopen($path."/".$filename.".Starting", "r");
785                 $conf_path=$path."/".$filename.".Starting";
786         } elseif (is_file($path."/".$filename.".Processed" )) {
787                 $config_handle = fopen($path."/".$filename.".Processed", "r");
788                 $conf_path=$path."/".$filename.".Processed";
789         } else {
790                 return "Not Found";
791         }
792         $config_content = fread($config_handle, filesize($conf_path));
793         fclose($config_handle);
794         $config = explode("\n", $config_content);
795
796         return $config;
797 //              print_r($config);
798 /*              $file_count = $config[5];
799                 $last=1;
800     for ($i=1; $i<=$file_count; $i++)
801     {
802         $file_part = $path."/SQ".zfill($i,6)."-".$filename;
803         if (is_file($file_part))
804        {
805
806         $handle = fopen($file_part, "rb");
807         $size_this = filesize($file_part);
808                                 //$stats[$i]=round((100/$config[4])*$size_this)."%";
809                                 if ((($size_this==$config[4] && ($last+1)==$i) )|| $i == $config[5]) {
810                                         $merged_file.=fread($handle, filesize($file_part));
811                                         $last = $i;
812                                 }
813         fclose($handle);
814        }
815      }
816      return $merged_file;
817      */
818 }
819
820 function print_files($path, $filename, $tovar=false) {
821         if (strpos($path, './uploads/ftp')) {
822                 $filestring = $path.'/'.$filename;
823                 if (is_file($filestring)) {
824                         $handle = fopen($filestring, "rb");
825                         while (!feof($handle))
826                         {
827                                 print(fread($handle, 1024));
828                                 ob_flush();
829                                 flush();
830                         }
831                 }
832         } else {
833                 if (is_file($path."/".$filename.".InProgress")) {
834                         $config_handle = fopen($path."/".$filename.".InProgress", "r");
835                         $conf_path=$path."/".$filename.".InProgress";
836                 } elseif (is_file($path."/".$filename.".Completed" )) {
837                         $config_handle = fopen($path."/".$filename.".Completed", "r");
838                         $conf_path=$path."/".$filename.".Completed";
839                 } elseif (is_file($path."/".$filename.".Starting" )) {
840                         $config_handle = fopen($path."/".$filename.".Starting", "r");
841                         $conf_path=$path."/".$filename.".Starting";
842                 } elseif (is_file($path."/".$filename.".Processed" )) {
843                         $config_handle = fopen($path."/".$filename.".Processed", "r");
844                         $conf_path=$path."/".$filename.".Processed";
845                 } else{
846                         return "Not Found";
847                 }
848                 $config_content = fread($config_handle, filesize($conf_path));
849                 fclose($config_handle);
850                 $config = explode("\n",$config_content);
851 //              print_r($config);
852                 $file_count = $config[5];
853                 $last = 0;
854                 $last_part_size = ( $config[3] - ( ( $config[5] -1 ) * $config[4] ) );
855                 for ($i=0;$i<=$file_count;$i++)
856                 {
857                         $file_part = $path."/SQ".zfill($i,6)."-".$filename;
858                         if (!is_file($file_part))
859                                 $file_part = $path."/SQ".zfill($i,3)."-".$filename;
860                         if (is_file($file_part))
861                         {
862                                 $handle = fopen($file_part, "rb");
863                                 $size_this = filesize($file_part);
864                                 if ( ( ( $size_this==$config[4] ) && ( ($last+1)==$i ) ) || ( ( $i == $config[5] ) && ( $size_this==$last_part_size ) && ( ($last+1)==$i ) ) ) {
865                                         if ($tovar) {
866                                                 $merged_file.=fread($handle, $size_this);
867                                                 $last = $i;
868                                         } else {
869                                                 while (!feof($handle))
870                                                 {
871                                                         print(fread($handle, 4096));
872                                                 #       @ob_flush();
873                                                 #       @flush();
874                                                 }
875                                                 $last = $i;
876                                         }
877                                 }
878                                 fclose($handle);
879                         }
880                 }
881                 if ($tovar)
882                         return $merged_file;
883         }
884 }
885
886 function check_md5($h) {
887         $return = false;
888         $config = $this->configs[$h];
889         $var = $this->print_files($config['path'], $config[2], true);
890         $hash = md5($var);
891         if ($hash==$config[6])
892                 $return=true;
893
894         return $return;
895 }
896
897 function file_crc($file_string) {
898         //$file_string = file_get_contents($file);
899
900         $crc = crc32($file_string);
901         return sprintf("%u\n", $crc);
902 }
903
904 function file_crc_debug($file) {
905         $file_string = file_get_contents($file);
906
907         $crc = crc32($file_string);
908         return sprintf("%u\n", $crc);
909 }
910
911 function delete_file($h, $s) {
912         $request = $this->get_config($h);
913         if (strpos($request['path'], './uploads/ftp')) {
914                 $filepath=$request['path'].'/'.$request[2];
915                 #remove file
916                 if (is_file($filepath))
917                         @unlink($filepath);
918                 if (is_file($filepath.'.hidden'))
919                         @unlink($filepath.'.hidden');
920         } else {
921                 #remove fileparts
922                 for ($i=0;$i<=$request[5];$i++) {
923                         $part_six   = $request['path']."/SQ".zfill($i,6)."-".$request[2];
924                         $part_three = $request['path']."/SQ".zfill($i,3)."-".$request[2];
925                         if (is_file($part_six))
926                                 @unlink($part_six);
927                         if (is_file($part_three))
928                                 @unlink($part_six);
929                 }
930                 #remove config file
931                 if (is_file($request['path'].'/'.$request[2].'.hidden'))        @unlink($request['path'].'/'.$request[2].'.hidden');
932                 if (is_file($request['path'].'/'.$request[2].'.Completed'))     @unlink($request['path'].'/'.$request[2].'.Completed');
933                 if (is_file($request['path'].'/'.$request[2].'.InProgress'))@unlink($request['path'].'/'.$request[2].'.InProgress');
934                 if (is_file($request['path'].'/'.$request[2].'.Processed'))     @unlink($request['path'].'/'.$request[2].'.Processed');
935                 if (is_file($request['path'].'/'.$request[2].'.Starting'))      @unlink($request['path'].'/'.$request[2].'.Starting');
936         }
937
938         #Update DB
939         $q = "DELETE FROM file_hash WHERE file_hash = '".mysql_escape_string($h)."'";
940         mysql_query($q);
941         $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())";
942         mysql_query($q);
943
944         #Send debug mail
945         $m_name = $s['user_name'];
946         $m_subject = "Squasher Debug: File Deleted by {$m_name}";
947         $m_body = "File Deleted: \n Requested by: {$m_name} \n File: {$filepath}";
948         mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
949 }
950
951 function show_files() {
952
953         $path = "./uploads/";
954
955         if ($dir = opendir($path)) {
956                 $i = 1;
957                 $last = 1;
958                 $files = array();
959                 $files_merged = array();
960                 while (false !== ($file = readdir($dir)))
961                 {
962                         if (($file !== ".") && ($file !== ".."))
963                         {
964                                 $filename = $path.$file;
965                                 $handle = fopen($filename, "rb");
966                                 $size_this = filesize($filename);
967                                 if ($i==1)
968                                         $size_first = $size_this;
969                                 $filecontent = fread($handle, filesize($filename));
970                                 $files[$i++] = $filename;
971                                 $files_merged[$file_base][]=$filename;
972                                 fclose($handle);
973                         }
974                 }
975         }
976         echo "<pre>";
977         print_r($files);
978         print_r($files_merged);
979         echo "</pre>";
980 }
981
982 function set_mime($filename) {
983         $ext_arr = explode('.', $filename);
984         $ext = strtolower(array_pop($ext_arr));
985         switch($ext) {
986                 case 'avi':
987                         $mime = 'video/avi';
988                         break;
989                 case 'mpeg':
990                 case 'mpg':
991                         $mime = 'video/mpeg';                                   //MPEG Video
992                         break;
993                 case 'exe':
994                 case 'bat':
995                 case 'doc':
996                 case 'xls':
997                         $mime = 'application/octet-stream';
998                         break;
999                 case 'gif':
1000                         $mime = 'image/gif';                                    //GIF Image
1001                         break;
1002                 case 'jpg':
1003                 case 'jpeg':
1004                         $mime = 'image/jpeg';                                   //JPEG Image
1005                         break;
1006                 case 'png':
1007                         $mime = 'image/png';                                    //PNG Image
1008                         break;
1009                 case 'wav':
1010                 case 'wave':
1011                         $mime = 'audio/wav';                                    //WAV Audio
1012                         break;
1013                 case 'mp3':
1014                         $mime = 'audio/mpeg';                                   //MP3 Audio
1015                         break;
1016                 case 'mov':
1017                         $mime = 'video/mov';                                    //Quicktime Video
1018                         break;
1019                 case 'wmv':
1020                         $mime = 'video/x-ms-wmv';                       //Windows WMV video
1021                         break;
1022                 case 'wma':
1023                         $mime = 'audio/x-ms-wma';                       //Windows WMA audio
1024                         break;
1025                 case 'rm':
1026                         $mime = 'audio/x-realaudio';    //RealPlayer Audio/Video (.rm)
1027                         break;
1028                 case 'ram':
1029                         $mime = 'audio/x-pn-realaudio'; //RealPlayer Audio/Video (.ram)
1030                         break;
1031                 case 'pdf':
1032                         $mime = 'application/pdf';              //PDF Document
1033                         break;
1034                 case 'doc':
1035                         $mime = 'application/msword';   //MS Word .doc file
1036                         break;
1037                 case 'zip':
1038                         $mime = 'application/zip';              //Zip File
1039                         break;
1040                 default:
1041                         $mime = 'application/octet-stream';
1042                         break;
1043         }
1044         //$return['mime']=$mime;
1045         //$return['ext']=$ext;
1046
1047         return $mime;
1048 }
1049
1050 function embed_video($h) {
1051         /*JASPER FIX, use config->systemurl */
1052                 ?>
1053       <!-- begin embedded WindowsMedia file... -->
1054       <table border='0' cellpadding='0' align="center">
1055       <tr><td>
1056       <OBJECT id='mediaPlayer'
1057       classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'
1058       codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'
1059       standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>
1060       <param name='fileName' value="http://master.squasher.netformatie.nl/?x=asx&f=<?=$h;?>">
1061       <param name='animationatStart' value='true'>
1062       <param name='transparentatStart' value='true'>
1063       <param name='autoStart' value="true">
1064       <param name='showControls' value="true">
1065       <param name='loop' value="true">
1066                         <param name="BufferingTime" value="3">
1067       <EMBED type='application/x-mplayer2'
1068         pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'
1069         id='mediaPlayer' name='mediaPlayer' autosize='1'
1070         bgcolor='darkblue' showcontrols="true" showtracker='-1'
1071         showdisplay='0' showstatusbar='-1' videoborder3d='-1' width='480' height='320'
1072         src="http://master.squasher.netformatie.nl/?x=asx&f=<?=$h;?>" autostart="true" designtimesp='5311' loop="true">
1073       </EMBED>
1074       </OBJECT>
1075       </td></tr>
1076       <!-- ...end embedded WindowsMedia file -->
1077         <!-- begin link to launch external media player... -->
1078         <tr><td align='center'>
1079         <a href="http://master.squasher.netformatie.nl/?x=asx&f=<?=$h;?>" style='font-size: 85%;' target='_blank'>Launch in external player</a>
1080         <!-- ...end link to launch external media player... -->
1081         </td></tr>
1082       </table>
1083                 <?
1084         }
1085
1086 function create_playlist($h, $t='asx', $title='Title') {
1087         switch ($t) {
1088
1089                 case 'asx':
1090
1091                         header('Content-Disposition: attachment; filename="stream.asx"');
1092                         echo '<ASX version="3.0">
1093 <title>Squasher Streaming Video</title>
1094         <Entry>
1095                 <title>Video Stream</title>
1096                 <ref HREF="http://master.squasher.netformatie.nl/?a=x&f='.$h.'"/>
1097         </Entry>
1098 </ASX>';
1099
1100                         break;
1101
1102                 case 'vlc':
1103                         header('Content-Disposition: attachment; filename="stream.'.$t.'"');
1104                         echo '#EXTM3U
1105 #EXTINF:-1,Squasher Streaming Video - '.$title.'
1106 http://master.squasher.netformatie.nl/?a=x&f='.$h.'';
1107
1108                         break;
1109
1110                 case 'm3u':
1111                 default:
1112                         header('Content-Disposition: attachment; filename="stream.m3u"');
1113                         echo '#EXTM3U
1114 #EXTINF:-1,Squasher Streaming Video - '.$title.'
1115 http://master.squasher.netformatie.nl/?a=x&f='.$h.'';
1116
1117                         break;
1118                 }
1119         }
1120 }
1121 // vim: syntax=php ts=4 sw=4 sts=4 sr noet
1122 ?>