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