예제 #1
0
파일: core.class.php 프로젝트: hardikk/HNH
 /**
  * Functional point that adds a new event in the calendar of the authenticated user
  *
  * @param   date      $startdate                 Starting date and time of event
  * @param   date      $enddate                   Ending date and time of event
  * @param   string    $subject                   Subject of event
  * @param   string    $description               Long description of event
  * @param   boolean   $asterisk_call             TRUE if must be generated reminder call
  * @param   string    $recording                 (Optional)  Name of the recording used to call
  * @param   string    $call_to                   (Optional) Extension to which call for Reminder
  * @param   string    $reminder_timer            (Optional) Number of minutes before which will make the call reminder
  * @param   array     $emails_notification       Zero or more emails will be notified with a message when creating the event.
  * @param   string    $color                     (Optional) Color for the event
  * @return  boolean   True if the event was successfully created, or false if an error exists
  */
 function addCalendarEvent($startdate, $enddate, $subject, $description, $asterisk_call, $recording, $call_to, $reminder_timer, $emails_notification, $color, $getIdInserted = FALSE)
 {
     global $arrConf;
     if (!$this->_checkUserAuthorized('calendar')) {
         return false;
     }
     // Identificar el usuario para averiguar el ID de usuario en calendario
     $id_user = $this->_leerIdUser();
     if (is_null($id_user)) {
         return false;
     }
     // Validación de instantes de inicio y final
     $sFechaInicio = $this->_checkDateTimeFormat(isset($startdate) ? $startdate : NULL);
     $sFechaFinal = $this->_checkDateTimeFormat(isset($enddate) ? $enddate : NULL);
     if (is_null($sFechaInicio) || is_null($sFechaFinal)) {
         return false;
     }
     if ($sFechaFinal < $sFechaInicio) {
         $t = $sFechaFinal;
         $sFechaFinal = $sFechaInicio;
         $sFechaInicio = $t;
     }
     // Verificar presencia de asunto y descripción
     if (!isset($subject) || trim($subject) == '') {
         $this->errMsg["fc"] = 'PARAMERROR';
         $this->errMsg["fm"] = 'Invalid subject';
         $this->errMsg["fd"] = 'Subject must be specified and nonempty';
         $this->errMsg["cn"] = get_class($this);
         return false;
     }
     if (!isset($description) || trim($description) == '') {
         $this->errMsg["fc"] = 'PARAMERROR';
         $this->errMsg["fm"] = 'Invalid description';
         $this->errMsg["fd"] = 'Description must be specified and nonempty';
         $this->errMsg["cn"] = get_class($this);
         return false;
     }
     // Validaciones dependientes de asterisk_call
     if (!isset($asterisk_call) || $asterisk_call !== TRUE && $asterisk_call !== FALSE) {
         $this->errMsg["fc"] = 'PARAMERROR';
         $this->errMsg["fm"] = 'Invalid reminder flag';
         $this->errMsg["fd"] = 'Reminder flag must be specified and be a boolean';
         $this->errMsg["cn"] = get_class($this);
         return false;
     }
     $listaAudios = array();
     $sExtUsuario = $this->_leerExtension();
     if (!$asterisk_call) {
         // Ninguno de estos valores se usa cuando no hay llamada
         $recording = NULL;
         $call_to = NULL;
         $reminder_timer = NULL;
     } else {
         // Si reminder_timer no es entero positivo, se asume 0
         if (!isset($reminder_timer) || !preg_match('/^\\d+$/', $reminder_timer)) {
             $reminder_timer = 0;
         }
         // Número a marcar debería ser cadena numérica
         if (!isset($call_to)) {
             $call_to = $sExtUsuario;
         }
         if (!preg_match('/^\\d+$/', $call_to)) {
             $this->errMsg["fc"] = 'PARAMERROR';
             $this->errMsg["fm"] = 'Invalid reminder dialout number';
             $this->errMsg["fd"] = 'Reminder dialout number (call_to) must be specified and be a numeric string';
             $this->errMsg["cn"] = get_class($this);
             return false;
         }
         // Verificar que la grabación se ha especificado y existe
         $listaAudios = $this->_listarAudiosExtension($sExtUsuario);
         if (!is_array($listaAudios)) {
             return NULL;
         }
         if (!isset($listaAudios[$recording])) {
             $this->errMsg["fc"] = 'PARAMERROR';
             $this->errMsg["fm"] = 'Invalid recording';
             $this->errMsg["fd"] = 'Specified recording not found.';
             $this->errMsg["cn"] = get_class($this);
             return false;
         }
     }
     if (!isset($emails_notification)) {
         $emails_notification = array();
     }
     if (!is_array($emails_notification)) {
         $emails_notification = array($emails_notification);
     }
     /* Construir cadena de correos en 1era forma ANORMAL. Se requiere la 
      * coma al final porque la interfaz web se come el último elemento al
      * mostrar la lista de correos. Además, los nombres descriptivos deben
      * estar encerrados en comillas dobles, y los correos tienen que estar
      * encerrados entre mayor y menor que. Todo esto se requiere para que
      * la interfaz funcione correctamente al mostrar los correos al editar. 
      */
     if (count($emails_notification) == 0) {
         $sCadenaCorreo = '';
     } else {
         function canonicalizar_correo($x)
         {
             $regs = NULL;
             if (preg_match('/^\\s*"?([^"]*)"?\\s*<(\\S*)>\\s*$/', $x, $regs)) {
                 $sNombre = '';
                 if (trim($regs[1]) != '') {
                     $sNombre = "\"{$regs[1]}\" ";
                 }
                 return "{$sNombre}<{$regs[2]}>";
             } else {
                 return "<{$x}>";
             }
         }
         $sCadenaCorreo = implode(', ', array_map('canonicalizar_correo', $emails_notification)) . ',';
     }
     $color = isset($color) ? $color : "#3366CC";
     /* Insertar el registro del nuevo evento. */
     $dbCalendar = $this->_getDB($arrConf['dsn_conn_database']);
     $pCalendar = new paloSantoCalendar($dbCalendar);
     $r = $pCalendar->insertEvent($id_user, substr($sFechaInicio, 0, 10), substr($sFechaFinal, 0, 10), substr($sFechaInicio, 0, 16), 1, $subject, $description, $asterisk_call ? 'on' : 'off', $asterisk_call ? $recording : '', $asterisk_call ? $call_to : '', count($emails_notification) > 0 ? 'on' : 'off', $sCadenaCorreo, substr($sFechaFinal, 0, 16), 1, substr(date("D", strtotime("2010-11-04 12:54:00")), 0, 2) . ",", $asterisk_call ? $reminder_timer : '', $color);
     if (!$r) {
         $this->errMsg["fc"] = 'DBERROR';
         $this->errMsg["fm"] = 'Database operation failed';
         $this->errMsg["fd"] = 'Unable to create event in calendar - ' . $pCalendar->errMsg;
         $this->errMsg["cn"] = get_class($pCalendar);
         return false;
     }
     $idEvento = $pCalendar->_DB->getLastInsertId();
     // Crear el archivo de llamada, en caso necesario
     if ($asterisk_call) {
         $this->_crearArchivoLlamadaAsterisk($idEvento, $sExtUsuario, $call_to, $listaAudios[$recording], 2, strtotime($sFechaInicio . ($reminder_timer > 0 ? " - {$reminder_timer} second" : '')));
     }
     // Enviar los correos de notificación, en caso necesario
     if (count($emails_notification) > 0) {
         $this->_enviarCorreosNotificacionEvento($idEvento, $sFechaInicio, $sFechaFinal, $subject, $emails_notification, $description, 'New_Event');
     }
     if ($getIdInserted) {
         return $dbCalendar->getLastInsertId();
     } else {
         return true;
     }
 }
