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