2 require_once("../config.php");
4 function zfill($n, $a) {
5 return str_repeat("0", max(0,$a-strlen($n))) . $n;
8 function named_records_sort($named_recs, $order_by, $reverse=false, $flags=0) {
10 foreach ($named_recs as $key => $fields)
11 $named_hash[$key] = $fields[$order_by];
14 arsort($named_hash,$flags=0) ;
16 asort($named_hash, $flags=0);
18 $sorted_records = array();
19 foreach($named_hash as $key => $val)$sorted_records[$key] = $named_recs[$key];
21 return $sorted_records;
24 function validate_user($username, $password, $salt) {
26 $creds['validated'] = false;
27 $query="SELECT * FROM users WHERE user_name = '".$db->real_escape_string($username)."'";
28 $q_result = $db->query($query);
29 while ($fetched_object = mysqli_fetch_object($q_result)) {
30 if (md5($fetched_object->user_pass.$salt) == $password) {
32 $creds['user_id'] = $fetched_object->user_id;
33 $creds['user_name'] = $fetched_object->user_name;
34 $creds['user_level'] = $fetched_object->user_level;
35 $creds['validated'] = true;
36 $_SESSION['creds'] = $creds;
37 log_event('login', null);
40 $_SESSION['creds'] = $creds;
41 return $creds['validated'];
45 function get_smarty() {
46 require_once(SQUASHER_SMARTY_SOURCE); // See config.php
49 $smarty->setTemplateDir(SQUASHER_SMARTY_TEMPLATES)
50 ->setCompileDir(SQUASHER_SMARTY_TEMPLATES_C)
51 ->setCacheDir(SQUASHER_SMARTY_CACHE);
57 function log_event($action, $filename, $hash=null, $debugmsg=null) {
60 $hash = str_repeat("0",32);
62 if ($debugmsg!==null) {
64 $user_name = 'squasher-web';
67 $user_id = $_SESSION['creds']['user_id'];
68 $user_name = $_SESSION['creds']['user_name'];
69 $ip = $_SERVER['REMOTE_ADDR'];
72 $hash = $hash===null ? 'NULL' : "'".$db->real_escape_string($hash)."'";
73 $filename = "'".$db->real_escape_string($filename)."'";
74 $action = "'".$db->real_escape_string($action)."'";
75 $user_name = "'". $db->real_escape_string($user_name)."'";
76 $ip = "'". $db->real_escape_string($ip)."'";
78 @$db->query("INSERT INTO log (hash,file,action,user_id,user_name,ip,date) VALUES ($hash, $filename, $action, $user_id, $user_name, $ip, NOW())");
84 var $configs = array();
86 var $subfolders = array();
89 var $history = array();
91 function get_configs() {
92 return $this->configs;
95 function subfolders() {
96 return $this->subfolders;
99 function get_config($h) {
101 return $this->configs[$h];
104 function folderrights() {
105 return $this->folderrights;
108 function userrights() {
109 return $this->userrights;
112 function update_history() {
113 $q="SELECT md5_hash,file,completed,checked FROM file_hash";
114 $r=$this->db->query($q);
115 while($o=mysqli_fetch_object($r)) {
116 $this->history[$o->md5_hash]['file']=$o->file;
117 $this->history[$o->md5_hash]['completed']=$o->completed;
118 $this->history[$o->md5_hash]['checked']=$o->checked;
122 function get_users($user_level) {
123 $q = "SELECT * FROM users";
124 if ($user_level<200) // super user have no restrictions at all
125 $q .= " WHERE user_level < ".$user_level;
126 $q .= " ORDER BY user_name ASC";
127 $r = $this->db->query($q);
130 while ($o = mysqli_fetch_object($r)) {
131 $return[$o->user_id]['id'] = $o->user_id;
132 $return[$o->user_id]['name'] = $o->user_name;
133 $return[$o->user_id]['level'] = $o->user_level;
134 $return[$o->user_id]['enabled'] = ($o->user_pass == '') ? false : true ;
140 function get_logs($type='all') {
142 $q="SELECT log.* FROM log WHERE log.user_id != '1' and ip != '87.233.211.2' ";
143 if ($_SESSION['creds']['user_id'] == 1)
144 $q="SELECT log.* FROM log WHERE log.user_id != 'x' ";
147 $q.= " AND log.action = '".$db->real_escape_string($type)."'";
149 $today =" AND date > date(date_add(now(), interval -0 day)) ";
150 $yesterday =" AND date < date(date_add(now(), interval -0 day)) AND date > date(date_add(now(), interval -1 day)) ";
151 $lastweek =" AND date < date(date_add(now(), interval -1 day)) AND date > date(date_add(now(), interval -6 day)) ";
152 $older =" AND date < date(date_add(now(), interval -7 day)) AND date > date(date_add(now(), interval -30 day)) ";
154 $order=" ORDER BY log.log_id desc ";
155 $r = $db->query($q.$today.$order);
158 'yesterday'=>array(),
162 while($a = mysqli_fetch_array($r)) {
163 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".$db->real_escape_string($a['ip'])."' GROUP BY users.user_name";
164 $ru = $db->query($qu);
165 $a['users_from_ip'] = " | ";
166 while($au = mysqli_fetch_array($ru))
167 $a['users_from_ip'] .= $au['user_name']." | ";
168 $return['today'][$a['log_id']] = $a;
170 $r = $db->query($q.$yesterday.$order);
171 while($a = mysqli_fetch_array($r)) {
172 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".$db->real_escape_string($a['ip'])."' GROUP BY users.user_name";
173 $ru = $db->query($qu);
174 $a['users_from_ip'] = " | ";
175 while($au = mysqli_fetch_array($ru))
176 $a['users_from_ip'] .= $au['user_name']." | ";
177 $return['yesterday'][$a['log_id']] = $a;
179 $r = $db->query($q.$lastweek.$order);
180 while($a = mysqli_fetch_array($r)) {
181 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".$db->real_escape_string($a['ip'])."' GROUP BY users.user_name";
182 $ru = $db->query($qu);
183 $a['users_from_ip'] = " | ";
184 while($au = mysqli_fetch_array($ru))
185 $a['users_from_ip'] .= $au['user_name']." | ";
186 $return['lastweek'][$a['log_id']] = $a;
188 $r = $db->query($q.$older.$order);
189 while($a = mysqli_fetch_array($r)) {
190 $qu="SELECT users.user_name FROM users LEFT JOIN log ON users.user_id = log.user_id WHERE log.ip='".$db->real_escape_string($a['ip'])."' GROUP BY users.user_name";
191 $ru = $db->query($qu);
192 $a['users_from_ip'] = " | ";
193 while($au = mysqli_fetch_array($ru))
194 $a['users_from_ip'] .= $au['user_name']." | ";
195 $return['older'][$a['log_id']] = $a;
201 function insert_users($u, $admin_level) {
203 $user_name = $u['user_name'];
204 $user_pass = $u['user_pass'];
205 $user_level = (int)$u['user_level'];
207 $q = "INSERT INTO users (user_name,user_pass,user_level) VALUES ('".$db->real_escape_string($user_name)."', '".$db->real_escape_string(md5($user_pass))."', ".$user_level.")";
212 * if user_level is 0, it means we don't really touch it, but we clear the password (can't log in anymore)
214 function update_users($u, $user_id) {
216 $user_id = (int)$user_id;
217 $user_name = @$u['user_name'];
218 $user_pass = @$u['user_pass'];
219 if (array_key_exists('user_level', $u))
220 $user_level = $u['user_level'];
224 $q = "UPDATE users SET user_name = '".$db->real_escape_string($user_name)."' WHERE user_id = ".$user_id;
228 $q = "UPDATE users SET user_pass = '".$db->real_escape_string(md5($user_pass))."' WHERE user_id = ".$user_id;
231 if ($user_level !== null) {
232 if ($user_level > 0) {
233 $q = "UPDATE users SET user_level = ".$user_level." WHERE user_id = ".$user_id;
236 $q = "UPDATE users SET user_pass = '' WHERE user_id = ".$user_id;
242 function remove_users($user_id) {
243 $user_id = (int)$user_id;
244 $q = "DELETE FROM users WHERE user_id = ".$user_id;
245 $r = $this->db->query($q);
250 * Get the permissions of a user over the file tree
252 * This builds a permission array, which is kind of recursive:
253 * The array keys are the name of the directories, and the values are an array
255 * The special key __access__ indicates the permission of a given directory,
266 * [subfolder01] => Array
268 * [subfolder02] => Array
271 * @param string user_id User id
272 * @return array Multidimensional array with dir and __access__ keys, and 0/1/2 values
274 function get_rights($user_id) {
278 $q = "SELECT folder_path, access FROM user_rights WHERE user_id = ".(int)$user_id;
280 while ($o = mysqli_fetch_object($r)) {
283 $arr_string = '$result';
285 //get foldernames from path
286 if ($o->folder_path != '/') {
287 $path = $o->folder_path;
289 $path=substr($path,1);
290 $folder_arr = explode('/',$path);
292 //create folder structure array
293 foreach ($folder_arr AS $key => $value) {
294 $value_escaped = str_replace("'", "\\'", $value);
295 $arr_string .= "['".$value_escaped."']";
298 $arr_string .= "['__access__']";
300 eval($arr_string." = '".$o->access."';");
307 * Get super user permissions, full recursive access on /
309 * @return array Permissions
311 function get_superuser_rights() {
312 return array('__access__' => 2);
317 * Initialise this->folderrights or this->$userrights
319 * this->folderrights are the permissions of the logged in user
320 * this->userrights are the permissions of the user beeing edited
324 * @param string user_id User id or -1 for full access
325 * @param string type 'folderrights' or 'userrights'
328 function give_rights($user_id, $type='folderrights') {
330 $rights = $this->get_superuser_rights();
332 $rights = $this->get_rights($user_id);
334 if ($type=='folderrights')
335 $this->folderrights = $rights;
336 else // $type=='userrights'
337 $this->userrights = $rights;
340 function update_rights($edited_user, $m, $admin_level) {
342 $q = "SELECT count(*) result FROM users WHERE user_id = ".(int)$edited_user." AND user_level < ".(int)$admin_level;
344 $o = mysqli_fetch_object($r);
347 foreach ($m AS $path => $access) {
348 $p_q = "SELECT count(*) result FROM user_rights WHERE user_id = ".(int)$edited_user." AND folder_path = '".$db->real_escape_string($path)."'";
349 $p_r = $db->query($p_q);
350 $p_o = mysqli_fetch_object($p_r);
351 if ($p_o->result == 1)
352 $db->query("UPDATE user_rights SET access = ".(int)$access." WHERE folder_path = '".$db->real_escape_string($path)."' AND user_id = ".(int)$edited_user);
353 if ($p_o->result == 0)
354 $db->query("INSERT INTO user_rights (user_id,folder_path,access) values (".(int)$edited_user.",'".$db->real_escape_string($path)."',".(int)$access.") ");
360 function show_rights_tree($path, $depth=0, $userid=0) {
365 $this->give_rights($userid, 'userrights');
367 // access = 0 --deny-all
368 // access = 1 --allow-dir-only
369 // access = 2 --allow-inc-subs
374 for ($i=0; $i<$depth; $i++)
376 if ($dir = opendir(SQUASHER_UPLOADS_DIR.$path)) {
377 $layout .= "<div style='clear:both;' >\n";
379 while (false !== ($file = readdir($dir))) {
380 $files_array[] = $file;
383 foreach ($files_array as $f_index => $file) {
384 if (($file{0} !== ".") && ($file !== ".."))
386 $filename = $path=='/' ? $path.$file : $path.'/'.$file;
387 if (!is_file(SQUASHER_UPLOADS_DIR.$filename) && $this->got_rights_array($filename) > 0) {
390 $check = $this->got_rights_array_admin($filename, $this->userrights);
396 $check_all = 'checked';
399 $check_allow = 'checked';
403 $check_deny = 'checked';
408 $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).";}";
410 $layout .= "<div class='depth".$depth."'>";
411 $layout .= "<div class='white_border' >".htmlspecialchars($file)."</div>\n";
412 $name_escaped = htmlspecialchars($name);
413 $layout .= '<div class="check_deny"><input name="m['.$name_escaped.']" value=0 type=radio '.$check_deny."></div>\n";
414 $layout .= '<div class="check_allow"><input name="m['.$name_escaped.']" value=1 type=radio '.$check_allow."></div>\n";
415 $layout .= '<div class="check_all"><input name="m['.$name_escaped.']" value=2 type=radio '.$check_all."></div>\n";
416 $sub_return = $this->show_rights_tree($filename,$depth+1,$userid);
417 if (is_array($style) && is_array($sub_return['style']))
418 $style = $style + $sub_return['style'];
419 $layout .= $sub_return['layout'];
425 $layout .= "</div>\n";
428 $return['style'] = $style;
429 $return['layout'] = $layout;
434 function got_rights_array($needle, $haystack='', $c=0) {
436 // - read_single_file
438 // - show_rights_tree
440 if (!is_array($haystack))
441 $haystack = $this->folderrights;
444 if ($needle{0} == '/' && @$haystack['__access__'] == 2 )
449 $needle = substr($needle, 1);
451 $needle_arr = explode('/', $needle);
452 $n = count($needle_arr);
455 foreach ($haystack as $k => $v) {
456 if ($needle_arr[$c] == $k) {
457 if (!is_array(@$v['__access__'])) {
458 if ($v['__access__'] == 2 ) return 2;
459 if ($v['__access__'] == 1 && $d == $n ) return 1;
460 if ($v['__access__'] == 0 && $d == $n ) return 0;
462 $return = $this->got_rights_array($needle, $v, $d);
469 function got_rights_array_admin($needle, $haystack='', $c=0) {
471 // - show_rights_tree
473 if (!is_array($haystack))
474 $haystack = $this->folderrights;
477 if ($needle{0} == '/' && @$haystack['__access__'] == 2 )
481 if ($needle{0} == '/')
482 $needle = substr($needle, 1);
484 $needle_arr = explode('/', $needle);
485 $n = count($needle_arr);
490 if (@$haystack['__access__'] == 2)
491 return $haystack['__access__'];
492 if (is_array($haystack[$needle_arr[$c]]))
493 $return = $this->got_rights_array_admin($needle, $haystack[$needle_arr[$c]], $d);
495 if (@$haystack['__access__'] > 0)
496 $return = $haystack['__access__'];
502 function got_rights_array_recursive($needle, $haystack='', $c=0) {
504 // - read_directory, for subfolders
506 if (!is_array($haystack))
507 $haystack = $this->folderrights;
510 if($needle{0}=='/' && @$haystack['__access__'] == 2 )
513 // check folder rights
515 $needle=substr($needle,1);
517 $needle_arr = explode('/', $needle);
518 $n = count($needle_arr);
522 foreach($haystack as $k => $v) {
523 if ($c < sizeof($needle_arr) && $needle_arr[$c] == $k) {
525 if ($v['__access__'] == 2)
526 $return = $return + $v['__access__'];
527 $return = $return + $this->got_rights_array_recursive($needle, $v, $d);
529 $return = $return + $this->in_array_recursive($v);
531 } elseif ($c == $n) {
532 $return = $return + $v['__access__'];
533 if($k != '__access__')$return = $return + $this->in_array_recursive($v);
540 function in_array_recursive($haystack) {
542 if (is_array($haystack)) {
543 foreach ($haystack as $key1 => $value1) {
544 if (is_array($value1)) {
545 $return = $return + $this->in_array_recursive($value1);
547 elseif ($value1 > 0) {
555 function read_single_file($path, $file) {
556 $filename = $path=='/' ? $path.$file : $path.'/'.$file;
557 $fsfilename = SQUASHER_UPLOADS_DIR.$filename; // name on the file system
559 if ($this->got_rights_array($path) > 0) {
560 if (is_file($fsfilename.'.Completed'))
562 elseif (is_file($fsfilename.'.InProgress'))
564 elseif (is_file($fsfilename.'.Starting'))
566 elseif (is_file($fsfilename.'.Processed'))
571 $handle = @fopen($fsfilename, "rb");
572 $sub_pos = strpos($file, $ext);
573 $base_name = substr($file, 0, $sub_pos);
574 $filecontent = @fread($handle, @filesize($fsfilename));
575 $config[$i] = explode("\r\n", $filecontent);
584 * [6] -> CRC32 checksum
586 if (@filesize($fsfilename) > 0) {
587 $h = md5($path."/".$config[$i][2]);
588 $this->configs[$h] = $config[$i];
589 $this->configs[$h]['squashed'] = true;
590 $this->configs[$h]['path'] = $path;
591 $this->configs[$h]['status'] = substr($ext, 1);
592 $this->configs[$h]['mime'] = $this->set_mime($this->configs[$h][2]);
593 $this->configs[$h]['hidden'] = is_file(SQUASHER_UPLOADS_DIR.$path.'/'.$base_name.'.hidden');
594 //to prevent dates of 1-1-1970 we set te dates of the config file
595 $this->configs[$h]['added'] = filectime($fsfilename);
596 $this->configs[$h]['lastchange'] = filemtime($fsfilename);
598 $this->populate_stats($path, $h);
600 #$this->update_hash($h,$path."/".$config[$i][2]);
602 $this->check_stats($h);
610 function read_directory($path, $getsubs=false, $getfirstfiles=true, $getdeepfiles=true, $populate=true) {
611 $fsdir = $path=='/' ? SQUASHER_UPLOADS_DIR : SQUASHER_UPLOADS_DIR.$path;
612 $hdir = @opendir(SQUASHER_UPLOADS_DIR.$path);
616 while (false !== ($file = readdir($hdir))) {
617 if ($file{0} == "." || substr($file,0,2) == "SQ")
618 continue; // skip this file
619 $filename = $path=='/' ? $path.$file : $path.'/'.$file;
620 $fsfilename = SQUASHER_UPLOADS_DIR.$filename; // name on the file system
621 if (!is_file($fsfilename) && strpos($filename, '/recieving/')!==0) {
623 if ($this->got_rights_array_recursive($filename) > 0) {
628 $this->subfolders[$key] = $file;
632 $this->read_directory($filename, false, $getdeepfiles, $getdeepfiles, $populate);
633 } elseif (strpos($filename,'/ftp/')===0) {
635 if ($this->got_rights_array($path) > 0 && !strpos($filename, '.hidden') ) {
637 $name_only = substr($filename, strlen($path)+1); // this is $file
638 $file_structure = explode('.', $name_only); // array of dot separated name fragment
639 $ext = array_pop($file_structure); // extension
640 $base_name = array_pop($file_structure); // (erk)
641 $this->configs[$h]['path'] = $path;
642 $this->configs[$h][0] = 'manual ftp';
643 $this->configs[$h][2] = $name_only;
644 $this->configs[$h][3] = filesize($fsfilename);
645 $this->configs[$h]['added'] = filectime($fsfilename);
646 $this->configs[$h]['lastchange'] = filemtime($fsfilename);
647 $this->configs[$h]['status'] = 'unknown';
648 $this->configs[$h]['squashed'] = false;
649 $this->configs[$h]['mime'] = $this->set_mime($name_only);
650 $this->configs[$h]['hidden'] = is_file(SQUASHER_UPLOADS_DIR.$path.'/'.$base_name.'.hidden');
652 } elseif ($getfirstfiles) {
654 if ($this->got_rights_array($path) > 0) {
655 if (strpos($file,'.Completed'))
657 elseif (strpos($file,'.InProgress'))
659 elseif (strpos($file,'.Starting'))
661 elseif (strpos($file,'.Processed'))
666 $handle = @fopen($fsfilename, "rb");
667 $sub_pos = strpos($file, $ext);
668 $base_name = substr($file, 0, $sub_pos);
669 $filecontent = @fread($handle, @filesize($fsfilename));
670 $config[$i] = explode("\r\n", $filecontent);
680 * [6] -> CRC32 checksum
683 if (@filesize($fsfilename) > 0) {
684 $h = md5($path."/".$config[$i][2]);
685 $this->configs[$h] = $config[$i];
686 $this->configs[$h]['squashed'] = true;
687 $this->configs[$h]['path'] = $path;
688 $this->configs[$h]['status'] = substr($ext, 1);
689 $this->configs[$h]['mime'] = $this->set_mime($this->configs[$h][2]);
690 $this->configs[$h]['hidden'] = is_file(SQUASHER_UPLOADS_DIR.$path.'/'.$base_name.'.hidden');
691 //to prevent dates of 1-1-1970 we set te dates of the config file
692 $this->configs[$h]['added'] = filectime($fsfilename);
693 $this->configs[$h]['lastchange'] = filemtime($fsfilename);
695 $this->populate_stats($path, $h);
697 $this->update_hash($h, $path."/".$config[$i][2]);
699 $this->check_stats($h);
707 function check_stats($h) {
709 $config = $this->get_config($h);
710 $count = @array_sum($config['stats']);
711 if ($config['status']=='Completed' && $count != $config[5]) {
712 $filepath=$config['path'].'/'.$config[2];
713 if ($this->history[$h]['completed']=="1") {
714 //don't display broken file, remove it instead
715 unlink(SQUASHER_UPLOADS_DIR.$config['path'].'/'.$config[2].'.Completed');
716 unset($this->configs[$h]);
720 $m_subject = "Squasher Debug: File Removed";
721 $m_body = "Upload removed: \n File: ".$config['path']."/".$config[2]." \n Status: ".$config['status']." \n Chunks: ".$count." out of ".$config[5];
722 mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
724 log_event('debug', $filepath, $h, 'cleanup');
727 rename(SQUASHER_UPLOADS_DIR.$config['path'].'/'.$config[2].'.Completed',
728 SQUASHER_UPLOADS_DIR.$config['path'].'/'.$config[2].'.InProgress');
729 $this->configs[$h]['status'] = 'InProgress';
734 $m_subject = "Squasher Debug: Upload Error";
735 $m_body = "Upload error: \n File: ".$config['path']."/".$config[2]." \n Status: ".$config['status']." \n Chunks: ".$count." out of ".$config[5];
736 mail('support@netformatie.nl', $m_subject, $m_body, "From: squasher@netformatie.nl");
737 mail('jan@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
738 mail('joop@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
739 mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
742 //wget -o/dev/null "http://www.mollie.nl/xml/sms/?username=netformatie&password=SMSdolsi&originator=Netformatie&recipients=${ENGINEER}&message=${CALLERID}";
745 $ship = explode('/',$config['path']);
746 if ($ship[2] == 'myas' || $ship[2] == 'myez' || $ship[2] == 'myrw')
747 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");
748 log_event('debug', $filepath, $h, 'retry');
751 } elseif ($config['status']=='Completed' && $count == $config[5]) {
752 if ($this->history[$h]['completed']==0)
753 $db->query("UPDATE file_hash SET completed = 1 WHERE md5_hash = '".$db->real_escape_string($h)."'");
757 function update_hash($hash, $path) {
759 $check_hash_query = "select * from file_hash where md5_hash = '".$hash."'";
760 $check_hash_result = $db->query($check_hash_query);
761 if(mysqli_num_rows($check_hash_result) == 0) {
762 $insert_hash_query = "INSERT INTO file_hash (md5_hash,file) values ('".$db->real_escape_string($hash)."','".$db->real_escape_string($path)."')";
763 $db->query($insert_hash_query);
767 /* unused function */
769 function path_to_arraystring($path, $arrayname) {
770 $path_values = explode('/', $path);
771 $return = $arrayname;
772 foreach ($path_values AS $key => $value) {
773 if ($value != '.' && $value != '')
774 $return.= "['".$value."']";
779 function populate_stats($path, $h) {
789 * [6] -> CRC32 checksum
791 $config = $this->configs[$h];
793 $q = "SELECT * FROM file_hash WHERE md5_hash = '".$db->real_escape_string($h)."'";
795 $o = mysqli_fetch_object($r);
796 $validated_chunks = $o->validated_chunks;
798 if ($this->history[$h]['completed']=="1") {
799 $file_part = $path."/SQ".zfill(1,6)."-".$config[2];
800 if (!is_file(SQUASHER_UPLOADS_DIR.$file_part))
801 $file_part = $path."/SQ".zfill(1,3)."-".$config[2];
802 if (is_file(SQUASHER_UPLOADS_DIR.$file_part)) {
803 $this->configs[$h]['added'] = filectime(SQUASHER_UPLOADS_DIR.$file_part);
804 $file_part = $path."/SQ".zfill($config[5],6)."-".$config[2];
805 if (!is_file(SQUASHER_UPLOADS_DIR.$file_part))
806 $file_part = $path."/SQ".zfill($config[5],3)."-".$config[2];
807 if (is_file(SQUASHER_UPLOADS_DIR.$file_part))
808 $this->configs[$h]['lastchange'] = filemtime(SQUASHER_UPLOADS_DIR.$file_part);
809 for ($i=1; $i<=$config[5]; $i++)
810 $this->configs[$h]['stats'][$i] = "1.00";
812 //failsafe voor verwijderde bestanden
813 $db->query("UPDATE file_hash SET completed = 0 WHERE md5_hash = '".$db->real_escape_string($h)."'");
816 $keep_validating = true;
817 for ($i=1; $i<=$config[5]; $i++) {
818 if ($validated_chunks > $i) {
819 $this->configs[$h]['stats'][$i]="1.00";
821 $file_part = $path."/SQ".zfill($i,6)."-".$config[2];
822 if (!is_file(SQUASHER_UPLOADS_DIR.$file_part))
823 $file_part = $path."/SQ".zfill($i,3)."-".$config[2];
824 if (is_file(SQUASHER_UPLOADS_DIR.$file_part)) {
825 $handle = fopen(SQUASHER_UPLOADS_DIR.$file_part, "rb");
826 $size_this = filesize(SQUASHER_UPLOADS_DIR.$file_part);
827 $added = filectime(SQUASHER_UPLOADS_DIR.$file_part);
828 $last_changed = filemtime(SQUASHER_UPLOADS_DIR.$file_part);
829 if ($this->configs[$h]['added'] > $added || !is_numeric($this->configs[$h]['added']))
830 $this->configs[$h]['added'] = $added;
831 if ($this->configs[$h]['lastchange'] < $last_changed)
832 $this->configs[$h]['lastchange'] = $last_changed;
833 if ($i != $config[5]) {
834 $this->configs[$h]['stats'][$i] = number_format((1/$config[4])*$size_this, 2, '.', '');
835 //number_format((100/$config[4])*$size_this, 2, '.', '')."%";
837 $this->configs[$h]['stats'][$i] = number_format((1/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '');
838 //number_format((100/($config[3]-($config[4]*($config[5]-1))))*$size_this, 2, '.', '')."%";
841 if ($config[4] == $size_this && $keep_validating) {
842 $validated_chunks = $i;
844 $keep_validating = false;
847 $this->configs[$h]['stats'][$i] = "0.00";
848 //$this->configs[$h]['stats'][$i]="0.00%";
853 $db->query("UPDATE file_hash SET validated_chunks = '".$db->real_escape_string($validated_chunks)."' WHERE md5_hash = '".$db->real_escape_string($h)."'");
859 function read_config($path, $filename) {
860 if (is_file($path."/".$filename.".InProgress")) {
861 $config_handle = fopen($path."/".$filename.".InProgress", "r");
862 $conf_path=$path."/".$filename.".InProgress";
863 } elseif (is_file($path."/".$filename.".Completed" )) {
864 $config_handle = fopen($path."/".$filename.".Completed", "r");
865 $conf_path=$path."/".$filename.".Completed";
866 } elseif (is_file($path."/".$filename.".Starting" )) {
867 $config_handle = fopen($path."/".$filename.".Starting", "r");
868 $conf_path=$path."/".$filename.".Starting";
869 } elseif (is_file($path."/".$filename.".Processed" )) {
870 $config_handle = fopen($path."/".$filename.".Processed", "r");
871 $conf_path=$path."/".$filename.".Processed";
875 $config_content = fread($config_handle, filesize($conf_path));
876 fclose($config_handle);
877 $config = explode("\n", $config_content);
883 /* $file_count = $config[5];
885 for ($i=1; $i<=$file_count; $i++)
887 $file_part = $path."/SQ".zfill($i,6)."-".$filename;
888 if (is_file($file_part))
891 $handle = fopen($file_part, "rb");
892 $size_this = filesize($file_part);
893 //$stats[$i]=round((100/$config[4])*$size_this)."%";
894 if ((($size_this==$config[4] && ($last+1)==$i) )|| $i == $config[5]) {
895 $merged_file.=fread($handle, filesize($file_part));
905 * Outputs one file (echo)
906 * @param string $path Absolute path within SQUASHER_UPLOADS_DIR
907 * @param string $filename File name in $path
908 * @param bool $tovar Returns content rather than outputing it
909 * @return file content if $tovar; or void
911 function print_files($path, $filename, $tovar=false) {
912 $fsfilename = SQUASHER_UPLOADS_DIR.$path.'/'.$filename;
913 if (strpos($path.'/', '/ftp/')===0) {
914 if (is_file($fsfilename)) {
915 $handle = fopen($fsfilename, 'rb');
916 while (!feof($handle))
918 print(fread($handle, 1024));
924 if (is_file($fsfilename.'.InProgress'))
925 $conf_path = $fsfilename.'.InProgress';
926 elseif (is_file($fsfilename.'.Completed' ))
927 $conf_path = $fsfilename.'.Completed';
928 elseif (is_file($fsfilename.'.Starting' ))
929 $conf_path = $fsfilename.'.Starting';
930 elseif (is_file($fsfilename.'.Processed' ))
931 $conf_path = $fsfilename.'.Processed';
934 $config_handle = fopen($conf_path, 'r');
935 $config_content = fread($config_handle, filesize($conf_path));
936 fclose($config_handle);
937 $config = explode("\n",$config_content);
939 $file_count = $config[5];
941 $last_part_size = ( $config[3] - ( ( $config[5] -1 ) * $config[4] ) );
942 for ($i=0;$i<=$file_count;$i++)
944 $file_part = SQUASHER_UPLOADS_DIR.$path."/SQ".zfill($i,6)."-".$filename;
945 if (!is_file($file_part))
946 $file_part = $path."/SQ".zfill($i,3)."-".$filename;
947 if (is_file($file_part))
949 $handle = fopen($file_part, "rb");
950 $size_this = filesize($file_part);
951 if ( ( ( $size_this==$config[4] ) && ( ($last+1)==$i ) ) || ( ( $i == $config[5] ) && ( $size_this==$last_part_size ) && ( ($last+1)==$i ) ) ) {
953 $merged_file.=fread($handle, $size_this);
956 while (!feof($handle))
958 print(fread($handle, 4096));
973 /* unused function */
975 function check_md5($h) {
977 $config = $this->configs[$h];
978 $var = $this->print_files($config['path'], $config[2], true);
980 if ($hash==$config[6])
986 /* unused function */
988 function file_crc($file_string) {
989 //$file_string = file_get_contents($file);
991 $crc = crc32($file_string);
992 return sprintf("%u\n", $crc);
995 /* unused function */
997 function file_crc_debug($file) {
998 $file_string = file_get_contents($file);
1000 $crc = crc32($file_string);
1001 return sprintf("%u\n", $crc);
1007 * @param string $h Md5 hash of the file path, in lower case
1008 * @param array $s Session credidentials
1010 function delete_file($h, $s) {
1012 $request = $this->get_config($h);
1013 $filepath = $request['path'].'/'.$request[2];
1014 if (strpos($request['path'], '/ftp/')===0) {
1016 $fsfilepath = SQUASHER_UPLOADS_DIR.$filepath;
1017 if (is_file($fsfilepath))
1018 @unlink($fsfilepath);
1019 if (is_file($fsfilepath.'.hidden'))
1020 @unlink($fsfilepath.'.hidden');
1022 $fspath = SQUASHER_UPLOADS_DIR.$request['path'];
1024 for ($i=0;$i<=$request[5];$i++) {
1025 $part_six = $fspath.'/SQ'.zfill($i,6).'-'.$request[2];
1026 $part_three = $fspath.'/SQ'.zfill($i,3).'-'.$request[2];
1027 if (is_file($part_six))
1029 if (is_file($part_three))
1030 @unlink($part_three);
1033 if (is_file($fspath.'/'.$request[2].'.hidden'))
1034 @unlink($fspath.'/'.$request[2].'.hidden');
1035 if (is_file($fspath.'/'.$request[2].'.Completed'))
1036 @unlink($fspath.'/'.$request[2].'.Completed');
1037 if (is_file($fspath.'/'.$request[2].'.InProgress'))
1038 @unlink($fspath.'/'.$request[2].'.InProgress');
1039 if (is_file($fspath.'/'.$request[2].'.Processed'))
1040 @unlink($fspath.'/'.$request[2].'.Processed');
1041 if (is_file($fspath.'/'.$request[2].'.Starting'))
1042 @unlink($fspath.'/'.$request[2].'.Starting');
1046 $q = "DELETE FROM file_hash WHERE md5_hash = '".$db->real_escape_string($h)."'";
1049 log_event('delete', $filepath, $h);
1052 $m_name = $s['user_name'];
1053 $m_subject = "Squasher Debug: File Deleted by {$m_name}";
1054 $m_body = "File Deleted: \n Requested by: {$m_name} \n File: {$filepath}";
1055 mail('jasper@netformatie.nl', $m_subject, $m_body, "From: support@netformatie.nl");
1058 /* unused debug function (echo / print_r)
1059 function show_files() {
1061 $path = "./uploads/";
1063 if ($dir = opendir($path)) {
1067 $files_merged = array();
1068 while (false !== ($file = readdir($dir)))
1070 if (($file !== ".") && ($file !== ".."))
1072 $filename = $path.$file;
1073 $handle = fopen($filename, "rb");
1074 $size_this = filesize($filename);
1076 $size_first = $size_this;
1077 $filecontent = fread($handle, filesize($filename));
1078 $files[$i++] = $filename;
1079 $files_merged[$file_base][]=$filename;
1086 print_r($files_merged);
1092 * Get mime-type from filename
1094 * Defaults to 'application/octet-stream'
1096 * @param string $filename The filename with an extension
1097 * @return string mime type
1099 function set_mime($filename) {
1100 $ext_arr = explode('.', $filename);
1101 $ext = strtolower(array_pop($ext_arr));
1104 $mime = 'video/avi';
1108 $mime = 'video/mpeg'; //MPEG Video
1114 $mime = 'application/octet-stream';
1117 $mime = 'image/gif'; //GIF Image
1121 $mime = 'image/jpeg'; //JPEG Image
1124 $mime = 'image/png'; //PNG Image
1128 $mime = 'audio/wav'; //WAV Audio
1131 $mime = 'audio/mpeg'; //MP3 Audio
1134 $mime = 'video/mov'; //Quicktime Video
1137 $mime = 'video/x-ms-wmv'; //Windows WMV video
1140 $mime = 'audio/x-ms-wma'; //Windows WMA audio
1143 $mime = 'audio/x-realaudio'; //RealPlayer Audio/Video (.rm)
1146 $mime = 'audio/x-pn-realaudio'; //RealPlayer Audio/Video (.ram)
1149 $mime = 'application/pdf'; //PDF Document
1152 $mime = 'application/msword'; //MS Word .doc file
1155 $mime = 'application/zip'; //Zip File
1158 $mime = 'application/octet-stream';
1161 //$return['mime']=$mime;
1162 //$return['ext']=$ext;
1168 // vim: syntax=php ts=4 sw=4 sts=4 sr noet