예제 #2
0
function saveEvent($smarty, $module_name, $local_templates_dir, &$pDB, $arrConf, $arrLang)
{
    $pCalendar = new paloSantoCalendar($pDB);
    $user = isset($_SESSION['elastix_user']) ? $_SESSION['elastix_user'] : "";
    $uid = Obtain_UID_From_User($user, $arrConf);
    $pDB3 = new paloDB($arrConf['dsn_conn_database1']);
    $ext = $pCalendar->obtainExtension($pDB3, $uid);
    $_DATA = $_POST;
    $action = getParameter("action");
    $id = getParameter("id_event");
    $event = getParameter("event");
    $description = getParameter("description");
    $date_ini = getParameter("date");
    $date_end = getParameter("to");
    $color = getParameter("colorHex");
    // options call reminder
    $reminder = getParameter("reminder");
    // puede ser on o off
    $call_to = getParameter("call_to");
    // elemento Call to
    $remainerTime = getParameter("ReminderTime");
    // tiempo de recordatorio 10, 20, 30 minutos antes
    $recording = getParameter("tts");
    // options email notification
    $notification = getParameter("notification");
    // puede ser on o off
    $notification_email = getParameter("notification_email");
    // si es notification==off => no se toma en cuenta esta variable
    $list = getParameter("emails");
    $hora = date('H', strtotime($date_ini));
    $minuto = date('i', strtotime($date_ini));
    $hora2 = date('H', strtotime($date_end));
    $minuto2 = date('i', strtotime($date_end));
    $asterisk_calls = "";
    $each_repeat = 1;
    $repeat = "none";
    $event_type = 0;
    if (!ctype_digit($id)) {
        $id = NULL;
    }
    if (!preg_match("/^#\\w{3,6}\$/", $color)) {
        $color = "#3366CC";
    }
    $_GET['event_date'] = date("Y-m-d", strtotime($date_ini));
    $start_event = strtotime($date_ini);
    $end_event = strtotime($date_end);
    $end_event2 = $end_event;
    //validar si la primera fecha es menor que la segunda
    if ($event != "") {
        if ($start_event <= $end_event) {
            if ($reminder == "on") {
                //Configure a phone call reminder
                $asterisk_calls = $reminder;
                if ($asterisk_calls == "on") {
                    // si es on entonces el campo call_to es vacio
                    if ($call_to == null || $call_to == "") {
                        $link = "<a href='?menu=userlist'>" . $arrLang['user_list'] . "</a>";
                        $smarty->assign("mb_message", $arrLang['error_ext'] . $link);
                        $content = viewForm_NewEvent($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
                        return $content;
                    }
                } else {
                    // se asigna una extension cualquiera
                    if ($call_to == "") {
                        $smarty->assign("mb_message", $arrLang['error_call_to']);
                        $content = viewForm_NewEvent($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
                        return $content;
                    }
                }
                // Número a llamar sólo puede ser numérico
                if (!preg_match('/^\\d+$/', $call_to)) {
                    $smarty->assign("mb_message", _tr('Invalid extension to call for reminder'));
                    $content = viewForm_NewEvent($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
                    return $content;
                }
                // Texto a generar no debe contener saltos de línea
                if (count(preg_split("/[\r\n]+/", $recording)) > 1) {
                    $smarty->assign("mb_message", _tr('Reminder text may not have newlines'));
                    $content = viewForm_NewEvent($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
                    return $content;
                }
            } else {
                $call_to = "";
                $asterisk_calls = "off";
                $recording = "";
                $remainerTime = "";
            }
            if ($notification == "on") {
                // si ingresa emails o contactos
                $list = htmlspecialchars_decode($list);
                // codifica los caracteres especiales
                $notification_email = $list;
            } else {
                $notification_email = "";
                $notification = "off";
            }
            $start = date('Y-m-d', $start_event);
            $end = date('Y-m-d', $end_event);
            $checkbox_days = getConvertDay($start_event);
            $starttime = date('Y-m-d', $start_event) . " " . $hora . ":" . $minuto;
            $endtime = date('Y-m-d', $end_event2) . " " . $hora2 . ":" . $minuto2;
            $day_repeat = explode(',', $checkbox_days);
            $event_type = 1;
            $num_frec = 0;
            if ($repeat == "none") {
                //solo un dia
                $event_type = 1;
                $num_frec = 0;
            }
            if ($repeat == "each_day") {
                //dias que se repiten durante un numero de semanas
                $event_type = 5;
                $num_frec = 7;
            }
            if ($repeat == "each_month") {
                //dias que se repiten durante un numero de meses
                $event_type = 6;
                $num_frec = 30;
            }
            // dataToSendEmail
            $data_Send['emails_notification'] = $notification_email;
            $data_Send['startdate'] = $start;
            $data_Send['enddate'] = $end;
            $data_Send['starttime'] = $starttime;
            $data_Send['eventtype'] = $event_type;
            $data_Send['subject'] = $event;
            $data_Send['description'] = $description;
            $data_Send['endtime'] = $endtime;
            if (getParameter("save_edit")) {
                // si se va modificar un evento existente
                $dataUp = $pCalendar->getEventById($id, $uid);
                if ($dataUp != "" && isset($dataUp)) {
                    $val = $pCalendar->updateEvent($id, $start, $end, $starttime, $event_type, $event, $description, $asterisk_calls, $recording, $call_to, $notification, $notification_email, $endtime, $each_repeat, $checkbox_days, $remainerTime, $color);
                } else {
                    $val = false;
                }
                if ($val == true) {
                    if ($notification_email != "") {
                        sendMails($data_Send, $arrLang, "UPDATE", $arrConf, $pDB, $module_name, $id);
                    }
                    if ($reminder == "on") {
                        createRepeatAudioFile($each_repeat, $day_repeat, $starttime, $endtime, $num_frec, $asterisk_calls, $ext, $call_to, $pDB, $id, $arrLang, $arrConf, $recording, $remainerTime);
                    } else {
                        //borra los .call que existan asociados a este evento
                        $dir_outgoing = $arrConf['dir_outgoing'];
                        system("rm -f {$dir_outgoing}/event_{$id}_*.call");
                        // si existen lo archivos los elimina
                    }
                    $smarty->assign("mb_message", $arrLang['update_successful']);
                    $content = viewCalendar($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
                    return $content;
                } else {
                    $smarty->assign("mb_message", $arrLang['error_update']);
                    $content = viewCalendar($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
                    return $content;
                }
            } else {
                if (getParameter("save_new")) {
                    // si se va a ingresar un nuevo evento
                    $val = $pCalendar->insertEvent($uid, $start, $end, $starttime, $event_type, $event, $description, $asterisk_calls, $recording, $call_to, $notification, $notification_email, $endtime, $each_repeat, $checkbox_days, $remainerTime, $color);
                    $id = $pDB->getLastInsertId();
                    if ($val == true) {
                        if ($notification_email != "") {
                            sendMails($data_Send, $arrLang, "NEW", $arrConf, $pDB, $module_name, $id);
                        }
                        if ($reminder == "on") {
                            createRepeatAudioFile($each_repeat, $day_repeat, $starttime, $endtime, $num_frec, $asterisk_calls, $ext, $call_to, $pDB, $id, $arrLang, $arrConf, $recording, $remainerTime);
                        }
                        $smarty->assign("mb_message", $arrLang['insert_successful']);
                        $content = viewCalendar($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
                        return $content;
                    } else {
                        $smarty->assign("mb_message", $arrLang['error_insert']);
                        $content = viewCalendar($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
                        return $content;
                    }
                } else {
                    $smarty->assign("mb_message", $arrLang['error_insert']);
                    $content = viewCalendar($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
                    return $content;
                }
            }
        } else {
            $smarty->assign("mb_message", $arrLang['error_date']);
            $content = viewCalendar($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
            return $content;
        }
    } else {
        $smarty->assign("mb_message", $arrLang['error_eventName']);
        $content = viewCalendar($smarty, $module_name, $local_templates_dir, $pDB, $arrConf, $arrLang);
        return $content;
    }
}