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