public function ajaxHandler()
 {
     switch ($_REQUEST['command']) {
         case 'getgravatar':
             $type = !empty($_POST['grouptype']) ? $_POST['grouptype'] : "";
             $id = !empty($_POST['id']) ? $_POST['id'] : "";
             switch ($type) {
                 case "internal":
                     $data = $this->freepbx->Userman->getUserByID($id);
                     $email = $data['email'];
                     break;
                 case "userman":
                     $email = !empty($_POST['email']) ? $_POST['email'] : '';
                     if (empty($email)) {
                         $data = $this->freepbx->Userman->getUserByID($id);
                         $email = $data['email'];
                     }
                     break;
             }
             if (empty($email)) {
                 return array("status" => false, "message" => _("Please enter a valid email address"));
             }
             $data = $this->getGravatar($email);
             if (!empty($data)) {
                 $dname = "cm-" . rand() . "-" . md5($email);
                 imagepng(imagecreatefromstring($data), $this->tmp . "/" . $dname . ".png");
                 return array("status" => true, "name" => $dname, "filename" => $dname . ".png");
             } else {
                 return array("status" => false, "message" => sprintf(_("Unable to find gravatar for %s"), $email));
             }
             break;
         case "delimage":
             if (!empty($_POST['id'])) {
                 $this->delImageByEntryID($_POST['id']);
                 return array("status" => true);
             } elseif (!empty($_POST['img'])) {
                 $name = basename($_POST['img']);
                 if (file_exists($this->tmp . "/" . $name)) {
                     unlink($this->tmp . "/" . $name);
                     return array("status" => true);
                 }
             }
             return array("status" => false, "message" => _("Invalid"));
             break;
         case 'uploadimage':
             // XXX If the posted file was too large,
             // we will get here, but $_FILES is empty!
             // Specifically, if the file that was posted is
             // larger than 'post_max_size' in php.ini.
             // So, php will throw an error, as index
             // $_FILES["files"] does not exist, because
             // $_FILES is empty.
             if (!isset($_FILES)) {
                 return array("status" => false, "message" => _("File upload failed"));
             }
             $this->freepbx->Media();
             foreach ($_FILES["files"]["error"] as $key => $error) {
                 switch ($error) {
                     case UPLOAD_ERR_OK:
                         $extension = pathinfo($_FILES["files"]["name"][$key], PATHINFO_EXTENSION);
                         $extension = strtolower($extension);
                         $supported = array("jpg", "png");
                         if (in_array($extension, $supported)) {
                             $tmp_name = $_FILES["files"]["tmp_name"][$key];
                             $dname = \Media\Media::cleanFileName($_FILES["files"]["name"][$key]);
                             $dname = "cm-" . rand() . "-" . pathinfo($dname, PATHINFO_FILENAME);
                             //imagepng(imagecreatefromstring(file_get_contents($tmp_name)), $this->tmp."/".$dname.".png");
                             $this->resizeImage(file_get_contents($tmp_name), $dname);
                             return array("status" => true, "name" => $dname, "filename" => $dname . ".png");
                         } else {
                             return array("status" => false, "message" => _("Unsupported file format"));
                             break;
                         }
                         break;
                     case UPLOAD_ERR_INI_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the upload_max_filesize directive in php.ini"));
                         break;
                     case UPLOAD_ERR_FORM_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"));
                         break;
                     case UPLOAD_ERR_PARTIAL:
                         return array("status" => false, "message" => _("The uploaded file was only partially uploaded"));
                         break;
                     case UPLOAD_ERR_NO_FILE:
                         return array("status" => false, "message" => _("No file was uploaded"));
                         break;
                     case UPLOAD_ERR_NO_TMP_DIR:
                         return array("status" => false, "message" => _("Missing a temporary folder"));
                         break;
                     case UPLOAD_ERR_CANT_WRITE:
                         return array("status" => false, "message" => _("Failed to write file to disk"));
                         break;
                     case UPLOAD_ERR_EXTENSION:
                         return array("status" => false, "message" => _("A PHP extension stopped the file upload"));
                         break;
                 }
             }
             return array("status" => false, "message" => _("Can Not Find Uploaded Files"));
             break;
         case 'grid':
             $group = $this->getGroupByID($_REQUEST['group']);
             $entries = $this->getEntriesByGroupID($_REQUEST['group']);
             $entries = array_values($entries);
             $final = array();
             switch ($group['type']) {
                 case "internal":
                     $i = 0;
                     foreach ($entries as $entry) {
                         $user = $this->freepbx->Userman->getUserByID($entry['user']);
                         $entry['fname'] = !empty($entry['fname']) ? $entry['fname'] : $user['fname'];
                         $entry['lname'] = !empty($entry['lname']) ? $entry['lname'] : $user['lname'];
                         $entry['displayname'] = !empty($entry['displayname']) ? $entry['displayname'] : (!empty($user['displayname']) ? $user['displayname'] : $entry['fname'] . " " . $entry['lname']);
                         $entry['displayname'] = !empty($entry['displayname']) ? $entry['displayname'] : $user['username'];
                         $entry['title'] = !empty($entry['title']) ? $entry['title'] : $user['title'];
                         $entry['company'] = !empty($entry['company']) ? $entry['company'] : $user['company'];
                         $entry['username'] = !empty($user['displayname']) ? $user['displayname'] : $entry['fname'] . " " . $entry['lname'];
                         $entry['actions'] = '<a href="config.php?display=contactmanager&amp;action=showentry&amp;group=' . $_REQUEST['group'] . '&amp;entry=' . $entry['uid'] . '"><i class="fa fa-edit fa-fw"></i></a><a href="config.php?display=contactmanager&amp;action=delentry&amp;group=' . $_REQUEST['group'] . '&amp;entry=' . $entry['uid'] . '"><i class="fa fa-ban fa-fw"></i></a>';
                         $final[$i] = $entry;
                         $i++;
                     }
                     break;
                 case "userman":
                     $i = 0;
                     foreach ($entries as $entry) {
                         if (empty($entry['user'])) {
                             continue;
                         }
                         $user = $this->freepbx->Userman->getUserByID($entry['user']);
                         $final[$i] = $user;
                         $final[$i]['displayname'] = !empty($user['displayname']) ? $user['displayname'] : $user['fname'] . " " . $user['lname'];
                         $final[$i]['displayname'] = !empty($user['displayname']) ? $user['displayname'] . " (" . $user['username'] . ")" : $user['username'];
                         $final[$i]['actions'] = '<a href="config.php?display=userman&action=showuser&user='******'id'] . '"><i class="fa fa-edit fa-fw"></i></a>';
                         $i++;
                     }
                     break;
                 case "external":
                     $i = 0;
                     foreach ($entries as $entry) {
                         $entry['numbers'] = !empty($entry['numbers']) ? $entry['numbers'] : array();
                         $nums = array();
                         foreach ($entry['numbers'] as &$number) {
                             $nums[] = $number['number'] . "(" . $number['type'] . ")";
                         }
                         $entry['numbers'] = !empty($entry['numbers']) ? implode("<br>", $nums) : "";
                         $entry['actions'] = '<a href="config.php?display=contactmanager&amp;action=showentry&amp;group=' . $_REQUEST['group'] . '&amp;entry=' . $entry['uid'] . '"><i class="fa fa-edit fa-fw"></i></a><a href="config.php?display=contactmanager&amp;action=delentry&amp;group=' . $_REQUEST['group'] . '&amp;entry=' . $entry['uid'] . '"><i class="fa fa-ban fa-fw"></i></a>';
                         $final[$i] = $entry;
                         $i++;
                     }
                     break;
             }
             return $final;
             break;
     }
 }
 /**
  * Handle AJAX
  */
 public function ajaxHandler()
 {
     $request = $_REQUEST;
     switch ($request['command']) {
         case "saveCustomLang":
             if (empty($_POST['id'])) {
                 $this->addCustomLanguage($_POST['language'], $_POST['description']);
             } else {
                 $this->updateCustomLanguage($_POST['id'], $_POST['language'], $_POST['description']);
             }
             return array("status" => true);
             break;
         case "convert":
             set_time_limit(0);
             $media = $this->FreePBX->Media;
             $temporary = $_POST['temporary'];
             $name = basename($_POST['name']);
             $codec = $_POST['codec'];
             $lang = $_POST['language'];
             $directory = $_POST['directory'];
             $path = $this->path . "/" . $lang;
             if (!empty($directory)) {
                 $path = $path . "/" . $directory;
             }
             if (!file_exists($path)) {
                 mkdir($path);
             }
             $name = preg_replace("/\\s+|'+|`+|\"+|<+|>+|\\?+|\\*|\\.+|&+/", "-", $name);
             if (!empty($codec)) {
                 $media->load($temporary);
                 try {
                     $media->convert($path . "/" . $name . "." . $codec);
                     unlink($temporary);
                 } catch (\Exception $e) {
                     return array("status" => false, "message" => $e->getMessage() . " [" . $path . "/" . $name . "." . $codec . "]");
                 }
                 return array("status" => true, "name" => $name);
             } else {
                 $ext = pathinfo($temporary, PATHINFO_EXTENSION);
                 if ($temporary && file_exists($temporary)) {
                     rename($temporary, $path . "/" . $name . "." . $ext);
                     return array("status" => true, "name" => $name);
                 } else {
                     return array("status" => true, "name" => $name);
                 }
             }
             break;
         case 'delete':
             switch ($request['type']) {
                 case 'customlangs':
                     $ret = array();
                     foreach ($request['customlangs'] as $language) {
                         $ret[$language] = $this->delCustomLanguage($language);
                     }
                     return array('status' => true, 'message' => $ret);
                     break;
             }
             break;
         case "upload":
             if (empty($_FILES["files"])) {
                 return array("status" => false, "message" => _("No files were sent to the server"));
             }
             foreach ($_FILES["files"]["error"] as $key => $error) {
                 switch ($error) {
                     case UPLOAD_ERR_OK:
                         $extension = pathinfo($_FILES["files"]["name"][$key], PATHINFO_EXTENSION);
                         $extension = strtolower($extension);
                         $supported = $this->FreePBX->Media->getSupportedFormats();
                         $archives = array("tgz", "gz", "tar", "zip");
                         if (in_array($extension, $supported['in']) || in_array($extension, $archives)) {
                             $tmp_name = $_FILES["files"]["tmp_name"][$key];
                             $dname = \Media\Media::cleanFileName($_FILES["files"]["name"][$key]);
                             $dname = pathinfo($dname, PATHINFO_FILENAME);
                             $id = time() . rand(1, 1000);
                             $name = $dname . '-' . $id . '.' . $extension;
                             move_uploaded_file($tmp_name, $this->temp . "/" . $name);
                             $gfiles = $bfiles = array();
                             if (in_array($extension, $archives)) {
                                 //this is an archive
                                 if ($extension == "zip") {
                                     $tar = new Zip();
                                 } else {
                                     $tar = new Tar();
                                 }
                                 $archive = $this->temp . "/" . $name;
                                 $tar->open($archive);
                                 $path = $this->temp . "/" . $id;
                                 if (!file_exists($path)) {
                                     mkdir($path);
                                 }
                                 $tar->extract($path);
                                 $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
                                 foreach ($objects as $name => $object) {
                                     if ($object->isDir()) {
                                         continue;
                                     }
                                     $file = (string) $object;
                                     $extension = pathinfo($file, PATHINFO_EXTENSION);
                                     $extension = strtolower($extension);
                                     $dir = dirname(str_replace($path . "/", "", $file));
                                     $dir = $dir != "." ? $dir : "";
                                     $dname = \Media\Media::cleanFileName(pathinfo($file, PATHINFO_FILENAME));
                                     if (!in_array($extension, $supported['in'])) {
                                         $bfiles[] = array("directory" => $dir, "filename" => (!empty($dir) ? $dir . "/" : "") . $dname, "localfilename" => $file, "id" => "");
                                         continue;
                                     }
                                     $gfiles[] = array("directory" => $dir, "filename" => (!empty($dir) ? $dir . "/" : "") . $dname, "localfilename" => $file, "id" => "");
                                 }
                                 unlink($archive);
                             } else {
                                 $gfiles[] = array("directory" => "", "filename" => pathinfo($dname, PATHINFO_FILENAME), "localfilename" => $this->temp . "/" . $name, "id" => $id);
                             }
                             return array("status" => true, "gfiles" => $gfiles, "bfiles" => $bfiles);
                         } else {
                             return array("status" => false, "message" => _("Unsupported file format"));
                             break;
                         }
                         break;
                     case UPLOAD_ERR_INI_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the upload_max_filesize directive in php.ini"));
                         break;
                     case UPLOAD_ERR_FORM_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"));
                         break;
                     case UPLOAD_ERR_PARTIAL:
                         return array("status" => false, "message" => _("The uploaded file was only partially uploaded"));
                         break;
                     case UPLOAD_ERR_NO_FILE:
                         return array("status" => false, "message" => _("No file was uploaded"));
                         break;
                     case UPLOAD_ERR_NO_TMP_DIR:
                         return array("status" => false, "message" => _("Missing a temporary folder"));
                         break;
                     case UPLOAD_ERR_CANT_WRITE:
                         return array("status" => false, "message" => _("Failed to write file to disk"));
                         break;
                     case UPLOAD_ERR_EXTENSION:
                         return array("status" => false, "message" => _("A PHP extension stopped the file upload"));
                         break;
                 }
             }
             break;
         default:
             echo json_encode(_("Error: You should never see this"));
             break;
     }
 }
 public function ajaxHandler()
 {
     switch ($_REQUEST['command']) {
         case "gethtml5byid":
             $media = $this->FreePBX->Media();
             $file = "";
             switch ($_POST['type']) {
                 case "system":
                     $path = $this->FreePBX->Config->get("ASTVARLIBDIR") . "/sounds";
                     $rec = $this->getRecordingById($_REQUEST['id']);
                     if (!empty($rec) && !empty($rec['soundlist'])) {
                         //if there are multiple files (compound) then just play the first
                         //This probably needs to be changed to combine them but
                         //the code for a combine doesnt exist yet *sigh*
                         $fileInfo = reset($rec['soundlist']);
                         $files = $this->fileStatus($fileInfo['name']);
                         if (!empty($files['en'])) {
                             $file = $path . "/en/" . reset($files['en']);
                         } else {
                             $lang = key($files);
                             $data = reset($files);
                             $file = $path . "/" . $lang . "/" . reset($data);
                         }
                     }
                     break;
                 case "temp":
                     $file = basename($_REQUEST['id']);
                     $file = $this->temp . "/" . $file;
                     break;
                 default:
                     break;
             }
             if (!empty($file)) {
                 if (file_exists($file)) {
                     $media->load($file);
                     $files = $media->generateHTML5();
                     $final = array();
                     foreach ($files as $format => $name) {
                         $final[$format] = "ajax.php?module=recordings&command=playback&file=" . urlencode($name);
                     }
                     return array("status" => true, "files" => $final);
                 }
             }
             return array("status" => false, "message" => _("File does not exist"));
             break;
         case "gethtml5":
             $media = $this->FreePBX->Media();
             $lang = basename($_POST['language']);
             $info = pathinfo($_POST['filenames'][$lang]);
             $path = $_POST['temporary'][$lang] ? $this->temp : $this->path;
             if (empty($info['extension'])) {
                 $file = preg_replace("/^" . $lang . "\\//i", "", $_POST['filenames'][$lang]);
                 $status = $this->fileStatus($file, !$_POST['temporary'][$lang]);
                 if (!empty($status[$lang])) {
                     $filename = $path . "/" . $lang . "/" . reset($status[$lang]);
                 }
             } else {
                 $filename = $path . "/" . $_POST['filenames'][$lang];
             }
             $media->load($filename);
             $files = $media->generateHTML5();
             $final = array();
             foreach ($files as $format => $name) {
                 $final[$format] = "ajax.php?module=recordings&command=playback&file=" . $name;
             }
             return array("status" => true, "files" => $final);
             break;
         case "convert":
             /*
             				[file] => en/1-for-am-2-for-pm
             		    [name] => custom/ivr-okkkk-recording-1456170709
             		    [codec] => wav
             		    [lang] => en
             		    [temporary] => 0
             		    [command] => convert
             		    [module] => recordings
             */
             set_time_limit(0);
             $media = $this->FreePBX->Media;
             $file = $_POST['file'];
             $name = $_POST['name'];
             $codec = $_POST['codec'];
             $lang = $_POST['lang'];
             $temporary = $_POST['temporary'];
             if (!file_exists($this->path . "/" . $lang . "/custom")) {
                 mkdir($this->path . "/" . $lang . "/custom", 0777, true);
             }
             $name = preg_replace("/\\s+|'+|`+|\"+|<+|>+|\\?+|\\*|\\.+|&+/", "-", $name);
             if (!empty($codec)) {
                 if ($temporary) {
                     $media->load($this->temp . "/" . $file);
                 } else {
                     $f = $file == $name ? $name : str_replace($lang . "/", "", $file);
                     $status = $this->fileStatus($f);
                     if (!empty($status[$lang])) {
                         if (!empty($status[$lang][$codec])) {
                             $file = $lang . "/" . $status[$lang][$codec];
                         } else {
                             $file = $lang . "/" . reset($status[$lang]);
                         }
                     } else {
                         return array("status" => false, "message" => _("Can not find suitable file in this language"));
                     }
                     $media->load($this->path . "/" . $file);
                 }
                 if (!$temporary && file_exists($this->path . "/" . $lang . "/" . $name . "." . $codec) && $file == $name) {
                     return array("status" => true, "name" => $name);
                 }
                 try {
                     $media->convert($this->path . "/" . $lang . "/" . $name . "." . $codec);
                 } catch (\Exception $e) {
                     return array("status" => false, "message" => $e->getMessage() . " [" . $this->path . "/" . $file . "." . $codec . "]");
                 }
                 return array("status" => true, "name" => $name);
             } else {
                 $ext = pathinfo($file, PATHINFO_EXTENSION);
                 if ($temporary && file_exists($this->temp . "/" . $file)) {
                     rename($this->temp . "/" . $file, $this->path . "/" . $lang . "/" . $name . "." . $ext);
                     return array("status" => true, "name" => $name);
                 } else {
                     return array("status" => true, "name" => $name);
                 }
             }
             break;
         case "save":
             $data = $_POST;
             if ($data['id'] == "0" || !empty($data['id'])) {
                 $this->updateRecording($data['id'], $data['name'], $data['description'], implode("&", $data['playback']), $data['fcode'], $data['fcode_pass']);
             } else {
                 $this->addRecording($data['name'], $data['description'], implode("&", $data['playback']), $data['fcode'], $data['fcode_pass']);
             }
             if (!empty($data['remove'])) {
                 foreach ($data['remove'] as $file) {
                     $file = basename($file);
                     if (file_exists($this->temp . "/" . $file)) {
                         unlink($this->temp . "/" . $file);
                     }
                 }
             }
             return array("status" => true);
             break;
         case "savebrowserrecording":
             if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
                 $time = time() . rand(1, 1000);
                 $filename = basename($_REQUEST['filename']) . "-" . $time . ".wav";
                 move_uploaded_file($_FILES["file"]["tmp_name"], $this->temp . "/" . $filename);
                 return array("status" => true, "filename" => $_REQUEST['filename'], "localfilename" => $filename);
             } else {
                 return array("status" => false, "message" => _("Unknown Error"));
             }
             break;
         case "deleterecording":
             $files = json_decode($_POST['filenames'], true);
             foreach ($files as $lang => $file) {
                 $file = basename($file);
                 if (file_exists($this->temp . "/" . $file)) {
                     unlink($this->temp . "/" . $file);
                 }
             }
             return array("status" => true);
             break;
         case "dialrecording":
             $astman = $this->FreePBX->astman;
             $status = $astman->originate(array("Channel" => "Local/" . $_POST['extension'] . "@from-internal", "Exten" => "dorecord", "Context" => "systemrecording-gui", "Priority" => 1, "Async" => "no", "CallerID" => _("System Recordings"), "Variable" => "RECFILE=" . $this->temp . "/" . basename($_POST['filename'])));
             if ($status['Response'] == "Success") {
                 return array("status" => true);
             } else {
                 return array("status" => false, "message" => $status['Message']);
             }
             break;
         case "checkrecording":
             $filename = !empty($_POST['filename']) ? basename($_POST['filename']) : '';
             if (file_exists($this->temp . "/" . $filename . ".finished")) {
                 unlink($this->temp . "/" . $filename . ".finished");
                 return array("finished" => true, "filename" => $filename, "localfilename" => $filename . ".wav", "recording" => false);
             } elseif (file_exists($this->temp . "/" . $filename . ".wav")) {
                 return array("finished" => false, "recording" => true);
             } else {
                 return array("finished" => false, "recording" => false);
             }
             break;
         case "saverecording":
             $name = !empty($_POST['name']) ? basename($_POST['name']) : '';
             $filename = !empty($_POST['filename']) ? basename($_POST['filename']) : '';
             $time = time() . rand(1, 1000);
             $fname = $name . "-" . $time . ".wav";
             if (file_exists($this->temp . "/" . $filename . ".wav")) {
                 rename($this->temp . "/" . $filename . ".wav", $this->temp . "/" . $fname);
                 return array("status" => true, "filename" => $name, "localfilename" => $fname);
             } else {
                 return array("status" => false, "message" => _("File does not exist"));
             }
             break;
         case "grid":
             $all = $this->getAll();
             $languageNames = $this->FreePBX->Soundlang->getLanguages();
             foreach ($all as &$recs) {
                 foreach ($recs['languages'] as &$lang) {
                     $lang = isset($languageNames[$lang]) ? $languageNames[$lang] : $lang;
                 }
                 $recs['languages'] = implode(", ", $recs['languages']);
             }
             return $all;
             break;
         case "upload":
             foreach ($_FILES["files"]["error"] as $key => $error) {
                 switch ($error) {
                     case UPLOAD_ERR_OK:
                         $extension = pathinfo($_FILES["files"]["name"][$key], PATHINFO_EXTENSION);
                         $extension = strtolower($extension);
                         $supported = $this->FreePBX->Media->getSupportedFormats();
                         if (in_array($extension, $supported['in'])) {
                             $tmp_name = $_FILES["files"]["tmp_name"][$key];
                             $dname = \Media\Media::cleanFileName($_FILES["files"]["name"][$key]);
                             $dname = pathinfo($dname, PATHINFO_FILENAME);
                             $id = time() . rand(1, 1000);
                             $name = $dname . '-' . $id . '.' . $extension;
                             move_uploaded_file($tmp_name, $this->temp . "/" . $name);
                             return array("status" => true, "filename" => pathinfo($dname, PATHINFO_FILENAME), "localfilename" => $name, "id" => $id);
                         } else {
                             return array("status" => false, "message" => _("Unsupported file format"));
                             break;
                         }
                         break;
                     case UPLOAD_ERR_INI_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the upload_max_filesize directive in php.ini"));
                         break;
                     case UPLOAD_ERR_FORM_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"));
                         break;
                     case UPLOAD_ERR_PARTIAL:
                         return array("status" => false, "message" => _("The uploaded file was only partially uploaded"));
                         break;
                     case UPLOAD_ERR_NO_FILE:
                         return array("status" => false, "message" => _("No file was uploaded"));
                         break;
                     case UPLOAD_ERR_NO_TMP_DIR:
                         return array("status" => false, "message" => _("Missing a temporary folder"));
                         break;
                     case UPLOAD_ERR_CANT_WRITE:
                         return array("status" => false, "message" => _("Failed to write file to disk"));
                         break;
                     case UPLOAD_ERR_EXTENSION:
                         return array("status" => false, "message" => _("A PHP extension stopped the file upload"));
                         break;
                 }
             }
             return array("status" => false, "message" => _("Can Not Find Uploaded Files"));
             break;
     }
 }
 public function ajaxHandler()
 {
     switch ($_REQUEST['command']) {
         case "savebrowserrecording":
             if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
                 $time = time() . rand(1, 1000);
                 $filename = basename($_REQUEST['filename']) . "-" . $time . ".wav";
                 move_uploaded_file($_FILES["file"]["tmp_name"], $this->temp . "/" . $filename);
                 return array("status" => true, "filename" => $_REQUEST['filename'], "localfilename" => $filename);
             } else {
                 return array("status" => false, "message" => _("Unknown Error"));
             }
             break;
         case "upload":
             foreach ($_FILES["files"]["error"] as $key => $error) {
                 switch ($error) {
                     case UPLOAD_ERR_OK:
                         $extension = pathinfo($_FILES["files"]["name"][$key], PATHINFO_EXTENSION);
                         $extension = strtolower($extension);
                         $supported = $this->FreePBX->Media->getSupportedFormats();
                         if (in_array($extension, $supported['in'])) {
                             $tmp_name = $_FILES["files"]["tmp_name"][$key];
                             $dname = \Media\Media::cleanFileName($_FILES["files"]["name"][$key]);
                             $dname = pathinfo($dname, PATHINFO_FILENAME);
                             $id = time() . rand(1, 1000);
                             $name = $dname . '-' . $id . '.' . $extension;
                             move_uploaded_file($tmp_name, $this->temp . "/" . $name);
                             return array("status" => true, "filename" => pathinfo($dname, PATHINFO_FILENAME), "localfilename" => $name, "id" => $id);
                         } else {
                             return array("status" => false, "message" => _("Unsupported file format"));
                             break;
                         }
                         break;
                     case UPLOAD_ERR_INI_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the upload_max_filesize directive in php.ini"));
                         break;
                     case UPLOAD_ERR_FORM_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"));
                         break;
                     case UPLOAD_ERR_PARTIAL:
                         return array("status" => false, "message" => _("The uploaded file was only partially uploaded"));
                         break;
                     case UPLOAD_ERR_NO_FILE:
                         return array("status" => false, "message" => _("No file was uploaded"));
                         break;
                     case UPLOAD_ERR_NO_TMP_DIR:
                         return array("status" => false, "message" => _("Missing a temporary folder"));
                         break;
                     case UPLOAD_ERR_CANT_WRITE:
                         return array("status" => false, "message" => _("Failed to write file to disk"));
                         break;
                     case UPLOAD_ERR_EXTENSION:
                         return array("status" => false, "message" => _("A PHP extension stopped the file upload"));
                         break;
                 }
             }
             return array("status" => false, "message" => _("Can Not Find Uploaded Files"));
             break;
         case 'getJSON':
             switch ($_REQUEST['jdata']) {
                 case 'grid':
                     $ivrs = $this->getDetails();
                     $ret = array();
                     foreach ($ivrs as $r) {
                         $r['name'] = $r['name'] ? $r['name'] : 'IVR ID: ' . $r['id'];
                         $ret[] = array('name' => $r['name'], 'id' => $r['id'], 'link' => array($r['id'], $r['name']));
                     }
                     return $ret;
                     break;
                 default:
                     return false;
                     break;
             }
             break;
         default:
             return false;
             break;
     }
 }
 /**
  * The Handler for all ajax events releated to this class
  *
  * Used by Ajax Class to process commands
  *
  * @return mixed Output if success, otherwise false will generate a 500 error serverside
  */
 function ajaxHandler()
 {
     $return = array("status" => false, "message" => "");
     switch ($_REQUEST['command']) {
         case 'refreshfoldercount':
             $folders = $this->UCP->FreePBX->Voicemail->getFolders();
             foreach ($folders as $folder) {
                 $folders[$folder['folder']]['count'] = $this->UCP->FreePBX->Voicemail->getMessagesCountByExtensionFolder($_REQUEST['ext'], $folder['folder']);
             }
             return array("status" => true, "folders" => $folders);
             break;
         case 'gethtml5':
             $media = $this->UCP->FreePBX->Media();
             $message = $this->UCP->FreePBX->Voicemail->getMessageByMessageIDExtension($_REQUEST['msg_id'], $_REQUEST['ext']);
             $file = $message['path'] . "/" . $message['file'];
             if (file_exists($file)) {
                 $media->load($file);
                 $files = $media->generateHTML5();
                 $final = array();
                 foreach ($files as $format => $name) {
                     $final[$format] = "index.php?quietmode=1&module=voicemail&command=playback&file=" . $name . "&ext=" . $_REQUEST['ext'];
                 }
                 return array("status" => true, "files" => $final);
             } else {
                 return array("status" => false, "message" => _("File does not exist"));
             }
             break;
         case 'grid':
             $folder = $_REQUEST['folder'];
             $limit = $_REQUEST['limit'];
             $order = $_REQUEST['order'];
             $orderby = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : "date";
             $ext = $_REQUEST['ext'];
             $search = !empty($_REQUEST['search']) ? $_REQUEST['search'] : "";
             $offset = $_REQUEST['offset'];
             $data = $this->UCP->FreePBX->Voicemail->getMessagesByExtensionFolder($ext, $folder, $order, $orderby, $offset, $limit);
             $messages = array();
             if (!empty($data['messages'])) {
                 foreach ($data['messages'] as $message) {
                     $message['callerid'] = htmlentities($message['callerid'], ENT_COMPAT | ENT_HTML401, "UTF-8");
                     $message['callerid'] = preg_replace("/&lt;(.*)&gt;/i", "&lt;<span class='clickable' data-type='number' data-primary='phone'>\$1</span>&gt;", $message['callerid']);
                     $messages[] = $message;
                 }
             }
             return array("total" => $this->UCP->FreePBX->Voicemail->getMessagesCountByExtensionFolder($ext, $folder), "rows" => $messages);
             break;
         case 'callme':
             $validUsers = array();
             $users = $this->UCP->FreePBX->Voicemail->getUsersList(true);
             foreach ($users as $user) {
                 $validUsers[] = $user[0];
             }
             if (!in_array($_POST['to'], $validUsers)) {
                 $return['message'] = _("Invalid Recipient");
                 return $return;
             }
             $message = $this->UCP->FreePBX->Voicemail->getMessageByMessageIDExtension($_POST['id'], $_REQUEST['ext']);
             if (!empty($message)) {
                 $astman = $this->UCP->FreePBX->astman;
                 $status = $astman->originate(array("Channel" => "Local/" . $_POST['to'] . "@from-internal", "Exten" => "s", "Context" => "vm-callme", "Priority" => 1, "Async" => "yes", "CallerID" => _("Voicemail Message") . " <" . _("VMAIL") . ">", "Variable" => "MSG=" . $message['path'] . "/" . $message['fid'] . ",MBOX=" . $_REQUEST['ext']));
                 if ($status['Response'] == "Success") {
                     $return['status'] = true;
                 } else {
                     $return['message'] = $status['Message'];
                 }
             }
             $return['message'] = "Invalid Message ID";
             return $return;
             break;
         case 'forward':
             $validUsers = array();
             $users = $this->UCP->FreePBX->Voicemail->getUsersList(true);
             foreach ($users as $user) {
                 $validUsers[] = $user[0];
             }
             if (!in_array($_POST['to'], $validUsers)) {
                 $return['message'] = _("Invalid Recipient");
                 return $return;
             }
             $message = $this->UCP->FreePBX->Voicemail->getMessageByMessageIDExtension($_POST['id'], $_REQUEST['ext']);
             if (!empty($message)) {
                 $this->UCP->FreePBX->Voicemail->forwardMessageByExtension($_POST['id'], $_REQUEST['ext'], $_POST['to']);
                 $return['status'] = true;
             } else {
                 $return['message'] = "Invalid Message ID";
             }
             return $return;
             break;
         case 'forwards':
             $return = array();
             $users = $this->UCP->FreePBX->Voicemail->getUsersList(true);
             $search = !empty($_REQUEST['search']) ? $_REQUEST['search'] : '';
             foreach ($users as $user) {
                 if (preg_match('/' . $search . '/i', $user[1]) || preg_match('/' . $search . '/i', $user[0])) {
                     $return[] = array("value" => $user[0], "text" => $user[1] . " (" . $user[0] . ")");
                 }
             }
             return $return;
             break;
         case 'vmxsettings':
             if (!$this->_checkVmX($_POST['ext'])) {
                 return false;
             }
             switch ($_POST['settings']['key']) {
                 case 'vmx-state':
                     $m = $_POST['settings']['value'] == 'true' ? 'enabled' : 'disabled';
                     if ($m == "disabled" && $this->Vmx->isInitialized($_POST['ext'])) {
                         $this->Vmx->disable($_POST['ext']);
                     } else {
                         $this->Vmx->setState($_POST['ext'], 'unavail', 'disabled');
                     }
                     break;
                 case 'vmx-usewhen-unavailable':
                     $m = $_POST['settings']['value'] == 'true' ? 'enabled' : 'disabled';
                     $this->Vmx->setState($_POST['ext'], 'unavail', $m);
                     break;
                 case 'vmx-usewhen-busy':
                     $m = $_POST['settings']['value'] == 'true' ? 'enabled' : 'disabled';
                     $this->Vmx->setState($_POST['ext'], 'busy', $m);
                     break;
                 case 'vmx-usewhen-temp':
                     $m = $_POST['settings']['value'] == 'true' ? 'enabled' : 'disabled';
                     $this->Vmx->setState($_POST['ext'], 'temp', $m);
                     break;
                 case 'vmx-opt0':
                     $this->Vmx->setMenuOpt($_POST['ext'], $_POST['settings']['value'], '0', 'unavail');
                     $this->Vmx->setMenuOpt($_POST['ext'], $_POST['settings']['value'], '0', 'busy');
                     $this->Vmx->setMenuOpt($_POST['ext'], $_POST['settings']['value'], '0', 'temp');
                     break;
                 case 'vmx-opt1':
                     if (empty($_POST['settings']['value'])) {
                         $this->Vmx->setFollowMe($_POST['ext'], '1', 'unavail');
                         $this->Vmx->setFollowMe($_POST['ext'], '1', 'busy');
                         $this->Vmx->setFollowMe($_POST['ext'], '1', 'temp');
                     } else {
                         $this->Vmx->setMenuOpt($_POST['ext'], $_POST['settings']['value'], '1', 'unavail');
                         $this->Vmx->setMenuOpt($_POST['ext'], $_POST['settings']['value'], '1', 'busy');
                         $this->Vmx->setMenuOpt($_POST['ext'], $_POST['settings']['value'], '1', 'temp');
                     }
                     break;
                 case 'vmx-opt2':
                     $this->Vmx->setMenuOpt($_POST['ext'], $_POST['settings']['value'], '2', 'unavail');
                     $this->Vmx->setMenuOpt($_POST['ext'], $_POST['settings']['value'], '2', 'busy');
                     $this->Vmx->setMenuOpt($_POST['ext'], $_POST['settings']['value'], '2', 'temp');
                     break;
                 default:
                     return false;
                     break;
             }
             $return = array("status" => true, "message" => "Saved", "alert" => "success");
             break;
         case 'checkboxes':
             $boxes = $this->getMailboxCount($this->extensions);
             return array("status" => true, "total" => $boxes['total'], "boxes" => $boxes['extensions']);
             break;
         case 'moveToFolder':
             $ext = $_POST['ext'];
             $status = $this->UCP->FreePBX->Voicemail->moveMessageByExtensionFolder($_POST['msg'], $ext, $_POST['folder']);
             $return = array("status" => $status, "message" => "");
             break;
         case 'delete':
             $ext = $_POST['ext'];
             $status = $this->UCP->FreePBX->Voicemail->deleteMessageByID($_POST['msg'], $ext);
             $return = array("status" => $status, "message" => "");
             break;
         case 'savesettings':
             $ext = $_POST['ext'];
             $saycid = $_POST['saycid'] == 'true' ? true : false;
             $envelope = $_POST['envelope'] == 'true' ? true : false;
             $delete = $_POST['vmdelete'] == 'true' ? true : false;
             $attach = $_POST['attach'] == 'true' ? true : false;
             $status = $this->UCP->FreePBX->Voicemail->saveVMSettingsByExtension($ext, $_POST['pwd'], $_POST['email'], $_POST['pager'], $saycid, $envelope, $attach, $delete);
             $return = array("status" => $status, "message" => "");
             break;
         case "upload":
             $return = array("status" => true, "message" => "");
             foreach ($_FILES["files"]["error"] as $key => $error) {
                 if ($error == UPLOAD_ERR_OK) {
                     $tmp_path = \FreePBX::Config()->get("ASTSPOOLDIR") . "/tmp";
                     if (!file_exists($tmp_path)) {
                         mkdir($tmp_path, 0777, true);
                     }
                     $extension = pathinfo($_FILES["files"]["name"][$key], PATHINFO_EXTENSION);
                     $supported = $this->UCP->FreePBX->Media->getSupportedFormats();
                     if (in_array($extension, $supported['in'])) {
                         $tmp_name = $_FILES["files"]["tmp_name"][$key];
                         $name = \Media\Media::cleanFileName($_FILES["files"]["name"][$key]);
                         if (!file_exists($tmp_path . "/vmtmp")) {
                             mkdir($tmp_path . "/vmtmp");
                         }
                         move_uploaded_file($tmp_name, $tmp_path . "/vmtmp/{$name}");
                         if (!file_exists($tmp_path . "/vmtmp/{$name}")) {
                             $return = array("status" => false, "message" => sprintf(_("Voicemail not moved to %s"), $tmp_path . "/vmtmp/" . $name));
                             break;
                         }
                         $this->UCP->FreePBX->Voicemail->saveVMGreeting($_REQUEST['ext'], $_REQUEST['type'], $extension, $tmp_path . "/vmtmp/{$name}");
                     } else {
                         $return = array("status" => false, "message" => _("Unsupported file format"));
                         break;
                     }
                 }
             }
             break;
         case "copy":
             $status = $this->UCP->FreePBX->Voicemail->copyVMGreeting($_POST['ext'], $_POST['source'], $_POST['target']);
             $return = array("status" => $status, "message" => "");
             break;
         case "record":
             $return = array("status" => true, "message" => "");
             if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
                 $tmp_path = sys_get_temp_dir();
                 $tmp_path = !empty($tmp_path) ? $tmp_path : '/tmp';
                 $tmp_name = $_FILES["file"]["tmp_name"];
                 $name = $_FILES["file"]["name"];
                 if (!file_exists($tmp_path . "/vmtmp")) {
                     mkdir($tmp_path . "/vmtmp");
                 }
                 move_uploaded_file($tmp_name, $tmp_path . "/vmtmp/{$name}");
                 if (!file_exists($tmp_path . "/vmtmp/{$name}")) {
                     $return = array("status" => false, "message" => sprintf(_("Voicemail not moved to %s"), $tmp_path . "/vmtmp/" . $name));
                     break;
                 }
                 $contents = file_get_contents($tmp_path . "/vmtmp/{$name}");
                 if (empty($contents)) {
                     $return = array("status" => false, "message" => sprintf(_("Voicemail was empty: %s"), $tmp_path . "/vmtmp/" . $name));
                     break;
                 }
                 $this->UCP->FreePBX->Voicemail->saveVMGreeting($_REQUEST['ext'], $_REQUEST['type'], 'wav', $tmp_path . "/vmtmp/{$name}");
             } else {
                 $return = array("status" => false, "message" => _("Unknown Error"));
                 break;
             }
             break;
         default:
             return false;
             break;
     }
     return $return;
 }
 public function ajaxHandler()
 {
     switch ($_REQUEST['command']) {
         case "deletemusic":
             $category = $this->getCategoryByID($_POST['categoryid']);
             if (empty($category)) {
                 return array("status" => false, "message" => _("Invalid category"));
             }
             $path = $this->getCategoryPath($category['category']);
             foreach (glob($path . "/" . $_POST['name'] . "*") as $file) {
                 if (!unlink($file)) {
                     return array("status" => false, "message" => sprintf(_("Unable to delete %s"), $file));
                     break;
                 }
             }
             return array("status" => true);
             break;
         case "save":
             if ($_POST['type'] == "files") {
                 //do conversions here whooooo
                 $media = $this->FreePBX->Media();
                 $category = $this->getCategoryByID($_POST['id']);
                 $path = $this->getCategoryPath($category['category']);
                 $files = $this->fileList($path);
                 foreach ($files as $file) {
                     $name = pathinfo($file, PATHINFO_FILENAME);
                     $media->load($path . "/" . $file);
                     foreach ($_POST['codecs'] as $codec) {
                         $fpath = $path . "/" . $name . "." . $codec;
                         if (!file_exists($fpath)) {
                             $media->convert($fpath);
                         }
                     }
                 }
             }
             $this->updateCategoryByID($_POST['id'], $_POST['type'], $_POST['erand'] == "yes", $_POST['application'], $_POST['format']);
             return array("status" => true);
             break;
         case "deleteCategory":
             if (empty($_POST['name']) || empty($_POST['categoryid'])) {
                 return array("status" => false);
             }
             $category = $this->getCategoryByID($_REQUEST['categoryid']);
             $path = $this->getCategoryPath($category['category']);
             $name = basename($_POST['name']);
             foreach (glob($path . "/" . $name . "*") as $file) {
                 unlink($file);
             }
             return array("status" => true);
             break;
         case "upload":
             // XXX If the posted file was too large,
             // we will get here, but $_FILES is empty!
             // Specifically, if the file that was posted is
             // larger than 'post_max_size' in php.ini.
             // So, php will throw an error, as index
             // $_FILES["files"] does not exist, because
             // $_FILES is empty.
             if (!isset($_FILES)) {
                 return array("status" => false, "message" => _("File upload failed"));
             }
             foreach ($_FILES["files"]["error"] as $key => $error) {
                 switch ($error) {
                     case UPLOAD_ERR_OK:
                         $extension = pathinfo($_FILES["files"]["name"][$key], PATHINFO_EXTENSION);
                         $extension = strtolower($extension);
                         $supported = $this->FreePBX->Media->getSupportedFormats();
                         $category = $this->getCategoryByID($_POST['id']);
                         $path = $this->getCategoryPath($category['category']);
                         $media = $this->FreePBX->Media();
                         if (in_array($extension, $supported['in'])) {
                             $tmp_name = $_FILES["files"]["tmp_name"][$key];
                             $dname = \Media\Media::cleanFileName($_FILES["files"]["name"][$key]);
                             $dname = pathinfo($dname, PATHINFO_FILENAME);
                             $name = $dname . '.' . $extension;
                             move_uploaded_file($tmp_name, $this->tmp . "/" . $name);
                             $media->load($this->tmp . "/" . $name);
                             foreach ($_POST['codec'] as $c) {
                                 $media->convert($path . "/" . $dname . "." . $c);
                             }
                             unlink($this->tmp . "/" . $name);
                             return array("status" => true, "name" => $dname, "filename" => $name, "formats" => $_POST['codec'], "category" => $category['category'], "categoryid" => $_POST['id']);
                         } else {
                             return array("status" => false, "message" => _("Unsupported file format"));
                             break;
                         }
                         break;
                     case UPLOAD_ERR_INI_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the upload_max_filesize directive in php.ini"));
                         break;
                     case UPLOAD_ERR_FORM_SIZE:
                         return array("status" => false, "message" => _("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"));
                         break;
                     case UPLOAD_ERR_PARTIAL:
                         return array("status" => false, "message" => _("The uploaded file was only partially uploaded"));
                         break;
                     case UPLOAD_ERR_NO_FILE:
                         return array("status" => false, "message" => _("No file was uploaded"));
                         break;
                     case UPLOAD_ERR_NO_TMP_DIR:
                         return array("status" => false, "message" => _("Missing a temporary folder"));
                         break;
                     case UPLOAD_ERR_CANT_WRITE:
                         return array("status" => false, "message" => _("Failed to write file to disk"));
                         break;
                     case UPLOAD_ERR_EXTENSION:
                         return array("status" => false, "message" => _("A PHP extension stopped the file upload"));
                         break;
                 }
             }
             return array("status" => false, "message" => _("Can Not Find Uploaded Files"));
             break;
         case "gethtml5":
             $media = $this->FreePBX->Media();
             $category = $this->getCategoryByID($_REQUEST['categoryid']);
             $path = $this->getCategoryPath($category['category']);
             $file = $path . "/" . $_REQUEST['file'];
             if (file_exists($file)) {
                 $media->load($file);
                 $files = $media->generateHTML5();
                 $final = array();
                 foreach ($files as $format => $name) {
                     $final[$format] = "ajax.php?module=music&command=playback&file=" . $name;
                 }
                 return array("status" => true, "files" => $final);
             } else {
                 return array("status" => false, "message" => _("File does not exist"));
             }
             break;
         case "getJSON":
             switch ($_REQUEST['jdata']) {
                 case 'categories':
                     return $this->getCategories();
                     break;
                 case 'musiclist':
                     $category = $this->getCategoryByID($_REQUEST['id']);
                     $path = $this->getCategoryPath($category['category']);
                     $files = array();
                     $count = 0;
                     $list = $this->fileList($path);
                     asort($list);
                     foreach ($list as $value) {
                         $fp = pathinfo($value);
                         if (!isset($files[$fp['filename']])) {
                             $files[$fp['filename']] = array('categoryid' => $category['id'], 'category' => $category['category'], 'id' => $count, 'filename' => $value, 'name' => $fp['filename'], 'formats' => array($fp['extension']));
                             $count++;
                         } else {
                             $files[$fp['filename']]['formats'][] = $fp['extension'];
                         }
                     }
                     return array_values($files);
                     break;
                 default:
                     print json_encode(_("Invalid Request"));
                     break;
             }
             break;
     }
 }