#!/usr/bin/php -q
<?php

// Copyright (c) 2012, Intorrent LLC, US. All rights Reserved.
//
// This software is the copyrighted work of Inroeewr, LLC.
// Use of the software is subject to the general business terms and conditions of Intorrent 
// and its related transaction documents like license sheets or other written notices.
//
// Any reproduction or redistribution of the software not in accordance with the license terms
// is expressly prohibited by law, and may result in severe civil and criminally penalties.
// Violators will be prosecuted to the maximum extent possible.

?>
<?php

  include "/usr/local/astium/web/php/config.php";

  $cms = new DB_CMS;
  $cms2 = new DB_CMS;

  $q = "select name, id from moh where status='active' and ( name like '%.mp3' or name like '%.ulaw' or name like '%.alaw' or name like '%.gsm' or name like '%.wav' or name like '%.WAV')";

  $cms->query($q);
  echo "found " . $cms->num_rows() . " candidates for fixing!\n";
  if ( $cms->num_rows() > 0 ) {
    while ($cms->next_record()) {
	$name = $cms->f('name');
	$name_orig = $cms->f('name');
	$id = $cms->f('id');
        echo "  Looking at $name($id)\n";
        $extens = strrchr($name, ".");
        if (strlen($extens) > 0 ) {
           $len1 = strlen($extens);
           $name = substr_replace($name, "", -$len1);
           echo "     removed the $extens\n";
        }
        // get rid of bad chars in the file name! 
        $allowables = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#%-_=:./";
        $nlen = strlen($name);
        $an = strspn($name, $allowables);
        if($an != $nlen) {
           $nname = $name;
           for($i=$an; $i < $nlen; $i++) {
             if(strspn($nname,$allowables, $i, 1) == 0 )
                $nname = substr_replace($nname, "_", $i, 1);
           }
           $name = $nname;
           $q2 = "update moh set name='$name' where id=$id";
           $cms2->query($q2);
           echo "Changed name from $name_orig to $name for id=$id\n";
        } else {
           $cms2->query("update moh set name='$name' where id=$id");
           echo "changed name from $name_orig to $name for id=$id\n";
        }
    }
  } 
  echo "Done!\n";
?>

