diff --git a/application/config/constants.php b/application/config/constants.php index 621f58ecb..ef4cdaf2c 100644 --- a/application/config/constants.php +++ b/application/config/constants.php @@ -127,37 +127,25 @@ define('EMAIL_CONFIG_INDEX', 'mail'); | Messaging system constants |-------------------------------------------------------------------------- */ -// Email kontakt type -define('EMAIL_KONTAKT_TYPE', 'email'); -// tbl_msg_recipient->sentInfo separator -define('SENT_INFO_NEWLINE', '\n'); - // Message statuses define('MSG_STATUS_UNREAD', 0); define('MSG_STATUS_READ', 1); define('MSG_STATUS_ARCHIVED', 2); define('MSG_STATUS_DELETED', 3); -// Priority -define('PRIORITY_LOW', 1); -define('PRIORITY_NORMAL', 2); -define('PRIORITY_HIGH', 3); -define('PRIORITY_URGENT', 4); +// Message priorities +define('MSG_PRIORITY_LOW', 1); +define('MSG_PRIORITY_NORMAL', 2); +define('MSG_PRIORITY_HIGH', 3); +define('MSG_PRIORITY_URGENT', 4); -define('MSG_ERR_SUBJECT_EMPTY', 40); -define('MSG_ERR_BODY_EMPTY', 41); -define('MSG_ERR_TEMPLATE_NOT_FOUND', 42); -define('MSG_ERR_DELIVERY_MESSAGE', 43); -define('MSG_ERR_CONTACT_NOT_FOUND', 44); -define('MSG_ERR_OU_CONTACTS_NOT_FOUND', 45); - -define('MSG_ERR_INVALID_USER_ID', 100); -define('MSG_ERR_INVALID_MSG_ID', 101); -define('MSG_ERR_INVALID_THREAD_ID', 102); -define('MSG_ERR_INVALID_STATUS_ID', 103); -define('MSG_ERR_INVALID_SENDER_ID', 104); -define('MSG_ERR_INVALID_RECIPIENTS', 105); -define('MSG_ERR_INVALID_RECEIVER_ID', 106); -define('MSG_ERR_INVALID_OU', 107); -define('MSG_ERR_INVALID_TEMPLATE', 108); -define('MSG_ERR_INVALID_TOKEN', 109); +// Message error status +define('MSG_ERR_INVALID_SUBJECT', 40); +define('MSG_ERR_INVALID_BODY', 41); +define('MSG_ERR_INVALID_TEMPLATE', 42); +define('MSG_ERR_INVALID_MSG_ID', 43); +define('MSG_ERR_INVALID_STATUS_ID', 44); +define('MSG_ERR_INVALID_SENDER', 45); +define('MSG_ERR_INVALID_RECIPIENTS', 46); +define('MSG_ERR_INVALID_OU', 47); +define('MSG_ERR_INVALID_TOKEN', 48); diff --git a/application/config/mail.php b/application/config/mail.php index 2163bc122..9d577720d 100644 --- a/application/config/mail.php +++ b/application/config/mail.php @@ -29,3 +29,6 @@ $config['wrapchars'] = 76; // Character count to wrap at. $config['mailtype'] = 'html'; // html or text $config['priority'] = 3; // Email Priority. 1 = highest. 5 = lowest. 3 = normal $config['validate'] = false; // If true then the email address will be validated + +// If enabled will be logged info about emails in Codeigniter error logs +$config['enable_debug'] = false; diff --git a/application/config/message.php b/application/config/message.php index 40d15a07e..35d34124b 100644 --- a/application/config/message.php +++ b/application/config/message.php @@ -7,13 +7,19 @@ $config['send_immediately'] = false; $config['msg_delivery'] = true; // Default true $config['system_person_id'] = 1; // Dummy sender, used for sending messages from the system -$config['redirect_view_message_url'] = '/Redirect/redirectByToken/'; -$config['message_html_view_url'] = '/ViewMessage/toHTML/'; +$config['redirect_view_message_url'] = '/system/messages/ViewMessage/redirectByToken/'; +$config['message_html_view_url'] = '/system/messages/ViewMessage/toHTML/'; // Change this to CIS Server (https://cis.example.com/index.ci.php) if you are sending Messages from Vilesci $config['message_server'] = site_url(); -$config['assistent_function'] = 'ass'; +// Organization unit function that are allowed to read messages for the organisation unit +$config['ou_receivers'] = array('ass'); +// Organization units that will never receive notice emails +$config['ou_receivers_no_notice'] = array('infocenter'); +// Organization units that will not send the notice email to the internal account, but to the private one +$config['ou_receivers_private'] = array('eac', 'ewu', 'scs'); $config['message_redirect_url'] = array(); -$config['message_redirect_url']['fallback'] = site_url('ViewMessage/writeReply'); -// $config['message_redirect_url']['OE_ROOT'] = 'https://SERVER-NAME/addons/aufnahme/OE_ROOT/cis/index.php'; +$config['message_redirect_url']['fallback'] = site_url('system/messages/ViewMessage/writeReply'); +// $config['message_redirect_url']['OE_ROOT_1'] = 'https:///addons/aufnahme/OE_ROOT/cis/index.php'; +// $config['message_redirect_url']['OE_ROOT_2'] = 'https:///'; diff --git a/application/config/navigation.php b/application/config/navigation.php index 9253c87a1..a89c259ee 100644 --- a/application/config/navigation.php +++ b/application/config/navigation.php @@ -72,11 +72,18 @@ $config['navigation_header'] = array( 'sort' => 40, 'requiredPermissions' => 'basis/vilesci:r', 'children'=> array( + 'messages' => array( + 'link' => site_url('system/messages/MessageClient/read'), + 'icon' => '', + 'target' => '_blank', + 'description' => 'Messages', + 'sort' => 10, + ), 'bpk' => array( 'link' => site_url('person/BPKWartung'), 'icon' => '', 'description' => 'BPK Wartung', - 'sort' => 10, + 'sort' => 20, 'requiredPermissions' => 'admin:r' ) ) diff --git a/application/controllers/MailJob.php b/application/controllers/MailJob.php deleted file mode 100644 index 2f8b5b92d..000000000 --- a/application/controllers/MailJob.php +++ /dev/null @@ -1,35 +0,0 @@ -load->library('MessageLib'); - } - - public function sendMessages($numberToSent = null, $numberPerTimeRange = null, $email_time_range = null, $email_from_system = null) - { - $this->messagelib->sendAll($numberToSent, $numberPerTimeRange, $email_time_range, $email_from_system); - } -} diff --git a/application/controllers/Redirect.php b/application/controllers/Redirect.php deleted file mode 100644 index 8a107b4b3..000000000 --- a/application/controllers/Redirect.php +++ /dev/null @@ -1,87 +0,0 @@ -load->model('system/MessageToken_model', 'MessageTokenModel'); - } - - /** - * redirectByToken - * - * - Loads the message using a token - * - Loads the root of the organisation unit tree using the oe_kurzbz present in the message - * - Redirect to the aufnahme related to the found organisation unit - */ - public function redirectByToken($token) - { - $msg = $this->MessageTokenModel->getMessageByToken($token); - if (isError($msg)) - { - show_error(getError($msg)); - } - - $oe_kurzbz = null; - if (hasData($msg)) $oe_kurzbz = getData($msg)[0]->oe_kurzbz; - - if ($oe_kurzbz != null && $oe_kurzbz != '') - { - $organisationRoot = null; - - $getOERoot = $this->MessageTokenModel->getOERoot($oe_kurzbz); - if (isSuccess($getOERoot)) // If no errors occurred - { - $organisationRoot = getData($getOERoot); - } - else - { - show_error('No organisation unit present in the message'); - } - - $addonAufnahmeUrls = $this->config->item('message_redirect_url'); - if(!isset($addonAufnahmeUrls[$organisationRoot])) - $organisationRoot = 'fallback'; - - if (isset($token) - && hasData($msg) - && is_array($addonAufnahmeUrls) - && $organisationRoot != null - && isset($addonAufnahmeUrls[$organisationRoot])) - { - redirect($addonAufnahmeUrls[$organisationRoot] . '?token=' . $token); - } - } - else - { - $addonAufnahmeUrls = $this->config->item('message_redirect_url'); - if (isset($token) - && hasData($msg) - && is_array($addonAufnahmeUrls) - && isset($addonAufnahmeUrls['fallback'])) - { - redirect($addonAufnahmeUrls['fallback'] . '?token=' . $token); - } - } - } -} diff --git a/application/controllers/ViewMessage.php b/application/controllers/ViewMessage.php deleted file mode 100644 index 4e076e99d..000000000 --- a/application/controllers/ViewMessage.php +++ /dev/null @@ -1,150 +0,0 @@ -config->load('message'); - - // Load model MessageToken_model, not calling the authentication system - $this->load->model('system/MessageToken_model', 'MessageTokenModel'); - $this->load->model('CL/Messages_model', 'CLMessagesModel'); - } - - /** - * Using the MessageTokenModel instead of MessageLib to allow - * viewing the message without prompting the login - */ - public function toHTML($token) - { - $msg = $this->MessageTokenModel->getMessageByToken($token); - if (isError($msg)) - { - show_error(getError($msg)); - } - - if (is_array(getData($msg)) && count(getData($msg)) > 0) - { - $setReadMessageStatusByToken = $this->MessageTokenModel->setReadMessageStatusByToken($token); - if (isError($setReadMessageStatusByToken)) - { - show_error(getError($setReadMessageStatusByToken)); - } - - $sender_id = getData($msg)[0]->sender_id; - $receiver_id = getData($msg)[0]->receiver_id; - $sender = $this->MessageTokenModel->getSenderData($sender_id); - - // To decide how to change the redirection - $isEmployee = $this->MessageTokenModel->isEmployee($receiver_id); - if (isError($isEmployee)) - { - show_error(getError($isEmployee)); - } - - if($this->config->item('redirect_view_message_url') != '') - $href = $this->config->item('message_server').$this->config->item('redirect_view_message_url').$token; - else - $href = ''; - - $data = array ( - 'sender_id' => $sender_id, - 'sender' => getData($sender)[0], - 'message' => getData($msg)[0], - 'isEmployee' => hasData($isEmployee), - 'href' => $href - ); - - $this->load->view('system/messages/messageHTML.php', $data); - } - } - - /** - * write the reply - */ - public function writeReply() - { - $token = $this->input->get('token'); - - if (isEmptyString($token)) - { - show_error('No token supplied'); - } - - $msg = null; - - // Get message data if possible - $msg = $this->MessageTokenModel->getMessageByToken($token); - if (!hasData($msg)) - { - show_error('No message found'); - } - - $msg = getData($msg)[0]; - - // Get variables - $receiverData = $this->MessageTokenModel->getPersonData($msg->sender_id); - if (!hasData($receiverData)) - { - show_error('No sender found'); - } - - $data = array ( - 'receivers' => getData($receiverData), - 'message' => $msg, - 'token' => $token - ); - - $this->load->view('system/messages/messageWriteReply', $data); - } - - /** - * Send a reply - */ - public function sendReply() - { - $subject = $this->input->post('subject'); - $body = $this->input->post('body'); - $persons = $this->input->post('persons'); - $relationmessage_id = $this->input->post('relationmessage_id'); - $token = $this->input->post('token'); - - if (!isset($relationmessage_id) || $relationmessage_id == '' || !isset($token) || $token == '') - { - show_error('Error while sending reply'); - } - - $sendReply = $this->CLMessagesModel->sendReply($subject, $body, $persons, $relationmessage_id, $token); - if (isError($sendReply)) - { - show_error(getError($sendReply)); - } - - $this->load->view('system/messages/messageReplySent'); - } -} diff --git a/application/controllers/api/v1/person/Person.php b/application/controllers/api/v1/person/Person.php index c8c95ae06..ca8a66bea 100644 --- a/application/controllers/api/v1/person/Person.php +++ b/application/controllers/api/v1/person/Person.php @@ -1,267 +1,267 @@ - 'basis/person:rw', 'CheckBewerbung' => 'basis/person:r')); - // Load model PersonModel - $this->load->model('person/person_model', 'PersonModel'); - } - - /** - * @return void - */ - public function getPerson() - { - $person_id = $this->get('person_id'); - $code = $this->get('code'); - $email = $this->get('email'); - - if (isset($code) || isset($email) || isset($person_id)) - { - if (isset($code) && isset($email)) - { - $result = $this->PersonModel->getPersonKontaktByZugangscode($code, $email); - } - else - { - $parametersArray = array(); - - if (isset($code)) - { - $parametersArray['zugangscode'] = $code; - } - else - { - $parametersArray['person_id'] = $person_id; - } - - $result = $this->PersonModel->loadWhere($parametersArray); - } - - $this->response($result, REST_Controller::HTTP_OK); - } - else - { - $this->response(); - } - } - - /** - * @return void - */ - public function getCheckBewerbung() - { - $email = $this->get('email'); - $studiensemester_kurzbz = $this->get('studiensemester_kurzbz'); - - if (isset($email)) - { - $result = $this->PersonModel->checkBewerbung($email, $studiensemester_kurzbz); - - $this->response($result, REST_Controller::HTTP_OK); - } - else - { - $this->response(); - } - } - - /** - * @return void - */ - public function postPerson() - { - $person = $this->post(); - $validation = $this->_validate($person); - - if (isSuccess($validation)) - { - if(isset($person['person_id']) && !(is_null($person['person_id'])) && ($person['person_id'] != '')) - { - $result = $this->PersonModel->updatePerson($person); - } - else - { - $result = $this->PersonModel->insert($person); - } - - $this->response($result, REST_Controller::HTTP_OK); - } - else - { - $this->response($validation, REST_Controller::HTTP_OK); - } - } - - private function _validate($person) - { - // If $person is consistent - if (!isset($person) || (isset($person) && !is_array($person))) - { - return error('Any parameters posted'); - } - - // Trim all the values - foreach($person as $key => $value) - { - if (gettype($value) == 'string') - { - $person[$key] = trim($value); - } - } - - if (isset($person['sprache']) && mb_strlen($person['sprache']) > 16) - { - return error('Sprache darf nicht laenger als 16 Zeichen sein'); - } - if (isset($person['anrede']) && mb_strlen($person['anrede']) > 16) - { - return error('Anrede darf nicht laenger als 16 Zeichen sein'); - } - if (isset($person['titelpost']) && mb_strlen($person['titelpost']) > 32) - { - return error('Titelpost darf nicht laenger als 32 Zeichen sein'); - } - if (isset($person['titelpre']) && mb_strlen($person['titelpre']) > 64) - { - return error('Titelpre darf nicht laenger als 64 Zeichen sein'); - } - if (isset($person['nachname']) && mb_strlen($person['nachname']) > 64) - { - return error('Nachname darf nicht laenger als 64 Zeichen sein'); - } - if (isset($person['nachname']) && ($person['nachname'] == '' || is_null($person['nachname']))) - { - return error('Nachname muss eingegeben werden'); - } - if (isset($person['vorname']) && mb_strlen($person['vorname']) > 32) - { - return error('Vorname darf nicht laenger als 32 Zeichen sein'); - } - if (isset($person['vornamen']) && mb_strlen($person['vornamen']) > 128) - { - return error('Vornamen darf nicht laenger als 128 Zeichen sein'); - } - if (isset($person['gebort']) && mb_strlen($person['gebort']) > 128) - { - return error('Geburtsort darf nicht laenger als 128 Zeichen sein'); - } - if (isset($person['homepage']) && mb_strlen($person['homepage']) > 256) - { - return error('Homepage darf nicht laenger als 256 Zeichen sein'); - } - if (isset($person['matr_nr']) && mb_strlen($person['matr_nr']) > 32) - { - return error('Matrikelnummer darf nicht laenger als 32 Zeichen sein'); - } - if (isset($person['ersatzkennzeichen']) && mb_strlen($person['ersatzkennzeichen']) > 10) - { - return error('Ersatzkennzeichen darf nicht laenger als 10 Zeichen sein'); - } - if (isset($person['familienstand']) && mb_strlen($person['familienstand']) > 1) - { - return error('Familienstand ist ungueltig'); - } - if (isset($person['anzahlkinder']) && $person['anzahlkinder'] != '' && !is_numeric($person['anzahlkinder'])) - { - return error('Anzahl der Kinder ist ungueltig'); - } - if (!isset($person['aktiv']) || (isset($person['aktiv']) && $person['aktiv'] !== true && $person['aktiv'] !== false)) - { - return error('Aktiv ist ungueltig'); - } - if (!isset($person['person_id']) && isset($person['insertvon']) && mb_strlen($person['insertvon']) > 32) - { - return error('Insertvon darf nicht laenger als 32 Zeichen sein'); - } - if (isset($person['updatevon']) && mb_strlen($person['updatevon']) > 32) - { - return error('Updatevon darf nicht laenger als 32 Zeichen sein'); - } - if (isset($person['geburtsnation']) && mb_strlen($person['geburtsnation']) > 3) - { - return error('Geburtsnation darf nicht laenger als 3 Zeichen sein'); - } - if (isset($person['staatsbuergerschaft']) && mb_strlen($person['staatsbuergerschaft']) > 3) - { - return error('Staatsbuergerschaft darf nicht laenger als 3 Zeichen sein'); - } - if (!isset($person['geschlecht']) || (isset($person['geschlecht']) && mb_strlen($person['geschlecht']) > 1)) - { - return error('Geschlecht darf nicht laenger als 1 Zeichen sein'); - } - if (isset($person['geschlecht']) && $person['geschlecht'] != 'm' && $person['geschlecht'] != 'w' && $person['geschlecht'] != 'u') - { - return error('Geschlecht muss w, m oder u sein!'); - } - - if (isset($person['svnr'])) - { - if ($person['svnr'] != '' && mb_strlen($person['svnr']) != 16 - && mb_strlen($person['svnr']) != 12 && mb_strlen($person['svnr']) != 10) - { - return error('SVNR muss 10, 12 oder 16 Zeichen lang sein'); - } - if (mb_strlen($person['svnr']) == 10 || mb_strlen($person['svnr']) == 12) - { - //SVNR mit Pruefziffer pruefen - //Die 4. Stelle in der SVNR ist die Pruefziffer - //(Summe von (gewichtung[i]*svnr[i])) modulo 11 ergibt diese Pruefziffer - //Falls nicht, ist die SVNR ungueltig - $gewichtung = array(3, 7, 9, 0, 5, 8, 4, 2, 1, 6); - $erg = 0; - $tmpSvnr = substr($person['svnr'], 0, 10); - //Quersumme bilden - for ($i = 0; $i < 10; $i++) - { - $erg += $gewichtung[$i] * $tmpSvnr{$i}; - } - - if ($tmpSvnr{3} != ($erg % 11)) //Vergleichen der Pruefziffer mit Quersumme Modulo 11 - { - return error('SVNR ist ungueltig'); - } - - if (mb_strlen($person['svnr']) == 12) - { - $last = substr($person['svnr'], 10, 12); - if ($last{0} != 'v' || !is_numeric($last{1})) - { - return error('SVNR ist ungueltig'); - } - } - } - - //Pruefen ob das Geburtsdatum mit der SVNR uebereinstimmt. - if (isset($person['gebdatum']) && $person['svnr'] != '' && $person['gebdatum'] != '') - { - if (!mb_ereg('([0-9]{1,2}).([0-9]{1,2}).([0-9]{4})', $person['gebdatum']) - && !mb_ereg('([0-9]{4})-([0-9]{2})-([0-9]{2})', $person['gebdatum'])) - { - return error('Format des Geburtsdatums ist ungueltig'); - } - } - } - - return success('Input data are valid'); - } -} + 'basis/person:rw', 'CheckBewerbung' => 'basis/person:r')); + // Load model PersonModel + $this->load->model('person/person_model', 'PersonModel'); + } + + /** + * @return void + */ + public function getPerson() + { + $person_id = $this->get('person_id'); + $code = $this->get('code'); + $email = $this->get('email'); + + if (isset($code) || isset($email) || isset($person_id)) + { + if (isset($code) && isset($email)) + { + $result = $this->PersonModel->getPersonKontaktByZugangscode($code, $email); + } + else + { + $parametersArray = array(); + + if (isset($code)) + { + $parametersArray['zugangscode'] = $code; + } + else + { + $parametersArray['person_id'] = $person_id; + } + + $result = $this->PersonModel->loadWhere($parametersArray); + } + + $this->response($result, REST_Controller::HTTP_OK); + } + else + { + $this->response(); + } + } + + /** + * @return void + */ + public function getCheckBewerbung() + { + $email = $this->get('email'); + $studiensemester_kurzbz = $this->get('studiensemester_kurzbz'); + + if (isset($email)) + { + $result = $this->PersonModel->checkBewerbung($email, $studiensemester_kurzbz); + + $this->response($result, REST_Controller::HTTP_OK); + } + else + { + $this->response(); + } + } + + /** + * @return void + */ + public function postPerson() + { + $person = $this->post(); + $validation = $this->_validate($person); + + if (isSuccess($validation)) + { + if(isset($person['person_id']) && !(is_null($person['person_id'])) && ($person['person_id'] != '')) + { + $result = $this->PersonModel->updatePerson($person); + } + else + { + $result = $this->PersonModel->insert($person); + } + + $this->response($result, REST_Controller::HTTP_OK); + } + else + { + $this->response($validation, REST_Controller::HTTP_OK); + } + } + + private function _validate($person) + { + // If $person is consistent + if (!isset($person) || (isset($person) && !is_array($person))) + { + return error('Any parameters posted'); + } + + // Trim all the values + foreach($person as $key => $value) + { + if (gettype($value) == 'string') + { + $person[$key] = trim($value); + } + } + + if (isset($person['sprache']) && mb_strlen($person['sprache']) > 16) + { + return error('Sprache darf nicht laenger als 16 Zeichen sein'); + } + if (isset($person['anrede']) && mb_strlen($person['anrede']) > 16) + { + return error('Anrede darf nicht laenger als 16 Zeichen sein'); + } + if (isset($person['titelpost']) && mb_strlen($person['titelpost']) > 32) + { + return error('Titelpost darf nicht laenger als 32 Zeichen sein'); + } + if (isset($person['titelpre']) && mb_strlen($person['titelpre']) > 64) + { + return error('Titelpre darf nicht laenger als 64 Zeichen sein'); + } + if (isset($person['nachname']) && mb_strlen($person['nachname']) > 64) + { + return error('Nachname darf nicht laenger als 64 Zeichen sein'); + } + if (isset($person['nachname']) && ($person['nachname'] == '' || is_null($person['nachname']))) + { + return error('Nachname muss eingegeben werden'); + } + if (isset($person['vorname']) && mb_strlen($person['vorname']) > 32) + { + return error('Vorname darf nicht laenger als 32 Zeichen sein'); + } + if (isset($person['vornamen']) && mb_strlen($person['vornamen']) > 128) + { + return error('Vornamen darf nicht laenger als 128 Zeichen sein'); + } + if (isset($person['gebort']) && mb_strlen($person['gebort']) > 128) + { + return error('Geburtsort darf nicht laenger als 128 Zeichen sein'); + } + if (isset($person['homepage']) && mb_strlen($person['homepage']) > 256) + { + return error('Homepage darf nicht laenger als 256 Zeichen sein'); + } + if (isset($person['matr_nr']) && mb_strlen($person['matr_nr']) > 32) + { + return error('Matrikelnummer darf nicht laenger als 32 Zeichen sein'); + } + if (isset($person['ersatzkennzeichen']) && mb_strlen($person['ersatzkennzeichen']) > 10) + { + return error('Ersatzkennzeichen darf nicht laenger als 10 Zeichen sein'); + } + if (isset($person['familienstand']) && mb_strlen($person['familienstand']) > 1) + { + return error('Familienstand ist ungueltig'); + } + if (isset($person['anzahlkinder']) && $person['anzahlkinder'] != '' && !is_numeric($person['anzahlkinder'])) + { + return error('Anzahl der Kinder ist ungueltig'); + } + if (!isset($person['aktiv']) || (isset($person['aktiv']) && $person['aktiv'] !== true && $person['aktiv'] !== false)) + { + return error('Aktiv ist ungueltig'); + } + if (!isset($person['person_id']) && isset($person['insertvon']) && mb_strlen($person['insertvon']) > 32) + { + return error('Insertvon darf nicht laenger als 32 Zeichen sein'); + } + if (isset($person['updatevon']) && mb_strlen($person['updatevon']) > 32) + { + return error('Updatevon darf nicht laenger als 32 Zeichen sein'); + } + if (isset($person['geburtsnation']) && mb_strlen($person['geburtsnation']) > 3) + { + return error('Geburtsnation darf nicht laenger als 3 Zeichen sein'); + } + if (isset($person['staatsbuergerschaft']) && mb_strlen($person['staatsbuergerschaft']) > 3) + { + return error('Staatsbuergerschaft darf nicht laenger als 3 Zeichen sein'); + } + if (!isset($person['geschlecht']) || (isset($person['geschlecht']) && mb_strlen($person['geschlecht']) > 1)) + { + return error('Geschlecht darf nicht laenger als 1 Zeichen sein'); + } + if (isset($person['geschlecht']) && $person['geschlecht'] != 'm' && $person['geschlecht'] != 'w' && $person['geschlecht'] != 'u') + { + return error('Geschlecht muss w, m oder u sein!'); + } + + if (isset($person['svnr'])) + { + if ($person['svnr'] != '' && mb_strlen($person['svnr']) != 16 + && mb_strlen($person['svnr']) != 12 && mb_strlen($person['svnr']) != 10) + { + return error('SVNR muss 10, 12 oder 16 Zeichen lang sein'); + } + if (mb_strlen($person['svnr']) == 10 || mb_strlen($person['svnr']) == 12) + { + //SVNR mit Pruefziffer pruefen + //Die 4. Stelle in der SVNR ist die Pruefziffer + //(Summe von (gewichtung[i]*svnr[i])) modulo 11 ergibt diese Pruefziffer + //Falls nicht, ist die SVNR ungueltig + $gewichtung = array(3, 7, 9, 0, 5, 8, 4, 2, 1, 6); + $erg = 0; + $tmpSvnr = substr($person['svnr'], 0, 10); + //Quersumme bilden + for ($i = 0; $i < 10; $i++) + { + $erg += $gewichtung[$i] * $tmpSvnr{$i}; + } + + if ($tmpSvnr{3} != ($erg % 11)) //Vergleichen der Pruefziffer mit Quersumme Modulo 11 + { + return error('SVNR ist ungueltig'); + } + + if (mb_strlen($person['svnr']) == 12) + { + $last = substr($person['svnr'], 10, 12); + if ($last{0} != 'v' || !is_numeric($last{1})) + { + return error('SVNR ist ungueltig'); + } + } + } + + //Pruefen ob das Geburtsdatum mit der SVNR uebereinstimmt. + if (isset($person['gebdatum']) && $person['svnr'] != '' && $person['gebdatum'] != '') + { + if (!mb_ereg('([0-9]{1,2}).([0-9]{1,2}).([0-9]{4})', $person['gebdatum']) + && !mb_ereg('([0-9]{4})-([0-9]{2})-([0-9]{2})', $person['gebdatum'])) + { + return error('Format des Geburtsdatums ist ungueltig'); + } + } + } + + return success('Input data are valid'); + } +} diff --git a/application/controllers/api/v1/system/Message.php b/application/controllers/api/v1/system/Message.php index be87526ed..1825b7db9 100644 --- a/application/controllers/api/v1/system/Message.php +++ b/application/controllers/api/v1/system/Message.php @@ -144,26 +144,26 @@ class Message extends APIv1_Controller */ public function postMessage() { - $validation = $this->_validatePostMessage($this->post()); + $postMessage = $this->_validatePostMessage($this->post()); - if (isSuccess($validation)) + if (isSuccess($postMessage)) { - $result = $this->messagelib->sendMessage( - isset($this->post()['person_id']) ? $this->post()['person_id'] : null, - isset($this->post()['receiver_id']) ? $this->post()['receiver_id'] : null, - $this->post()['subject'], - $this->post()['body'], - PRIORITY_NORMAL, - isset($this->post()['relationmessage_id']) ? $this->post()['relationmessage_id'] : null, - isset($this->post()['oe_kurzbz']) ? $this->post()['oe_kurzbz'] : null, // Sender organisation unit - isset($this->post()['multiPartMime']) ? $this->post()['multiPartMime'] : true + $result = $this->messagelib->sendMessageUser( + $this->post()['receiver_id'], // receiverPersonId + $this->post()['subject'], // subject + $this->post()['body'], // body + $this->post()['person_id'] ? $this->post()['person_id'] : null, // sender_id + isset($this->post()['oe_kurzbz']) ? $this->post()['oe_kurzbz'] : null, // senderOU + isset($this->post()['relationmessage_id']) ? $this->post()['relationmessage_id'] : null, // relationmessage_id + MSG_PRIORITY_NORMAL, // priority + isset($this->post()['multiPartMime']) ? $this->post()['multiPartMime'] : true // multiPartMime ); $this->response($result, REST_Controller::HTTP_OK); } else { - $this->response($validation, REST_Controller::HTTP_OK); + $this->response($postMessage, REST_Controller::HTTP_OK); } } @@ -172,26 +172,27 @@ class Message extends APIv1_Controller */ public function postMessageVorlage() { - $validation = $this->_validatePostMessageVorlage($this->post()); + $postMessage = $this->_validatePostMessageVorlage($this->post()); - if (isSuccess($validation)) + if (isSuccess($postMessage)) { - $result = $this->messagelib->sendMessageVorlage( - isset($this->post()['sender_id']) ? $this->post()['sender_id'] : null, - isset($this->post()['receiver_id']) ? $this->post()['receiver_id'] : null, - $this->post()['vorlage_kurzbz'], - isset($this->post()['oe_kurzbz']) ? $this->post()['oe_kurzbz'] : null, // Sender organisation unit - $this->post()['data'], - isset($this->post()['relationmessage_id']) ? $this->post()['relationmessage_id'] : null, - isset($this->post()['orgform_kurzbz']) ? $this->post()['orgform_kurzbz'] : null, - isset($this->post()['multiPartMime']) ? $this->post()['multiPartMime'] : true + $result = $this->messagelib->sendMessageUserTemplate( + isset($this->post()['receiver_id']) ? $this->post()['receiver_id'] : null, // receiversPersonId + $this->post()['vorlage_kurzbz'], // vorlage + $this->post()['data'], // parseData + isset($this->post()['orgform_kurzbz']) ? $this->post()['orgform_kurzbz'] : null, // orgform + isset($this->post()['sender_id']) ? $this->post()['sender_id'] : null, // sender_id + isset($this->post()['oe_kurzbz']) ? $this->post()['oe_kurzbz'] : null, // senderOU + isset($this->post()['relationmessage_id']) ? $this->post()['relationmessage_id'] : null, // relationmessage_id + MSG_PRIORITY_NORMAL, // priority + isset($this->post()['multiPartMime']) ? $this->post()['multiPartMime'] : true // multiPartMime ); $this->response($result, REST_Controller::HTTP_OK); } else { - $this->response($validation, REST_Controller::HTTP_OK); + $this->response($postMessage, REST_Controller::HTTP_OK); } } @@ -220,26 +221,26 @@ class Message extends APIv1_Controller /** * _validatePostMessage */ - private function _validatePostMessage($message = null) + private function _validatePostMessage($post = null) { - if (!isset($message)) + if (!isset($post)) { return error('Parameter is null'); } - if (!isset($message['subject'])) + if (!isset($post['subject'])) { return error('subject is not set'); } - if( !isset($message['body'])) + if (!isset($post['body'])) { return error('body is not set'); } - if (!isset($message['receiver_id']) && !isset($message['oe_kurzbz'])) + if (!isset($post['receiver_id'])) { - return error('If a receiver_id is not given a oe_kurzbz must be specified'); + return error('receiver_id is not set'); } - return success('Input data are valid'); + return success(); } /** diff --git a/application/controllers/jobs/MailJob.php b/application/controllers/jobs/MailJob.php new file mode 100644 index 000000000..f459d4d3e --- /dev/null +++ b/application/controllers/jobs/MailJob.php @@ -0,0 +1,47 @@ +load->library('MessageLib'); + } + + /** + * Send all the NOT sent notice emails for messaging system + * The parameters are all not mandatory, they could be used to overrides the configs for testing, debug or one shot purposes + */ + public function sendAllMessageEmailNotices($since = '1970-01-01', $numberToSent = null, $numberPerTimeRange = null, $emailTimeRange = null, $emailFromSystem = null) + { + $this->logInfo('Send all message email notices started'); + + // Send them all! + $sendAllEmailNotices = $this->messagelib->sendAllEmailNotices($since, $numberToSent, $numberPerTimeRange, $emailTimeRange, $emailFromSystem); + + if (isError($sendAllEmailNotices)) + { + $optionalParameters = new stdClass(); + $optionalParameters->$since = $since; + $optionalParameters->$numberToSent = $numberToSent; + $optionalParameters->$numberPerTimeRange = $numberPerTimeRange; + $optionalParameters->$emailTimeRange = $emailTimeRange; + $optionalParameters->$emailFromSystem = $emailFromSystem; + + $this->logError($sendAllEmailNotices->retval, $optionalParameters); + } + elseif (!hasData($sendAllEmailNotices)) + { + $this->logInfo('There were no unsent messages'); + } + + $this->logInfo('Send all message email notices ended'); + } +} diff --git a/application/controllers/jobs/ReihungstestJob.php b/application/controllers/jobs/ReihungstestJob.php index 84a5fe614..859b8f265 100644 --- a/application/controllers/jobs/ReihungstestJob.php +++ b/application/controllers/jobs/ReihungstestJob.php @@ -3,30 +3,32 @@ if (!defined('BASEPATH')) exit('No direct script access allowed'); class ReihungstestJob extends CLI_Controller { - /** - * Constructor - */ - public function __construct() - { - parent::__construct(); + /** + * Constructor + */ + public function __construct() + { + parent::__construct(); - // Load models - $this->load->model('crm/Reihungstest_model', 'ReihungstestModel'); - $this->load->model('crm/RtStudienplan_model', 'RtStudienplanModel'); - $this->load->model('organisation/Studiengang_model', 'StudiengangModel'); - $this->load->model('organisation/Studienplan_model', 'StudienplanModel'); + // Load models + $this->load->model('crm/Reihungstest_model', 'ReihungstestModel'); + $this->load->model('crm/RtStudienplan_model', 'RtStudienplanModel'); + $this->load->model('crm/Konto_model', 'KontoModel'); + $this->load->model('crm/Prestudentstatus_model', 'PrestudentstatusModel'); + $this->load->model('organisation/Studiengang_model', 'StudiengangModel'); + $this->load->model('organisation/Studienplan_model', 'StudienplanModel'); - // Load helpers - $this->load->helper('hlp_sancho_helper'); - } + // Load helpers + $this->load->helper('hlp_sancho_helper'); + } - /** - * runReihungstestJob - */ - public function runReihungstestJob() - { - // Get study plans that have no assigned placement tests yet - $result = $this->ReihungstestModel->checkMissingReihungstest(); + /** + * runReihungstestJob + */ + public function runReihungstestJob() + { + // Get study plans that have no assigned placement tests yet + $result = $this->ReihungstestModel->checkMissingReihungstest(); $missing_rt_arr = array(); if (hasData($result)) @@ -38,8 +40,8 @@ class ReihungstestJob extends CLI_Controller show_error(getError($result)); } - // Get free places - $result = $this->ReihungstestModel->getFreePlaces(); + // Get free places + $result = $this->ReihungstestModel->getFreePlaces(); $free_places_arr = array(); if (hasData($result)) @@ -51,8 +53,8 @@ class ReihungstestJob extends CLI_Controller show_error(getError($result)); } - // Prepare data for mail template 'ReihungstestJob' - $content_data_arr = $this->_getContentData($missing_rt_arr, $free_places_arr); + // Prepare data for mail template 'ReihungstestJob' + $content_data_arr = $this->_getContentData($missing_rt_arr, $free_places_arr); // Send email in Sancho design if (!empty($missing_rt_arr) || !empty($free_places_arr)) @@ -95,7 +97,7 @@ class ReihungstestJob extends CLI_Controller // Get placement tests where registration date was yesterday $result = $this->ReihungstestModel->checkReachedRegistrationDate($degreeProgram); - $reachedRegistration_rt_arr = array(); + $reachedRegistration_rt_arr = array(); if (hasData($result)) { @@ -106,11 +108,11 @@ class ReihungstestJob extends CLI_Controller show_error(getError($result)); } - $applicants_arr = array(); + $applicants_arr = array(); - foreach ($reachedRegistration_rt_arr as $reihungstest) - { - $applicants = $this->ReihungstestModel->getApplicantsOfPlacementTestForCronjob($reihungstest->reihungstest_id); + foreach ($reachedRegistration_rt_arr as $reihungstest) + { + $applicants = $this->ReihungstestModel->getApplicantsOfPlacementTestForCronjob($reihungstest->reihungstest_id); if (hasData($applicants)) { @@ -214,24 +216,24 @@ class ReihungstestJob extends CLI_Controller // Get applicants that have been added to a test after Anmeldefrist $result = $this->ReihungstestModel->getApplicantAssignedAfterDate($degreeProgram); - $applicants_after_anmeldefrist_arr = array(); + $applicants_after_anmeldefrist_arr = array(); - if (hasData($result)) - { - $applicants_after_anmeldefrist_arr = $result->retval; - } - elseif (isError($result)) - { - show_error(getError($result)); - } + if (hasData($result)) + { + $applicants_after_anmeldefrist_arr = $result->retval; + } + elseif (isError($result)) + { + show_error(getError($result)); + } - $studiengang = ''; - $mailReceipients = ''; // String with all mailadresses - $mailcontent_data_arr = array(); - $headerstyle = 'style="background: #DCE4EF; border: 1px solid #FFF; padding: 4px; text-align: left;"'; - $rowstyle = 'style="background-color: #EEEEEE; padding: 4px;"'; - $mailcontent = ''; - $applicants_list = ''; + $studiengang = ''; + $mailReceipients = ''; // String with all mailadresses + $mailcontent_data_arr = array(); + $headerstyle = 'style="background: #DCE4EF; border: 1px solid #FFF; padding: 4px; text-align: left;"'; + $rowstyle = 'style="background-color: #EEEEEE; padding: 4px;"'; + $mailcontent = ''; + $applicants_list = ''; if (count($applicants_after_anmeldefrist_arr) > 0) { @@ -277,11 +279,11 @@ class ReihungstestJob extends CLI_Controller '; - } + } - $studiengang = $applicant->studiengang_kz; - $mailReceipients .= $applicant->email . ';'; - $applicants_list .= ' + $studiengang = $applicant->studiengang_kz; + $mailReceipients .= $applicant->email . ';'; + $applicants_list .= ' ' . date_format(date_create($applicant->datum), 'd.m.Y') . ' ' . $applicant->uhrzeit . ' @@ -315,7 +317,7 @@ class ReihungstestJob extends CLI_Controller } /* - * Sends an email to all applicants of a placement test to remind them 3 working days before + * Sends an email to all applicants of a placement test to remind them 2 working days before * * @param integer $degreeProgram. Kennzahl of Degree Program to check * @param string $bcc. Optional. BCC-Mailadress to send the Mails to @@ -341,66 +343,66 @@ class ReihungstestJob extends CLI_Controller $from = urldecode($from); } - // Get placement tests with testdate within the next 2 weeks - $resultNextTestDates = $this->ReihungstestModel->getNextPlacementtests($degreeProgram, 14); - if (hasData($resultNextTestDates)) - { - $nextTestDates = $resultNextTestDates->retval; - $enddate = ''; - // Loop through the dates - foreach ($nextTestDates as $testDates) - { - $workingdays = 0; - $testsOndate = array(); + // Get placement tests with testdate within the next 2 weeks + $resultNextTestDates = $this->ReihungstestModel->getNextPlacementtests($degreeProgram, 14); + if (hasData($resultNextTestDates)) + { + $nextTestDates = $resultNextTestDates->retval; + $enddate = ''; + // Loop through the dates + foreach ($nextTestDates as $testDates) + { + $workingdays = 0; + $testsOndate = array(); - // Deduct days till 3 working days are reached - for ($i = 1; ; $i++) - { - if (isDateWorkingDay($testDates->datum, $i) === true) - { - $workingdays++; - } - if ($workingdays == 3) - { - $enddate = date("Y-m-d", strtotime("$testDates->datum -" . $i . " days")); - break; - } - else - { - continue; - } - } + // Deduct days till 2 working days are reached + for ($i = 1; ; $i++) + { + if (isDateWorkingDay($testDates->datum, $i) === true) + { + $workingdays++; + } + if ($workingdays == 2) + { + $enddate = date("Y-m-d", strtotime("$testDates->datum -" . $i . " days")); + break; + } + else + { + continue; + } + } - // If $enddate is today -> load all tests of $testDates->datum - if (date("Y-m-d", strtotime($enddate)) == date('Y-m-d')) - { - $resultTestsOnDate = $this->ReihungstestModel->getTestsOnDate($testDates->datum, $degreeProgram); + // If $enddate is today -> load all tests of $testDates->datum + if (date("Y-m-d", strtotime($enddate)) == date('Y-m-d')) + { + $resultTestsOnDate = $this->ReihungstestModel->getTestsOnDate($testDates->datum, $degreeProgram); - if (hasData($resultTestsOnDate)) - { - $testsOndate = $resultTestsOnDate->retval; - } - elseif (isError($resultTestsOnDate)) - { - show_error(getError($resultTestsOnDate)); - } - } + if (hasData($resultTestsOnDate)) + { + $testsOndate = $resultTestsOnDate->retval; + } + elseif (isError($resultTestsOnDate)) + { + show_error(getError($resultTestsOnDate)); + } + } - if (!isEmptyArray($testsOndate)) - { - foreach ($testsOndate as $reihungstest) - { - // Loads applicants of a test - $applicants = $this->ReihungstestModel->getApplicantsOfPlacementTest($reihungstest->reihungstest_id); + if (!isEmptyArray($testsOndate)) + { + foreach ($testsOndate as $reihungstest) + { + // Loads applicants of a test + $applicants = $this->ReihungstestModel->getApplicantsOfPlacementTest($reihungstest->reihungstest_id); - if (hasData($applicants)) - { - $applicants_arr = $applicants->retval; - } - elseif (isError($applicants)) - { - show_error(getError($applicants)); - } + if (hasData($applicants)) + { + $applicants_arr = $applicants->retval; + } + elseif (isError($applicants)) + { + show_error(getError($applicants)); + } foreach ($applicants_arr as $applicant) { @@ -420,237 +422,237 @@ class ReihungstestJob extends CLI_Controller $mailcontent_data_arr['wegbeschreibung'] = $applicant->lageplan; } - sendSanchoMail( - 'Sancho_RemindApplicantsOfTest', - $mailcontent_data_arr, - $applicant->email, - 'Ihre Anmeldung zum Reihungstest - Reminder / Your registration for the placement test - Reminder', - DEFAULT_SANCHO_HEADER_IMG, - DEFAULT_SANCHO_FOOTER_IMG, - $from, - '', - $bcc); - } - } - } - } - } - } + sendSanchoMail( + 'Sancho_RemindApplicantsOfTest', + $mailcontent_data_arr, + $applicant->email, + 'Ihre Anmeldung zum Reihungstest - Reminder / Your registration for the placement test - Reminder', + DEFAULT_SANCHO_HEADER_IMG, + DEFAULT_SANCHO_FOOTER_IMG, + $from, + '', + $bcc); + } + } + } + } + } + } - /** - * This job sends eMail(s) to the relevant stg assistance(s) informing about: - * All applicants, who have sent new applications AFTER they had absolved a - * placement test in the actual studiensemester - * AND who have been confirmed yesterday. - */ - public function mailNewApplicants() - { - // Get yesterdays confirmed applicants for Bachelor-studies - $this->load->model('crm/Prestudentstatus_model', 'PrestudentstatusModel'); - $this->PrestudentstatusModel->addSelect(' - tbl_person.person_id, - tbl_prestudentstatus.prestudent_id, - tbl_prestudent.studiengang_kz, - tbl_prestudentstatus.studiensemester_kurzbz, - tbl_prestudentstatus.bestaetigtam, - tbl_prestudentstatus.bewerbung_abgeschicktamum - '); - $this->PrestudentstatusModel->addJoin('public.tbl_prestudent', 'prestudent_id'); - $this->PrestudentstatusModel->addJoin('public.tbl_studiengang', 'studiengang_kz'); - $this->PrestudentstatusModel->addJoin('public.tbl_studiengangstyp', 'typ'); - $this->PrestudentstatusModel->addJoin('public.tbl_person', 'person_id'); + /** + * This job sends eMail(s) to the relevant stg assistance(s) informing about: + * All applicants, who have sent new applications AFTER they had absolved a + * placement test in the actual studiensemester + * AND who have been confirmed yesterday. + */ + public function mailNewApplicants() + { + // Get yesterdays confirmed applicants for Bachelor-studies + $this->load->model('crm/Prestudentstatus_model', 'PrestudentstatusModel'); + $this->PrestudentstatusModel->addSelect(' + tbl_person.person_id, + tbl_prestudentstatus.prestudent_id, + tbl_prestudent.studiengang_kz, + tbl_prestudentstatus.studiensemester_kurzbz, + tbl_prestudentstatus.bestaetigtam, + tbl_prestudentstatus.bewerbung_abgeschicktamum + '); + $this->PrestudentstatusModel->addJoin('public.tbl_prestudent', 'prestudent_id'); + $this->PrestudentstatusModel->addJoin('public.tbl_studiengang', 'studiengang_kz'); + $this->PrestudentstatusModel->addJoin('public.tbl_studiengangstyp', 'typ'); + $this->PrestudentstatusModel->addJoin('public.tbl_person', 'person_id'); - $yesterdays_applicants_arr = $this->PrestudentstatusModel->loadWhere(' - status_kurzbz = \'Interessent\' AND - typ = \'b\' AND - bestaetigtam = current_date - 1 - '); + $yesterdays_applicants_arr = $this->PrestudentstatusModel->loadWhere(' + status_kurzbz = \'Interessent\' AND + typ = \'b\' AND + bestaetigtam = current_date - 1 + '); - // Retrieve the person_ids of yesterdays confirmed applicants - $person_id_arr = array(); - if (hasData($yesterdays_applicants_arr)) - { - foreach ($yesterdays_applicants_arr->retval as $yesterdays_applicant) - { - if (isset($yesterdays_applicant->person_id)) { - $person_id_arr[] = $yesterdays_applicant->person_id; - } - } - } - elseif (isError($yesterdays_applicants_arr)) - { - show_error(getError($yesterdays_applicants_arr)); - } + // Retrieve the person_ids of yesterdays confirmed applicants + $person_id_arr = array(); + if (hasData($yesterdays_applicants_arr)) + { + foreach ($yesterdays_applicants_arr->retval as $yesterdays_applicant) + { + if (isset($yesterdays_applicant->person_id)) { + $person_id_arr[] = $yesterdays_applicant->person_id; + } + } + } + elseif (isError($yesterdays_applicants_arr)) + { + show_error(getError($yesterdays_applicants_arr)); + } - // Get all other prestudenten of the given persons. - if (!isEmptyArray($person_id_arr)) - { - $this->load->model('crm/Prestudent_model', 'PrestudentModel'); - $this->PrestudentModel->addDistinct(); - $this->PrestudentModel->addSelect(' - person_id, - tbl_reihungstest.studiensemester_kurzbz, - tbl_reihungstest.reihungstest_id, - (SELECT(tbl_reihungstest.datum::text || \' \' || tbl_reihungstest.uhrzeit::text)::timestamp) AS reihungstest_timestamp - '); - $this->PrestudentModel->addJoin('public.tbl_studiengang', 'studiengang_kz'); - $this->PrestudentModel->addJoin('public.tbl_studiengangstyp', 'typ'); - $this->PrestudentModel->addJoin('public.tbl_prestudentstatus', 'prestudent_id'); - $this->PrestudentModel->addJoin('public.tbl_person', 'person_id'); - $this->PrestudentModel->addJoin('public.tbl_rt_person', 'person_id'); - $this->PrestudentModel->addJoin('public.tbl_reihungstest', 'tbl_reihungstest.reihungstest_id = tbl_rt_person.rt_id'); + // Get all other prestudenten of the given persons. + if (!isEmptyArray($person_id_arr)) + { + $this->load->model('crm/Prestudent_model', 'PrestudentModel'); + $this->PrestudentModel->addDistinct(); + $this->PrestudentModel->addSelect(' + person_id, + tbl_reihungstest.studiensemester_kurzbz, + tbl_reihungstest.reihungstest_id, + (SELECT(tbl_reihungstest.datum::text || \' \' || tbl_reihungstest.uhrzeit::text)::timestamp) AS reihungstest_timestamp + '); + $this->PrestudentModel->addJoin('public.tbl_studiengang', 'studiengang_kz'); + $this->PrestudentModel->addJoin('public.tbl_studiengangstyp', 'typ'); + $this->PrestudentModel->addJoin('public.tbl_prestudentstatus', 'prestudent_id'); + $this->PrestudentModel->addJoin('public.tbl_person', 'person_id'); + $this->PrestudentModel->addJoin('public.tbl_rt_person', 'person_id'); + $this->PrestudentModel->addJoin('public.tbl_reihungstest', 'tbl_reihungstest.reihungstest_id = tbl_rt_person.rt_id'); - // Store them, if they have already absolved a placement test in the same study term they have applied for. - $placement_absolvents_arr = $this->PrestudentModel->loadWhere(' - person_id IN (' . implode(', ', $person_id_arr) . ') AND - typ = \'b\' AND - teilgenommen = \'t\' AND - tbl_reihungstest.studiensemester_kurzbz IN ( - SELECT - studiensemester_kurzbz - FROM - public.tbl_studiensemester - WHERE - ende >= now() - ) - '); - } + // Store them, if they have already absolved a placement test in the same study term they have applied for. + $placement_absolvents_arr = $this->PrestudentModel->loadWhere(' + person_id IN (' . implode(', ', $person_id_arr) . ') AND + typ = \'b\' AND + teilgenommen = \'t\' AND + tbl_reihungstest.studiensemester_kurzbz IN ( + SELECT + studiensemester_kurzbz + FROM + public.tbl_studiensemester + WHERE + ende >= now() + ) + '); + } - // Store data to be send in the email-link - $result_arr = array(); - foreach($yesterdays_applicants_arr->retval as $yesterdays_applicant) - { - foreach ($placement_absolvents_arr->retval as $placement_absolvent) - { - if ($yesterdays_applicant->person_id == $placement_absolvent->person_id && - $yesterdays_applicant->studiensemester_kurzbz == $placement_absolvent->studiensemester_kurzbz && - $yesterdays_applicant->bewerbung_abgeschicktamum >= $placement_absolvent->reihungstest_timestamp) - { - $obj = new stdClass(); - $obj->prestudent_id = $yesterdays_applicant->prestudent_id; // prestudent_id of the yesterdays applicant - $obj->studiengang_kz = $yesterdays_applicant->studiengang_kz; // study program of interest of the yesterdays applicant - $obj->reihungstest_id = $placement_absolvent->reihungstest_id; // reihungstest_id of absolved reihungstest of that person + // Store data to be send in the email-link + $result_arr = array(); + foreach($yesterdays_applicants_arr->retval as $yesterdays_applicant) + { + foreach ($placement_absolvents_arr->retval as $placement_absolvent) + { + if ($yesterdays_applicant->person_id == $placement_absolvent->person_id && + $yesterdays_applicant->studiensemester_kurzbz == $placement_absolvent->studiensemester_kurzbz && + $yesterdays_applicant->bewerbung_abgeschicktamum >= $placement_absolvent->reihungstest_timestamp) + { + $obj = new stdClass(); + $obj->prestudent_id = $yesterdays_applicant->prestudent_id; // prestudent_id of the yesterdays applicant + $obj->studiengang_kz = $yesterdays_applicant->studiengang_kz; // study program of interest of the yesterdays applicant + $obj->reihungstest_id = $placement_absolvent->reihungstest_id; // reihungstest_id of absolved reihungstest of that person - $result_arr[]= $obj; - } - } - } + $result_arr[]= $obj; + } + } + } - // Sort by STG. This is important to send the mails clustered by STG to the different STG assistances. - usort($result_arr, function ($a, $b) - { - if ($a->studiengang_kz == $b->studiengang_kz) { - return 0; - } - return ($a->studiengang_kz < $b->studiengang_kz) ? -1 : 1; - }); + // Sort by STG. This is important to send the mails clustered by STG to the different STG assistances. + usort($result_arr, function ($a, $b) + { + if ($a->studiengang_kz == $b->studiengang_kz) { + return 0; + } + return ($a->studiengang_kz < $b->studiengang_kz) ? -1 : 1; + }); - $to = ''; // mail recipient (stg assistance) - $content_arr = array(); // url paths to the new applicants - $base_link = base_url('vilesci/stammdaten/auswertung_fhtw.php'); + $to = ''; // mail recipient (stg assistance) + $content_arr = array(); // url paths to the new applicants + $base_link = base_url('vilesci/stammdaten/auswertung_fhtw.php'); - $i = 0; // loop counter - $len = count($result_arr); + $i = 0; // loop counter + $len = count($result_arr); - // Loop trough list of new applicants - foreach($result_arr as $result) - { - $studiengang = $this->StudiengangModel->load($result->studiengang_kz); - $mail_stg_assistance = $studiengang->retval[0]->email; + // Loop trough list of new applicants + foreach($result_arr as $result) + { + $studiengang = $this->StudiengangModel->load($result->studiengang_kz); + $mail_stg_assistance = $studiengang->retval[0]->email; - // If first loop - if ($i == 0) - { - $to = $mail_stg_assistance; // set recipient initially - } + // If first loop + if ($i == 0) + { + $to = $mail_stg_assistance; // set recipient initially + } - // If new study is encountered but is not the first loop - if ($to != $mail_stg_assistance && $i != 0) - { - // Prepare content for mail template - $content_data_arr = $this->_getContentDataNewApplicant($content_arr); + // If new study is encountered but is not the first loop + if ($to != $mail_stg_assistance && $i != 0) + { + // Prepare content for mail template + $content_data_arr = $this->_getContentDataNewApplicant($content_arr); - // Send mail - sendSanchoMail( - 'BewerberNachReihungstest', - $content_data_arr, - $to, - 'Neue Bewerbungen nach absolviertem Reihungstest', - 'sancho_header_min_bw.jpg', - 'sancho_footer_min_bw.jpg' - ); + // Send mail + sendSanchoMail( + 'BewerberNachReihungstest', + $content_data_arr, + $to, + 'Neue Bewerbungen nach absolviertem Reihungstest', + 'sancho_header_min_bw.jpg', + 'sancho_footer_min_bw.jpg' + ); - // Reset content for new study applicants & reset recipient (new stg assistance) - $content_arr = array($base_link. '?reihungstest='. $result->reihungstest_id. '&prestudent_id='. $result->prestudent_id); - $to = $mail_stg_assistance; - } - // If same study - else - { - // just add content - $content_arr[]= $base_link. '?reihungstest='. $result->reihungstest_id. '&prestudent_id='. $result->prestudent_id; // add to content - } + // Reset content for new study applicants & reset recipient (new stg assistance) + $content_arr = array($base_link. '?reihungstest='. $result->reihungstest_id. '&prestudent_id='. $result->prestudent_id); + $to = $mail_stg_assistance; + } + // If same study + else + { + // just add content + $content_arr[]= $base_link. '?reihungstest='. $result->reihungstest_id. '&prestudent_id='. $result->prestudent_id; // add to content + } - // If last loop - if (($i == $len - 1)) - { - // Prepare content for mail template - $content_data_arr = $this->_getContentDataNewApplicant($content_arr); + // If last loop + if (($i == $len - 1)) + { + // Prepare content for mail template + $content_data_arr = $this->_getContentDataNewApplicant($content_arr); - // Send mail - sendSanchoMail( - 'BewerberNachReihungstest', - $content_data_arr, - $to, - 'Neue Bewerbungen nach absolviertem Reihungstest', - 'sancho_header_min_bw.jpg', - 'sancho_footer_min_bw.jpg' - ); - } - $i++; // iterate counter - } - } + // Send mail + sendSanchoMail( + 'BewerberNachReihungstest', + $content_data_arr, + $to, + 'Neue Bewerbungen nach absolviertem Reihungstest', + 'sancho_header_min_bw.jpg', + 'sancho_footer_min_bw.jpg' + ); + } + $i++; // iterate counter + } + } - // ------------------------------------------------------------------------ - // Private methods - /** - * Returns associative array with data as needed in the reihungstest job template. - * @param array $missing_rt_arr Array with studienpläne, which have no assigned placement tests. - * @param array $free_places_arr Array with info and amount of free placement test places. - * @return array - */ - private function _getContentData($missing_rt_arr, $free_places_arr) - { - $style_tbl1 = ' cellpadding="0" cellspacing="10" width="100%" style="font-family: courier, verdana, sans-serif; font-size: 0.95em; border: 1px solid #000000;" '; - $style_tbl2 = ' cellpadding="0" cellspacing="20" width="100%" style="font-family: courier, verdana, sans-serif; font-size: 0.95em; border: 1px solid #000000;" '; + // ------------------------------------------------------------------------ + // Private methods + /** + * Returns associative array with data as needed in the reihungstest job template. + * @param array $missing_rt_arr Array with studienpläne, which have no assigned placement tests. + * @param array $free_places_arr Array with info and amount of free placement test places. + * @return array + */ + private function _getContentData($missing_rt_arr, $free_places_arr) + { + $style_tbl1 = ' cellpadding="0" cellspacing="10" width="100%" style="font-family: courier, verdana, sans-serif; font-size: 0.95em; border: 1px solid #000000;" '; + $style_tbl2 = ' cellpadding="0" cellspacing="20" width="100%" style="font-family: courier, verdana, sans-serif; font-size: 0.95em; border: 1px solid #000000;" '; - // Prepare HTML table with study plans that have no placement tests yet - if (!empty($missing_rt_arr)) { - $studienplan_list - = ' + // Prepare HTML table with study plans that have no placement tests yet + if (!empty($missing_rt_arr)) { + $studienplan_list + = ' '; - foreach ($missing_rt_arr as $rt) { - $studienplan_list .= ' + foreach ($missing_rt_arr as $rt) { + $studienplan_list .= ' ' . $rt->bezeichnung . ' '; - } + } - $studienplan_list .= ' + $studienplan_list .= ' '; - } else { - $studienplan_list = ' + } else { + $studienplan_list = ' Alles okay! Alle Studienpläne haben zumindest einen Reihungstest. '; - } + } - // Prepare HTML table with information and amount of free places - if (!empty($free_places_arr)) { - $freie_plaetze_list = ' + // Prepare HTML table with information and amount of free places + if (!empty($free_places_arr)) { + $freie_plaetze_list = ' Fakultät @@ -659,67 +661,67 @@ class ReihungstestJob extends CLI_Controller '; - foreach ($free_places_arr as $free_place) { - $datum = new DateTime($free_place->datum); - $style_alarm = ($free_place->freie_plaetze <= 5) ? ' style=" color: red; font-weight: bold" ' : ''; // mark if <=5 free places + foreach ($free_places_arr as $free_place) { + $datum = new DateTime($free_place->datum); + $style_alarm = ($free_place->freie_plaetze <= 5) ? ' style=" color: red; font-weight: bold" ' : ''; // mark if <=5 free places - $freie_plaetze_list .= ' + $freie_plaetze_list .= ' ' . $free_place->fakultaet . ' ' . $datum->format('d.m.Y') . ' ' . $free_place->freie_plaetze . ' '; - } + } - $freie_plaetze_list .= ' + $freie_plaetze_list .= ' '; - } else { - $freie_plaetze_list = ' + } else { + $freie_plaetze_list = ' Es gibt heute keine Ergebnisse zu freien Reihungstestplätze. '; - } + } - // Set associative array with the prepared HTML tables and URL be used by the template's variables - $content_data_arr['studienplan_list'] = $studienplan_list; - $content_data_arr['freie_plaetze_list'] = $freie_plaetze_list; - $content_data_arr['link'] = site_url('/organisation/Reihungstest'); + // Set associative array with the prepared HTML tables and URL be used by the template's variables + $content_data_arr['studienplan_list'] = $studienplan_list; + $content_data_arr['freie_plaetze_list'] = $freie_plaetze_list; + $content_data_arr['link'] = site_url('/organisation/Reihungstest'); - return $content_data_arr; - } + return $content_data_arr; + } - /** - * Returns associative array with data as needed in the BewerberNachReihungstest-template. - * @param array $content_arr Array with links to the testtool evaluation page of the new applicants. - * @return array - */ - private function _getContentDataNewApplicant($content_arr) - { - $content = ''; - $counter = 1; - foreach ($content_arr as $row) - { - $content .= '
Link zu: Bewerber '. $counter. ''; - $counter++; - } + /** + * Returns associative array with data as needed in the BewerberNachReihungstest-template. + * @param array $content_arr Array with links to the testtool evaluation page of the new applicants. + * @return array + */ + private function _getContentDataNewApplicant($content_arr) + { + $content = ''; + $counter = 1; + foreach ($content_arr as $row) + { + $content .= '
Link zu: Bewerber '. $counter. ''; + $counter++; + } - $content_data_arr['link'] = $content; - return $content_data_arr; - } + $content_data_arr['link'] = $content; + return $content_data_arr; + } - /** - * Checks the upcoming placement tests if there are correct studyplans assigned - * If there are invalid studyplans assigned (outdated because there exists a new version), - * it tries to find a better one and assigns it additionaly - */ - public function correctStudienplan() - { - // get all placement tests with incorrect studyplan - $qry = " + /** + * Checks the upcoming placement tests if there are correct studyplans assigned + * If there are invalid studyplans assigned (outdated because there exists a new version), + * it tries to find a better one and assigns it additionaly + */ + public function correctStudienplan() + { + // get all placement tests with incorrect studyplan + $qry = " SELECT tbl_reihungstest.reihungstest_id, tbl_studienplan.studienplan_id, @@ -752,37 +754,300 @@ class ReihungstestJob extends CLI_Controller ) "; - $db = new DB_Model(); - $result_rt = $db->execReadOnlyQuery($qry); + $db = new DB_Model(); + $result_rt = $db->execReadOnlyQuery($qry); - if (hasdata($result_rt)) { - foreach ($result_rt->retval as $row_rt) { - // find an active studyplan for the same degree program with is valid in this semester - $result_stpl = $this->StudienplanModel->getStudienplaeneBySemester( - $row_rt->studiengang_kz, - $row_rt->studiensemester_kurzbz - ); + if (hasdata($result_rt)) { + foreach ($result_rt->retval as $row_rt) { + // find an active studyplan for the same degree program with is valid in this semester + $result_stpl = $this->StudienplanModel->getStudienplaeneBySemester( + $row_rt->studiengang_kz, + $row_rt->studiensemester_kurzbz + ); - if (hasData($result_stpl)) { - foreach ($result_stpl->retval as $row_stpl) { - // Add new Studyplan to RtStudienplan if missing - $rt_studienplan = $this->RtStudienplanModel->loadWhere(array( - "reihungstest_id" => $row_rt->reihungstest_id, - "studienplan_id" => $row_stpl->studienplan_id - )); + if (hasData($result_stpl)) { + foreach ($result_stpl->retval as $row_stpl) { + // Add new Studyplan to RtStudienplan if missing + $rt_studienplan = $this->RtStudienplanModel->loadWhere(array( + "reihungstest_id" => $row_rt->reihungstest_id, + "studienplan_id" => $row_stpl->studienplan_id + )); - if (!hasData($rt_studienplan)) { - echo "\nAdding StudienplanId: $row_stpl->studienplan_id"; - echo " to ReihungstestId: $row_rt->reihungstest_id"; + if (!hasData($rt_studienplan)) { + echo "\nAdding StudienplanId: $row_stpl->studienplan_id"; + echo " to ReihungstestId: $row_rt->reihungstest_id"; - $this->RtStudienplanModel->insert(array( - "reihungstest_id" => $row_rt->reihungstest_id, - "studienplan_id" => $row_stpl->studienplan_id - )); - } - } - } - } - } - } + $this->RtStudienplanModel->insert(array( + "reihungstest_id" => $row_rt->reihungstest_id, + "studienplan_id" => $row_stpl->studienplan_id + )); + } + } + } + } + } + } + + /* + * Cronjob for priorisation process of FHTW + * + * Wenn ein Student in einer höheren Prio aufgenommen wird, werden die anderen Bewerbungen auf "Abgewiesen" gesetzt, + * solang diese noch im Status "Bewerber" sind. + * Andernfalls wird eine Mail an die niedrigeren Prios verschickt, dass eine höhere Prio aufgenommen hat + * Die Kaution wird automatisch gebucht + * + * @param string $bcc. Optional. BCC-Mailadress to send the Mails to + * @param string $from. Optional. Sender-Mailadress shown to recipient + */ + public function prioritizationJob($bcc = null, $from = null) + { + $qry = " SELECT DISTINCT + get_rolle_prestudent (tbl_prestudent.prestudent_id, 'WS2020') AS laststatus, /* Todo: Studiensemester dynamisch ermitteln oder als Parameter */ + tbl_prestudentstatus.studiensemester_kurzbz, + tbl_prestudent.* + FROM PUBLIC.tbl_person + JOIN PUBLIC.tbl_prestudent USING (person_id) + JOIN PUBLIC.tbl_prestudentstatus USING (prestudent_id) + JOIN lehre.tbl_studienplan USING (studienplan_id) + JOIN lehre.tbl_studienordnung USING (studienordnung_id) + JOIN PUBLIC.tbl_studiengang ON (tbl_studienordnung.studiengang_kz = tbl_studiengang.studiengang_kz) + WHERE tbl_prestudentstatus.datum >= (SELECT CURRENT_DATE -1) + AND get_rolle_prestudent (tbl_prestudent.prestudent_id, 'WS2020') IN ('Aufgenommener','Bewerber','Wartender') + AND studiensemester_kurzbz = 'WS2020' /* Todo: Studiensemester dynamisch ermitteln oder als Parameter */ + AND tbl_studiengang.typ = 'b' + ORDER BY studiengang_kz, laststatus + "; + + // Encode Params + if ($bcc != '') + { + // $bcc can be given as null-string, so check that too + if ($bcc == 'null') + { + $bcc = ''; + } + else + { + $bcc = urldecode($bcc); + } + } + if ($from != '') + { + $from = urldecode($from); + } + + $db = new DB_Model(); + $result_prestudents = $db->execReadOnlyQuery($qry); + $mailArray = array(); + + if (hasdata($result_prestudents)) + { + foreach ($result_prestudents->retval as $row_ps) + { + // Wenn der letzte Status "Aufgenommener" ist, alle niedrigeren Prios auf "Abgewiesen" setzen + // falls diese Bewerber oder Warteliste sind + // Danach Kaution einbuchen + if ($row_ps->laststatus == 'Aufgenommener') + { + // Alle niedrigeren Prios laden + $qryNiedrPrios = " + SELECT DISTINCT + get_rolle_prestudent (tbl_prestudent.prestudent_id, '".$row_ps->studiensemester_kurzbz."') AS laststatus, + tbl_studienplan.orgform_kurzbz, + tbl_person.nachname, + tbl_person.vorname, + tbl_prestudent.* + FROM PUBLIC.tbl_person + JOIN PUBLIC.tbl_prestudent USING (person_id) + JOIN PUBLIC.tbl_prestudentstatus USING (prestudent_id) + JOIN lehre.tbl_studienplan USING (studienplan_id) + JOIN PUBLIC.tbl_studiengang ON (tbl_prestudent.studiengang_kz = tbl_studiengang.studiengang_kz) + WHERE tbl_prestudent.person_id = ".$row_ps->person_id." + AND tbl_prestudent.prestudent_id != ".$row_ps->prestudent_id." + AND get_rolle_prestudent (tbl_prestudent.prestudent_id, '".$row_ps->studiensemester_kurzbz."') IN ('Aufgenommener','Bewerber','Wartender') + AND studiensemester_kurzbz = '".$row_ps->studiensemester_kurzbz."' + AND tbl_studiengang.typ = 'b' + AND priorisierung > ".$row_ps->priorisierung." + ORDER BY studiengang_kz, laststatus + "; + + $resultNiedrPrios = $db->execReadOnlyQuery($qryNiedrPrios); + + if (hasdata($resultNiedrPrios)) + { + foreach ($resultNiedrPrios->retval as $rowNiedrPrios) + { + if ($rowNiedrPrios->laststatus == 'Bewerber') + { + // Abgewiesenen-Status mit Statusgrund "Aufnahme anderer Studiengang" (ID 5) setzen + $lastStatus = $this->PrestudentstatusModel->getLastStatus($rowNiedrPrios->prestudent_id); + + $result = $this->PrestudentstatusModel->insert( + array( + 'prestudent_id' => $rowNiedrPrios->prestudent_id, + 'studiensemester_kurzbz' => $lastStatus->retval[0]->studiensemester_kurzbz, + 'ausbildungssemester' => $lastStatus->retval[0]->ausbildungssemester, + 'datum' => date('Y-m-d'), + 'orgform_kurzbz' => $lastStatus->retval[0]->orgform_kurzbz, + 'studienplan_id' => $lastStatus->retval[0]->studienplan_id, + 'status_kurzbz' => 'Abgewiesener', + 'statusgrund_id' => 5, + 'insertvon' => 'prioritizationJob', + 'insertamum' => date('Y-m-d H:i:s') + ) + ); + if (isSuccess($result)) + { + // Derzeit nur Info an Admins schicken, wenn er Bewerber war + $mailArray[$rowNiedrPrios->studiengang_kz][$rowNiedrPrios->orgform_kurzbz]['AbgewiesenWeilBewerber'][] + = $rowNiedrPrios->nachname.' '.$rowNiedrPrios->vorname.' ('.$rowNiedrPrios->prestudent_id.')'; + } + } + elseif ($rowNiedrPrios->laststatus == 'Wartender') + { + // Abgewiesenen-Status mit Statusgrund "Aufnahme anderer Studiengang" (ID 5) setzen + // Mail zur Info an Assistenz schicken + $lastStatus = $this->PrestudentstatusModel->getLastStatus($rowNiedrPrios->prestudent_id); + + $result = $this->PrestudentstatusModel->insert( + array( + 'prestudent_id' => $rowNiedrPrios->prestudent_id, + 'studiensemester_kurzbz' => $lastStatus->retval[0]->studiensemester_kurzbz, + 'ausbildungssemester' => $lastStatus->retval[0]->ausbildungssemester, + 'datum' => date('Y-m-d'), + 'orgform_kurzbz' => $lastStatus->retval[0]->orgform_kurzbz, + 'studienplan_id' => $lastStatus->retval[0]->studienplan_id, + 'status_kurzbz' => 'Abgewiesener', + 'statusgrund_id' => 5, + 'insertvon' => 'prioritizationJob', + 'insertamum' => date('Y-m-d H:i:s') + ) + ); + if (isSuccess($result)) + { + $mailArray[$rowNiedrPrios->studiengang_kz][$rowNiedrPrios->orgform_kurzbz]['AbgewiesenGesetztWartender'][] + = $rowNiedrPrios->nachname.' '.$rowNiedrPrios->vorname.' ('.$rowNiedrPrios->prestudent_id.')'; + } + } + elseif ($rowNiedrPrios->laststatus == 'Aufgenommener') + { + // Mail zur Info an Assistenz schicken, dass in höherer Prio aufgenommen wurde + $mailArray[$rowNiedrPrios->studiengang_kz][$rowNiedrPrios->orgform_kurzbz]['AufnahmeHoeherePrio'][] + = $rowNiedrPrios->nachname.' '.$rowNiedrPrios->vorname.' ('.$rowNiedrPrios->prestudent_id.')'; + } + } + } + + // Kaution einbuchen für $row_ps->prestudent_id + // Vorher prüfen, ob schon eine Kaution gebucht ist + // Todo: Betrag automatisch aus tbl_buchungstyp laden + + $qryKautionExists = " + SELECT count(*) as anzahl + FROM public.tbl_konto + WHERE person_id = ".$row_ps->person_id." + AND studiensemester_kurzbz = '".$row_ps->studiensemester_kurzbz."' + AND buchungstyp_kurzbz = 'Kaution'"; + + $resultKautionExists = $db->execReadOnlyQuery($qryKautionExists); + if (hasdata($resultKautionExists)) + { + if ($resultKautionExists->retval[0]->anzahl == '0') + { + // Todo: Zahlungsreferenz generieren (StudiengangsOE+Buchungsnummer) + $this->KontoModel->insert(array( + "person_id" => $row_ps->person_id, + "studiengang_kz" => $row_ps->studiengang_kz, + "studiensemester_kurzbz" => $row_ps->studiensemester_kurzbz, + "betrag" => -150, + "buchungsdatum" => date('Y-m-d'), + "buchungstext" => 'Kaution', + "buchungstyp_kurzbz" => 'Kaution', + "insertvon" => 'prioritizationJob', + "insertamum" => date('Y-m-d H:i:s') + )); + } + } + } + } + } + + // Mails senden + if (!isEmptyArray($mailArray)) + { + foreach ($mailArray AS $stg=>$orgform) + { + $studiengang = $this->StudiengangModel->load($stg); + $mailcontent = ''; + + foreach ($orgform AS $art=>$value) + { + // Orgform nur dazu schreiben, wenn es mehr als Eine gibt + if (count($orgform) > 1) + { + $mailcontent .= '

Orgform '.$art.'

'; + } + if (isset($value['AbgewiesenGesetztWartender']) && !isEmptyArray($value['AbgewiesenGesetztWartender'])) + { + $mailcontent .= '

+ Folgende Personen auf der Warteliste wurden in einem höher priorisierten Studiengang aufgenommen und haben deshalb einen Status "Abgewiesen" erhalten:

'; + $mailcontent .= ''; + //$mailcontent .= ''; + $mailcontent .= ' '; + sort($value['AbgewiesenGesetztWartender']); + foreach ($value['AbgewiesenGesetztWartender'] AS $key=>$bewerber) + { + $mailcontent .= ''; + } + $mailcontent .= '
Zuvor Warteliste
'.$bewerber.'


'; + } + if (isset($value['AufnahmeHoeherePrio']) && !isEmptyArray($value['AufnahmeHoeherePrio'])) + { + $mailcontent .= '

+ Folgende Aufgenommene wurden in einem höher priorisierten Studiengang aufgenommen:

'; + $mailcontent .= ''; + //$mailcontent .= ''; + $mailcontent .= ' '; + sort($value['AufnahmeHoeherePrio']); + foreach ($value['AufnahmeHoeherePrio'] AS $key=>$bewerber) + { + $mailcontent .= ''; + } + $mailcontent .= '
Aufgenommene
'.$bewerber.'
'; + } + if ($bcc != '' && isset($value['AbgewiesenWeilBewerber']) && !isEmptyArray($value['AbgewiesenWeilBewerber'])) + { + $mailcontent .= '

+ Folgende BewerberInnen wurden zu Abgewiesenen gemacht:

'; + $mailcontent .= ''; + //$mailcontent .= ''; + $mailcontent .= ' '; + sort($value['AbgewiesenWeilBewerber']); + foreach ($value['AbgewiesenWeilBewerber'] AS $key => $bewerber) + { + $mailcontent .= ''; + } + $mailcontent .= '
Aufgenommene
'.$bewerber.'
'; + } + } + + $mailcontent_data_arr['table'] = $mailcontent; + + // Send email in Sancho design + if (!isEmptyString($mailcontent)) + { + sendSanchoMail( + 'Sancho_ReihungstestteilnehmerJob', + $mailcontent_data_arr, + $studiengang->retval[0]->email, + 'Status Abgewiesen gesetzt', + 'sancho_header_min_bw.jpg', + 'sancho_footer_min_bw.jpg', + $from, + '', + $bcc); + } + } + } + } } diff --git a/application/controllers/system/FASMessages.php b/application/controllers/system/FASMessages.php deleted file mode 100644 index e656db790..000000000 --- a/application/controllers/system/FASMessages.php +++ /dev/null @@ -1,191 +0,0 @@ - 'basis/message:rw', - 'writeReply' => 'basis/message:rw' - ) - ); - - // Loads the message library - $this->load->library('MessageLib'); - - // Loads the widget library - $this->load->library('WidgetLib'); - - $this->loadPhrases( - array( - 'global', - 'ui' - ) - ); - } - - // ----------------------------------------------------------------------------------------------------------------- - // Public methods - - /** - * Write a new message - */ - public function write($sender_id) - { - $prestudent_id = $this->input->post('prestudent_id'); // recipients prestudend_id(s) - - if (!is_numeric($sender_id)) - { - show_error('The current logged user person_id is not defined'); - } - - $msgVarsData = $this->_getMsgVarsData($prestudent_id); - - // Retrieves message vars for a person from view view vw_msg_vars_person - $variablesArray = $this->_getMessageVarsPerson(); - - // Organisation units used to get the templates - $oe_kurzbz = $this->_getOeKurzbz($sender_id); - - // Admin or commoner? - $isAdmin = $this->_getIsAdmin($sender_id); - - $data = array( - 'recipients' => getData($msgVarsData), - 'variables' => $variablesArray, - 'oe_kurzbz' => $oe_kurzbz, // used to get the templates - 'isAdmin' => $isAdmin - ); - - $this->load->view('system/messages/messageWrite', $data); - } - - /** - * Write a reply - */ - public function writeReply($sender_id, $msg_id, $receiver_id) - { - $prestudent_id = $this->input->post('prestudent_id'); // recipients prestudend_id(s) - - if (!is_numeric($sender_id)) - { - show_error('The current logged user person_id is not defined'); - } - - if (!is_numeric($msg_id)) - { - show_error('The msg_id must be a number'); - } - - if (!is_numeric($receiver_id)) - { - show_error('The receiver_id must be a number'); - } - - $msg = $this->_getMessage($msg_id, $receiver_id); - - $msgVarsData = $this->_getMsgVarsData($prestudent_id); - - // Retrieves message vars for a person from view view vw_msg_vars_person - $variablesArray = $this->_getMessageVarsPerson(); - - // Organisation units used to get the templates - $oe_kurzbz = $this->_getOeKurzbz($sender_id); - - // Admin or commoner? - $isAdmin = $this->_getIsAdmin($sender_id); - - $data = array( - 'recipients' => getData($msgVarsData), - 'message' => $msg, - 'variables' => $variablesArray, - 'oe_kurzbz' => $oe_kurzbz, // used to get the templates - 'isAdmin' => $isAdmin - ); - - $this->load->view('system/messages/messageWrite', $data); - } - - // ----------------------------------------------------------------------------------------------------------------- - // Private methods - - /** - * - */ - private function _getMessage($msg_id, $receiver_id) - { - $msg = $this->messagelib->getMessage($msg_id, $receiver_id); - if (isError($msg)) - { - show_error(getError($msg)); - } - elseif (!hasData($msg)) - { - show_error('The selected message does not exist'); - } - else - { - $msg = getData($msg)[0]; - } - - return $msg; - } - - /** - * Retrieves message vars from view vw_msg_vars - */ - private function _getMsgVarsData($prestudent_id) - { - $this->load->model('system/Message_model', 'MessageModel'); - $msgVarsData = $this->MessageModel->getMsgVarsDataByPrestudentId($prestudent_id); - - if (isError($msgVarsData)) - { - show_error(getError($msgVarsData)); - } - - return $msgVarsData; - } - - /** - * Wrapper method to call messagelib->getMessageVarsPerson - */ - private function _getMessageVarsPerson() - { - $variables = $this->messagelib->getMessageVarsPerson(); - - if (isError($variables)) show_error(getError($variables)); - - return getData($variables); - } - - /** - * Wrapper method to call messagelib->getOeKurzbz - */ - private function _getOeKurzbz($sender_id) - { - $oe_kurzbz = $this->messagelib->getOeKurzbz($sender_id); - - if (isError($oe_kurzbz)) show_error(getError($oe_kurzbz)); - - return getData($oe_kurzbz); - } - - /** - * Wrapper method to call messagelib->getIsAdmin - */ - private function _getIsAdmin($sender_id) - { - $isAdmin = $this->messagelib->getIsAdmin($sender_id); - - if (isError($isAdmin)) show_error(getError($isAdmin)); - - return getData($isAdmin); - } -} diff --git a/application/controllers/system/Messages.php b/application/controllers/system/Messages.php deleted file mode 100644 index 58ffbd0a7..000000000 --- a/application/controllers/system/Messages.php +++ /dev/null @@ -1,210 +0,0 @@ - array('basis/message:rw', 'infocenter:rw'), - 'send' => array('basis/message:rw', 'infocenter:rw'), - 'sendJson' => array('basis/message:rw', 'infocenter:rw'), - 'getVorlage' => array('basis/message:r', 'infocenter:r'), - 'parseMessageText' => array('basis/message:r', 'infocenter:r'), - 'getMessageFromIds' => array('basis/message:r', 'infocenter:r') - ) - ); - - // Loads the message library - $this->load->library('MessageLib'); - - // Loads the widget library - $this->load->library('WidgetLib'); - - $this->load->model('system/Message_model', 'MessageModel'); - $this->load->model('CL/Messages_model', 'CLMessagesModel'); - - $this->loadPhrases( - array( - 'global', - 'ui' - ) - ); - } - - // ----------------------------------------------------------------------------------------------------------------- - // Public methods - - /** - * Write a new message - */ - public function write() - { - $person_id = $this->input->post('person_id'); - $sender_id = null; - - $authUser = $this->CLMessagesModel->getAuthUser(); - if (isError($authUser)) - { - show_error(getError($authUser)); - } - else - { - $sender_id = getData($authUser)[0]->person_id; - } - - $msgVarsData = $this->MessageModel->getMsgVarsDataByPersonId($person_id); - if (isError($msgVarsData)) show_error(getError($msgVarsData)); - - // Retrieves message vars for a person from view view vw_msg_vars_person - $variables = $this->messagelib->getMessageVarsPerson(); - if (isError($variables)) show_error(getError($variables)); - - // Organisation units used to get the templates - $oe_kurzbz = $this->messagelib->getOeKurzbz($sender_id); - if (isError($oe_kurzbz)) show_error(getError($oe_kurzbz)); - - // Admin or commoner? - $isAdmin = $this->messagelib->getIsAdmin($sender_id); - if (isError($isAdmin)) show_error(getError($isAdmin)); - - $data = array ( - 'recipients' => getData($msgVarsData), - 'variables' => getData($variables), - 'oe_kurzbz' => getData($oe_kurzbz), // used to get the templates - 'isAdmin' => getData($isAdmin) - ); - - $this->load->view('system/messages/messageWrite', $data); - } - - /** - * Send message - */ - public function send() - { - $persons = $this->input->post('persons'); - $relationmessage_id = $this->input->post('relationmessage_id'); - - $msgVarsData = $this->MessageModel->getMsgVarsDataByPersonId($persons); - - $send = $this->CLMessagesModel->send($msgVarsData, $relationmessage_id); - - $this->load->view('system/messages/messageSent', array('success' => isSuccess($send))); - } - - /** - * Send message, response is in JSON format - */ - public function sendJson() - { - $prestudents = $this->input->post('prestudents'); - $vorlage_kurzbz = $this->input->post('vorlage_kurzbz'); - $oe_kurzbz = $this->input->post('oe_kurzbz'); - $msgVars = $this->input->post('msgvars'); - - $msgVarsData = $this->MessageModel->getMsgVarsDataByPrestudentId($prestudents); - - $this->load->model('crm/Prestudent_model', 'PrestudentModel'); - $prestudentsData = $this->PrestudentModel->getOrganisationunits($prestudents); - - // Adds the organisation unit to each prestudent - if (isEmptyString($oe_kurzbz) && hasData($msgVarsData) && hasData($prestudentsData)) - { - $this->CLMessagesModel->addOeToPrestudents($msgVarsData, $prestudentsData); - } - - $send = $this->CLMessagesModel->send($msgVarsData, null, $oe_kurzbz, $vorlage_kurzbz, $msgVars); - if (isError($send)) - { - $this->outputJsonError(getError($send)); - } - else - { - $this->outputJsonSuccess(getData($send)); - } - } - - /** - * getVorlage - */ - public function getVorlage() - { - $vorlage_kurzbz = $this->input->get('vorlage_kurzbz'); - $result = null; - - if (!isEmptyString($vorlage_kurzbz)) - { - $this->load->model('system/Vorlagestudiengang_model', 'VorlagestudiengangModel'); - $this->VorlagestudiengangModel->addOrder('version','DESC'); - - $result = $this->VorlagestudiengangModel->loadWhere(array('vorlage_kurzbz' => $vorlage_kurzbz)); - } - else - { - $result = error('The given vorlage_kurzbz is not valid'); - } - - if (isError($result) || !hasData($result)) - { - $this->outputJsonError(getError($result)); - } - else - { - $this->outputJsonSuccess(getData($result)); - } - } - - /** - * parseMessageText - */ - public function parseMessageText() - { - $person_id = $this->input->get('person_id'); - $text = $this->input->get('text'); - $parsedText = ''; - $data = null; - - if (is_numeric($person_id)) - { - $data = $this->MessageModel->getMsgVarsDataByPersonId($person_id); - } - else - { - $data = error('The given person_id is not a valid number'); - } - - if (isError($data) || !hasData($data)) - { - $this->outputJsonError(getError($data)); - } - else - { - $parsedText = $this->messagelib->parseMessageText($text, $this->CLMessagesModel->replaceKeys((array)getData($data)[0])); - - $this->outputJsonSuccess($parsedText); - } - } - - /** - * Outputs message data for a message (identified my msg id and receiver id) in JSON format - * @param $msg_id - * @param $receiver_id - */ - public function getMessageFromIds() - { - $msg_id = $this->input->get('msg_id'); - $receiver_id = $this->input->get('receiver_id'); - - $msg = $this->messagelib->getMessage($msg_id, $receiver_id); - - $this->output - ->set_content_type('application/json') - ->set_output(json_encode(array(getData($msg)[0]))); - } -} diff --git a/application/controllers/system/Phrases.php b/application/controllers/system/Phrases.php index f589eaeb2..2bb003567 100644 --- a/application/controllers/system/Phrases.php +++ b/application/controllers/system/Phrases.php @@ -161,7 +161,7 @@ class Phrases extends Auth_Controller $phrase_inhalt = $this->phraseslib->insertPhraseinhalt($data); if ($phrase_inhalt->error) - show_error(getError($phrase_inhalt); + show_error(getError($phrase_inhalt)); $phrase_inhalt_id = $phrase_inhalt->retval; diff --git a/application/controllers/system/Vorlage.php b/application/controllers/system/Vorlage.php index ba8b26137..7ae79c77f 100644 --- a/application/controllers/system/Vorlage.php +++ b/application/controllers/system/Vorlage.php @@ -269,7 +269,7 @@ class Vorlage extends Auth_Controller show_error(getError($vorlagetext)); $data = array( - 'text' => $this->vorlagelib->parseVorlagetext($vorlagetext->retval[0]->text, $jsonDecodedForm) + 'text' => parseText($vorlagetext->retval[0]->text, $jsonDecodedForm) ); $this->load->view('system/vorlage/templatetextPreview', $data); diff --git a/application/controllers/system/infocenter/InfoCenter.php b/application/controllers/system/infocenter/InfoCenter.php index d085e7db0..92636e6df 100644 --- a/application/controllers/system/infocenter/InfoCenter.php +++ b/application/controllers/system/infocenter/InfoCenter.php @@ -69,6 +69,7 @@ class InfoCenter extends Auth_Controller // Name of Interessentenstatus const INTERESSENTSTATUS = 'Interessent'; const ABGEWIESENERSTATUS = 'Abgewiesener'; + const BEWERBERSTATUS = 'Bewerber'; // Statusgruende for which no Studiengangsfreigabemessage should be sent private $_statusgruendeNoStgFreigabeMessage = array('FIT Programm', 'FIT program', 'FIT programme'); @@ -493,7 +494,9 @@ class InfoCenter extends Auth_Controller $logdata = $this->_getPersonAndStudiengangFromPrestudent($prestudent_id); - $akteresult = $this->AkteModel->loadWhere(array('person_id' => $logdata['person_id'], 'formal_geprueft_amum !=' => NULL)); + $person_id = $logdata['person_id']; + + $akteresult = $this->AkteModel->loadWhere(array('person_id' => $person_id, 'formal_geprueft_amum !=' => NULL)); if (hasData($lastStatus) && isSuccess($akteresult)) { @@ -529,6 +532,8 @@ class InfoCenter extends Auth_Controller if (isSuccess($result)) { $this->load->model('crm/Dokumentprestudent_model', 'DokumentprestudentModel'); + $json->retval['nonCriticalErrors'] = array(); + $json->retval['infoMessages'] = array(); //set documents which have been formal geprüft to accepted $dokument_kurzbzs = array(); @@ -542,7 +547,7 @@ class InfoCenter extends Auth_Controller // acceptresult returns null if no documents to accept if ($acceptresult !== null && isError($acceptresult)) - $json->retval['nonCriticalErrors'] = 'error when accepting documents in FAS'; + $json->retval['nonCriticalErrors'][] = 'error when accepting documents in FAS'; $logparams = array($prestudent_id, $logdata['studiengang_kurzbz'], ''); @@ -554,8 +559,69 @@ class InfoCenter extends Auth_Controller if (hasData($statusgrund_kurzbz)) $logparams[2] = ', confirmation type '.$statusgrund_kurzbz->retval[0]->bezeichnung_mehrsprachig[0]; } + else + { + // check if there is already a Bewerberstatus and Reihungsverfahren already absolviert + $bewerber = $this->PersonModel->hasBewerber($person_id, $lastStatus->studiensemester_kurzbz, 'b'); - $this->_log($logdata['person_id'], 'freigegeben', $logparams); + if (hasData($bewerber)) + { + $bewerbercnt = getData($bewerber); + + if (is_numeric($bewerbercnt[0]->anzahl_bewerber) && $bewerbercnt[0]->anzahl_bewerber > 0) + { + // then insert Bewerberstatus and rt absolviert, teilgenommen for prestudent + $bewerberresult = $this->PrestudentstatusModel->insert( + array( + 'prestudent_id' => $prestudent_id, + 'status_kurzbz' => self::BEWERBERSTATUS, + 'studiensemester_kurzbz' => $lastStatus->studiensemester_kurzbz, + 'ausbildungssemester' => $lastStatus->ausbildungssemester, + 'datum' => date('Y-m-d'), + 'orgform_kurzbz' => $lastStatus->orgform_kurzbz, + 'studienplan_id' => $lastStatus->studienplan_id, + 'insertvon' => $this->_uid, + 'insertamum' => date('Y-m-d H:i:s') + ) + ); + + if (isError($bewerberresult)) + $json->retval['nonCriticalErrors'][] = 'error when inserting Bewerberstatus'; + + $rtangetretenres = $this->PrestudentModel->update( + $prestudent_id, + array( + 'reihungstestangetreten' => true + ) + ); + + if (isError($rtangetretenres)) + { + $json->retval['nonCriticalErrors'][] = 'error when setting reihungstestangetreten'; + } + else + { + $json->retval['infoMessages'][] = $this->p->t('infocenter', 'rtPunkteEintragenInfo'); + $this->load->model('crm/RtPerson_model', 'RtPersonModel'); + + $rtteilgenommenres = $this->RtPersonModel->update( + array( + 'person_id' => $person_id, + 'studienplan_id' => $lastStatus->studienplan_id + ), + array( + 'teilgenommen' => true + ) + ); + + if (isError($rtteilgenommenres)) + $json->retval['nonCriticalErrors'][] = 'error when setting reihungstest teilgenommen'; + } + } + } + } + + $this->_log($person_id, 'freigegeben', $logparams); $this->_sendFreigabeMail($prestudent_id); } @@ -649,7 +715,7 @@ class InfoCenter extends Auth_Controller public function reloadMessages($person_id) { $messages = $this->MessageModel->getMessagesOfPerson($person_id, 1); - $this->load->view('system/messages/messageList.php', array('messages' => $messages->retval)); + $this->load->view('system/infocenter/messageList.php', array('messages' => $messages->retval)); } /** @@ -1496,7 +1562,7 @@ class InfoCenter extends Auth_Controller } /** - * Sends infomail with prestudent and person data when Prestudent is freigegeben + * Sends infomail to Studiengang with prestudent and person data when Prestudent is freigegeben * @param $prestudent_id */ private function _sendFreigabeMail($prestudent_id) diff --git a/application/controllers/system/messages/FASMessages.php b/application/controllers/system/messages/FASMessages.php new file mode 100644 index 000000000..55d1da25f --- /dev/null +++ b/application/controllers/system/messages/FASMessages.php @@ -0,0 +1,60 @@ + 'basis/message:rw', + 'writeReplyTemplate' => 'basis/message:rw' + ) + ); + + // Loads model CLMessagesModel which contains the GUI logic + $this->load->model('CL/Messages_model', 'CLMessagesModel'); + + // Phrases used in loaded views + $this->loadPhrases( + array( + 'global', + 'ui' + ) + ); + } + + /** + * Writes a new message to a prestudent using templates + */ + public function writeTemplate() + { + $prestudents = $this->input->post('prestudent_id'); // recipients prestudend_id(s) + + // Loads the view to write a new message with a template + $this->load->view( + 'system/messages/htmlWriteTemplate', + $this->CLMessagesModel->prepareHtmlWriteTemplatePrestudents($prestudents) + ); + } + + /** + * Writes a reply to a message identified by parameters $message_id and $recipient_id + * The recipient is a prestudent + * Uses templates + */ + public function writeReplyTemplate($message_id, $recipient_id) + { + $prestudents = $this->input->post('prestudent_id'); // recipients prestudend_id(s) + + // Loads the view to write a new message with a template + $this->load->view( + 'system/messages/htmlWriteTemplate', + $this->CLMessagesModel->prepareHtmlWriteTemplatePrestudents($prestudents, $message_id, $recipient_id) + ); + } +} diff --git a/application/controllers/system/messages/MessageClient.php b/application/controllers/system/messages/MessageClient.php new file mode 100644 index 000000000..a0cc5c518 --- /dev/null +++ b/application/controllers/system/messages/MessageClient.php @@ -0,0 +1,112 @@ +load->library('AuthLib'); + + // Loads model CLMessagesModel which contains the GUI logic + $this->load->model('CL/Messages_model', 'CLMessagesModel'); + + // Phrases used in loaded views + $this->loadPhrases( + array( + 'global', + 'ui' + ) + ); + } + + /** + * Starts the GUI used to read all the personal messages + */ + public function read() + { + // Loads the view to read messages + $this->load->view('system/messages/ajaxRead'); + } + + /** + * Starts the GUI used to write a personal message to an organisation unit + */ + public function write() + { + // Loads the view to write a message + $this->load->view('system/messages/ajaxWrite', $this->CLMessagesModel->prepareAjaxWrite()); + } + + /** + * Starts the GUI used to reply to a received personal message + */ + public function writeReply() + { + $token = $this->input->get('token'); + + // Loads the view to reply to a message + $this->load->view('system/messages/ajaxWriteReply', $this->CLMessagesModel->prepareAjaxWriteReply($token)); + } + + /** + * Returns JSON that that contains all the received messages by the currently logged user + */ + public function listReceivedMessages() + { + $this->outputJson($this->CLMessagesModel->prepareAjaxReadReceived()); + } + + /** + * Returns JSON that that contains all the sent messages by the currently logged user + */ + public function listSentMessages() + { + $this->outputJson($this->CLMessagesModel->prepareAjaxReadSent()); + } + + /** + * Sends a message to an organisation unit + */ + public function sendMessageToOU() + { + $receiverOU = $this->input->post('receiverOU'); + $subject = $this->input->post('subject'); + $body = $this->input->post('body'); + + $this->outputJson($this->CLMessagesModel->sendToOrganisationUnit($receiverOU, $subject, $body)); + } + + /** + * Sends a message to an organisation unit + */ + public function sendMessageReply() + { + $receiver_id = $this->input->post('receiver_id'); + $relationmessage_id = $this->input->post('relationmessage_id'); + $token = $this->input->post('token'); + $subject = $this->input->post('subject'); + $body = $this->input->post('body'); + + $this->outputJson($this->CLMessagesModel->sendReply($receiver_id, $subject, $body, $relationmessage_id, $token)); + } + + /** + * Set a message as read + */ + public function setMessageRead() + { + $message_id = $this->input->post('message_id'); + $statusPersonId = $this->input->post('statusPersonId'); + + $this->outputJson($this->CLMessagesModel->setMessageRead($message_id, $statusPersonId)); + } +} diff --git a/application/controllers/system/messages/Messages.php b/application/controllers/system/messages/Messages.php new file mode 100644 index 000000000..296022ca4 --- /dev/null +++ b/application/controllers/system/messages/Messages.php @@ -0,0 +1,144 @@ + array('basis/message:rw', 'infocenter:rw'), + 'sendImplicitTemplate' => array('basis/message:rw', 'infocenter:rw'), + 'sendExplicitTemplateJson' => array('basis/message:rw', 'infocenter:rw'), + 'getVorlage' => array('basis/message:r', 'infocenter:r'), + 'parseMessageText' => array('basis/message:r', 'infocenter:r'), + 'getMessageFromIds' => array('basis/message:r', 'infocenter:r') + ) + ); + + // Loads model CLMessagesModel which contains the GUI logic + $this->load->model('CL/Messages_model', 'CLMessagesModel'); + + // Phrases used in loaded views + $this->loadPhrases( + array( + 'global', + 'ui' + ) + ); + } + + // ----------------------------------------------------------------------------------------------------------------- + // Methods with HTML output + + /** + * Initialize all the parameters used by view system/messages/htmlWriteTemplate + * to build a GUI used to write a messate to user/s using a template + */ + public function writeTemplate() + { + $persons = $this->input->post('person_id'); + + // Loads the view to write a new message with a template + $this->load->view( + 'system/messages/htmlWriteTemplate', + $this->CLMessagesModel->prepareHtmlWriteTemplatePersons($persons) + ); + } + + /** + * Send a new message or reply to user/s + * If a relationmessage_id this message is a reply to another one + * Body is a template and will be parsed using information present in persons parameter + */ + public function sendImplicitTemplate() + { + $subject = $this->input->post('subject'); + $body = $this->input->post('body'); + $recipients_ids = $this->input->post('recipients_ids'); + $relationmessage_id = $this->input->post('relationmessage_id'); + $type = $this->input->post('type'); + + $sendImplicitTemplate = $this->CLMessagesModel->sendImplicitTemplate($type, $recipients_ids, $subject, $body, $relationmessage_id); + if (isSuccess($sendImplicitTemplate)) + { + $this->load->view('system/messages/htmlMessageSentSuccess'); + } + else + { + $this->load->view('system/messages/htmlMessageSentError'); + } + } + + // ----------------------------------------------------------------------------------------------------------------- + // Methods with JSON output called by this controller and FASMessages (view system/messages/htmlWriteTemplate) + + /** + * Returns an object that represent a template store in database + * If no templates are found with the given parameter or the given parameter is an empty string, + * then an error is returned + */ + public function getVorlage() + { + $vorlage_kurzbz = $this->input->get('vorlage_kurzbz'); + + $this->outputJson($this->CLMessagesModel->getVorlage($vorlage_kurzbz)); + } + + /** + * Parse the given given text using data from the given user + * Use the CI parser which performs simple text substitution for pseudo-variable + */ + public function parseMessageText() + { + $receiver_id = $this->input->post('receiver_id'); + $text = $this->input->post('text'); + $type = $this->input->post('type'); + + if ($type == Messages_model::TYPE_PERSONS) + { + $this->outputJson($this->CLMessagesModel->parseMessageTextPerson($receiver_id, $text)); + } + elseif ($type == Messages_model::TYPE_PRESTUDENTS) + { + $this->outputJson($this->CLMessagesModel->parseMessageTextPrestudent($receiver_id, $text)); + } + else + { + $this->outputJsonError('Not a person nor a prestudent was provided'); + } + } + + // ----------------------------------------------------------------------------------------------------------------- + // Methods with JSON output called by infocenter + + /** + * Outputs message data for a message (identified my msg id and receiver id) in JSON format + */ + public function getMessageFromIds() + { + $message_id = $this->input->get('msg_id'); + $receiver_id = $this->input->get('receiver_id'); + + $this->outputJson($this->CLMessagesModel->getMessageFromIds($message_id, $receiver_id)); + } + + /** + * Send a new message + * - The recipients are prestudents + * - An email template with message var may be provided + * - A global organisation unit may be provided, otherwise is used the prestudent one + * - A template is explicitly specified + */ + public function sendExplicitTemplateJson() + { + $prestudents = $this->input->post('prestudents'); + $oe_kurzbz = $this->input->post('oe_kurzbz'); + $vorlage_kurzbz = $this->input->post('vorlage_kurzbz'); + $msgVars = $this->input->post('msgvars'); + + $sendExplicitTemplate = $this->CLMessagesModel->sendExplicitTemplate($prestudents, $oe_kurzbz, $vorlage_kurzbz, $msgVars); + $this->outputJson(getData($sendExplicitTemplate)); + } +} diff --git a/application/controllers/system/messages/ViewMessage.php b/application/controllers/system/messages/ViewMessage.php new file mode 100644 index 000000000..ccb9afb33 --- /dev/null +++ b/application/controllers/system/messages/ViewMessage.php @@ -0,0 +1,134 @@ +config->load('message'); + + // Load model MessageToken_model, not calling the authentication system + $this->load->model('CL/Messages_model', 'CLMessagesModel'); + + // Phrases used in loaded views + $this->loadPhrases( + array( + 'global', + 'ui' + ) + ); + } + + /** + * Display a message in read mode only using the specified token + */ + public function toHTML($token) + { + // Loads the view to read a received message using its token as identifier + $this->load->view('system/messages/htmlRead', $this->CLMessagesModel->prepareHtmlRead($token)); + } + + /** + * Write a reply message to a received one using its token as identifier + */ + public function writeReply() + { + $token = $this->input->get('token'); // gets received message token + + // Loads the view to write a reply message + $this->load->view('system/messages/htmlWriteReply', $this->CLMessagesModel->prepareHtmlWriteReply($token)); + } + + /** + * Send a reply message (no templates are used) + */ + public function sendReply() + { + $subject = $this->input->post('subject'); + $body = $this->input->post('body'); + $receiver_id = $this->input->post('receiver_id'); + $relationmessage_id = $this->input->post('relationmessage_id'); + $token = $this->input->post('token'); + + $sendReply = $this->CLMessagesModel->sendReply($receiver_id, $subject, $body, $relationmessage_id, $token); + if (isSuccess($sendReply)) + { + $this->load->view('system/messages/htmlMessageSentSuccess'); + } + else + { + $this->load->view('system/messages/htmlMessageSentError'); + } + } + + /** + * With the given token redirects the user to reply page configured in the config/message.php file + */ + public function redirectByToken($token) + { + // Loads model MessageTokenModel + $this->load->model('system/MessageToken_model', 'MessageTokenModel'); + + // Retrieves the single message data using the given token + $msg = $this->MessageTokenModel->getMessageByToken($token); + // If it is an error or it does not contain data show an error + if (!hasData($msg)) show_error('MSG-ERR-0001: An error occurred while redirecting, please contact the administrator'); + // else + $oe_kurzbz = getData($msg)[0]->oe_kurzbz; + + $organisationRoot = null; // by default is null + + // If an organisation unit is present in the message tries to retrieve the root organisation unit + // from the one found in the message + if (!isEmptyString($oe_kurzbz)) + { + // Retrieves the root organisation unit from the one found in the message + $getOERoot = $this->MessageTokenModel->getOERoot($oe_kurzbz); + // If it is an error or it does not contain data show an error + if (!hasData($getOERoot)) show_error('MSG-ERR-0002: An error occurred while redirecting, please contact the administrator'); + // else + $organisationRoot = getData($getOERoot)[0]->oe_kurzbz; + } + + // Retrieves the possible redirecting URLs array from configs + $messageRedirectUrls = $this->config->item('message_redirect_url'); + // If it is not a valid array then show an error + if (isEmptyArray($messageRedirectUrls)) show_error('MSG-ERR-0003: An error occurred while redirecting, please contact the administrator'); + + // If this organisation unit root is not configured as an entry in the possible redirecting URLs array, + // then tries to use the default one... + if (!isset($messageRedirectUrls[$organisationRoot])) + { + $organisationRoot = 'fallback'; + + // ...if even the default one is not present show an error + if (!isset($messageRedirectUrls[$organisationRoot])) + { + show_error('MSG-ERR-0004: An error occurred while redirecting, please contact the administrator'); + } + } + + // Finally if everything was right then the user can be redirected + redirect($messageRedirectUrls[$organisationRoot] . '?token=' . $token); + } +} diff --git a/application/helpers/hlp_authentication_helper.php b/application/helpers/hlp_authentication_helper.php index 194f0b249..459c7fb80 100644 --- a/application/helpers/hlp_authentication_helper.php +++ b/application/helpers/hlp_authentication_helper.php @@ -20,7 +20,6 @@ function getAuthPersonId() return isLogged() ? ($ci->authlib->getAuthObj())->{AuthLib::AO_PERSON_ID} : null; } - /** * If the user is NOT logged then a null value is returned. * If the user is alredy logged, then it is possible to access to the authentication object diff --git a/application/helpers/hlp_common_helper.php b/application/helpers/hlp_common_helper.php index bb8b1b8e4..6a2675a04 100644 --- a/application/helpers/hlp_common_helper.php +++ b/application/helpers/hlp_common_helper.php @@ -24,39 +24,54 @@ if (! defined('BASEPATH')) exit('No direct script access allowed'); // ------------------------------------------------------------------------ /** - * generateToken() - generates a new token for diffent use - * - reading Messages from external - * - forgotten Password - * - * @return string + * Generates a new token for diffent use cases. Default token length is 64 + * - Reading messages + * - Forgotten password + * - etc + * Returns null on failure */ function generateToken($length = 64) { + $token = null; + $firstGeneratedToken = null; + // For PHP 7 you can use random_bytes() if (function_exists('random_bytes')) { - $token = base64_encode(random_bytes($length)); - //base64 is about 33% longer, so we need to truncate the result - return strtr(substr($token, 0, $length), '+/=', '-_,'); + try + { + $firstGeneratedToken = random_bytes($length); // try to generates cryptographically secure pseudo-random bytes... + } + catch (Exception $e) { $firstGeneratedToken = null; } // if fails $firstGeneratedToken is set to null } - - // for PHP >=5.3 and <7 - if (function_exists('openssl_random_pseudo_bytes')) + // For PHP >= 5.3 and < 7 and openssl is available + elseif (function_exists('openssl_random_pseudo_bytes')) { - $token = base64_encode(openssl_random_pseudo_bytes($length, $strong)); - // is the token strong enough? - if($strong == true) - return strtr(substr($token, 0, $length), '+/=', '-_,'); + $firstGeneratedToken = openssl_random_pseudo_bytes($length, $strong); + // If the token generation ended with errors OR the generated token is NOT strong enough + if ($firstGeneratedToken == false || $strong == false) $firstGeneratedToken = null; // $firstGeneratedToken is set to null } - //fallback to mt_rand if php < 5.3 or no openssl available - $characters = '0123456789'; - $characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+'; - $charactersLength = strlen($characters)-1; - $token = ''; - //select some random characters - for ($i = 0; $i < $length; $i++) - $token .= $characters[mt_rand(0, $charactersLength)]; + if ($firstGeneratedToken != null) // If everything was fine + { + // base64 is about 33% longer, so we need to truncate the result + $token = strtr(substr(base64_encode($firstGeneratedToken), 0, $length), '+/=', '-_,'); + } + + // Fallback to mt_rand if: + // php < 5.3 + // OR no openssl is available + // OR openssl_random_pseudo_bytes used an algorithm that is cryptographically NOT strong + // OR one of the previous methods failed + if ($token == null) + { + $token = ''; // set $token as an empty string + $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+'; + $charactersLength = strlen($characters) - 1; + + // Select some random characters + for ($i = 0; $i < $length; $i++) $token .= $characters[mt_rand(0, $charactersLength)]; + } return $token; } @@ -225,6 +240,52 @@ function isDateWorkingDay($date, $days = null) } } +/** + * Parse the given text using the given data parameter + * Use the CI parser which performs simple text substitution for pseudo-variable + */ +function parseText($text, $data) +{ + $ci =& get_instance(); // get CI instance + $ci->load->library('parser'); // Loads CI parser library + + return $ci->parser->parse_string($text, $data, true); +} + +/** + * Parse the given template using the given data parameter + * Use the CI parser which performs simple text substitution for pseudo-variable + */ +function parseTemplate($template, $data) +{ + $ci =& get_instance(); // get CI instance + $ci->load->library('parser'); // Loads CI parser library + + return $ci->parser->parse($template, $data, true); +} + +/** + * Terminate immediately the execution of the current script. + * If message parameter is given then: + * - logs the given message in CI logs + * - prints the given message to standard output + * Otherwise terminate with the generic error + */ +function terminateWithError($message = null) +{ + if (!isEmptyString($message)) + { + $ci =& get_instance(); // get CI instance + $ci->load->library('LogLib'); // Loads LogLib + + $ci->loglib->logError($message); + + exit($message); + } + + exit(EXIT_ERROR); +} + /** * Checks if the current user is logged by checking that the AuthLib is loaded and * it is present the authentication object in session diff --git a/application/helpers/hlp_sancho_helper.php b/application/helpers/hlp_sancho_helper.php index 6f5ef8c24..5d2d9f1f1 100644 --- a/application/helpers/hlp_sancho_helper.php +++ b/application/helpers/hlp_sancho_helper.php @@ -98,9 +98,7 @@ function _parseMailContent($vorlage_kurzbz, $vorlage_data) !isEmptyString($result->retval[0]->text)) { // Parses template text - $parsedText = $ci->vorlagelib->parseVorlagetext($result->retval[0]->text, $vorlage_data); - - return $parsedText; + return parseText($result->retval[0]->text, $vorlage_data); } } } diff --git a/application/libraries/MailLib.php b/application/libraries/MailLib.php index 6d0a48f73..dbbc22f08 100644 --- a/application/libraries/MailLib.php +++ b/application/libraries/MailLib.php @@ -7,6 +7,8 @@ if (! defined('BASEPATH')) exit('No direct script access allowed'); */ class MailLib { + const ENABLE_DEBUG = 'enable_debug'; + private $sended; // Sended email counter // Properties for storing the configuration @@ -15,6 +17,8 @@ class MailLib private $email_time_range; private $email_from_system; + private $_ci; // Codeigniter instance + /** * Class constructor */ @@ -24,16 +28,16 @@ class MailLib $this->sended = 0; // Get CI instance - $this->ci =& get_instance(); + $this->_ci =& get_instance(); // The second parameter is used to avoiding name collisions in the config array - $this->ci->config->load('mail', true); + $this->_ci->config->load('mail', true); // CI Email library - $this->ci->load->library('email'); + $this->_ci->load->library('email'); // Initializing email library with the loaded configurations - $this->ci->email->initialize($this->ci->config->config['mail']); + $this->_ci->email->initialize($this->_ci->config->config['mail']); // Set the configuration properties with the standard configuration values $this->email_number_to_sent = $this->getEmailCfgItem('email_number_to_sent'); @@ -48,6 +52,22 @@ class MailLib */ public function send($from, $to, $subject, $message, $alias = '', $cc = null, $bcc = null, $altMessage = '', $bulk = false, $autogenerated = false) { + // If it is configured then log mail info into the CI error logs + if ($this->getEmailCfgItem(self::ENABLE_DEBUG) === true) + { + $this->_ci->load->library('LogLib'); // Loads logging library + + // Log them all! + $this->_ci->loglib->logError('From: '.$from); + $this->_ci->loglib->logError('To: '.$to); + $this->_ci->loglib->logError('Subject: '.$subject); + $this->_ci->loglib->logError('Message: '.$message); + $this->_ci->loglib->logError('Alias: '.$alias); + $this->_ci->loglib->logError('CC: '.$cc); + $this->_ci->loglib->logError('BCC: '.$bcc); + $this->_ci->loglib->logError('Alternative message: '.$altMessage); + } + // If from is not specified then use the standard one if (is_null($from) || $from == '') { @@ -67,7 +87,7 @@ class MailLib } } - $this->ci->email->from($from, $alias); + $this->_ci->email->from($from, $alias); // Check if the email address of the debug recipient is a valid one $recipient = $to; @@ -83,20 +103,20 @@ class MailLib $recipientBCC = MAIL_DEBUG; } - $this->ci->email->to($recipient); - if (!is_null($recipientCC)) $this->ci->email->cc($recipientCC); - if (!is_null($recipientBCC)) $this->ci->email->bcc($recipientBCC); - $this->ci->email->subject($subject); - $this->ci->email->message($message); - if (!isEmptyString($altMessage)) $this->ci->email->set_alt_message($altMessage); + $this->_ci->email->to($recipient); + if (!is_null($recipientCC)) $this->_ci->email->cc($recipientCC); + if (!is_null($recipientBCC)) $this->_ci->email->bcc($recipientBCC); + $this->_ci->email->subject($subject); + $this->_ci->email->message($message); + if (!isEmptyString($altMessage)) $this->_ci->email->set_alt_message($altMessage); if($bulk) - $this->ci->email->set_header('Precedence', 'bulk'); + $this->_ci->email->set_header('Precedence', 'bulk'); if($autogenerated) - $this->ci->email->set_header('Auto-Submitted', 'auto-generated'); + $this->_ci->email->set_header('Auto-Submitted', 'auto-generated'); // Avoid printing on standard output ugly error messages - $result = @$this->ci->email->send(); + $result = @$this->_ci->email->send(); // If the email was succesfully sended then increment the counter // and checks if it has to wait until the sending of the next @@ -110,43 +130,34 @@ class MailLib } /** - * To ovveride the configurations + * Overrides configuration parameters + * If the given parameters are not null or empty strings then they are used to override + * the following properties of this object: + * - email_number_to_sent + * - email_number_per_time_range + * - email_time_range + * - email_from_system */ - public function overrideConfigs($cfg) + public function overrideConfigs($numberToSent, $numberPerTimeRange, $emailTimeRange, $emailFromSystem) { - if (!is_null($cfg)) + if (is_numeric($numberToSent)) $this->email_number_to_sent = $numberToSent; + + if (is_numeric($numberPerTimeRange)) $this->email_number_per_time_range = $numberPerTimeRange; + + if (is_numeric($emailTimeRange)) $this->email_time_range = $emailTimeRange; + + if (!isEmptyString($emailFromSystem) && filter_var($emailFromSystem, FILTER_VALIDATE_EMAIL)) { - if (isset($cfg->email_number_to_sent) && is_numeric($cfg->email_number_to_sent)) - { - $this->email_number_to_sent = $cfg->email_number_to_sent; - } - if (isset($cfg->email_number_per_time_range) && is_numeric($cfg->email_number_per_time_range)) - { - $this->email_number_per_time_range = $cfg->email_number_per_time_range; - } - if (isset($cfg->email_time_range) && is_numeric($cfg->email_time_range)) - { - $this->email_time_range = $cfg->email_time_range; - } - if (isset($cfg->email_from_system) && filter_var($cfg->email_from_system, FILTER_VALIDATE_EMAIL)) - { - $this->email_from_system = $cfg->email_from_system; - } + $this->email_from_system = $emailFromSystem; } } /** - * Returns the current configuration + * Returns value of property email_number_to_sent */ - public function getConfigs() + public function getEmailNumberToSent() { - $cfg = new stdClass(); - $cfg->email_number_to_sent = $this->email_number_to_sent; - $cfg->email_number_per_time_range = $this->email_number_per_time_range; - $cfg->email_time_range = $this->email_time_range; - $cfg->email_from_system = $this->email_from_system; - - return $cfg; + return $this->email_number_to_sent; } /** @@ -180,6 +191,6 @@ class MailLib */ private function getEmailCfgItem($itemName) { - return $this->ci->config->item($itemName, EMAIL_CONFIG_INDEX); + return $this->_ci->config->item($itemName, EMAIL_CONFIG_INDEX); } } diff --git a/application/libraries/MessageLib.php b/application/libraries/MessageLib.php index feba96473..b97ef4bae 100644 --- a/application/libraries/MessageLib.php +++ b/application/libraries/MessageLib.php @@ -7,7 +7,24 @@ if (! defined('BASEPATH')) exit('No direct script access allowed'); */ class MessageLib { - const MSG_INDX_PREFIX = 'message_'; + // Config entries + const CFG_SYSTEM_PERSON_ID = 'system_person_id'; + const CFG_SEND_IMMEDIATELY = 'send_immediately'; + const CFG_MESSAGE_SERVER = 'message_server'; + const CFG_MESSAGE_HTML_VIEW_URL = 'message_html_view_url'; + const CFG_OU_RECEIVERS = 'ou_receivers'; + const CFG_OU_RECEIVERS_NO_NOTICE = 'ou_receivers_no_notice'; + const CFG_OU_RECEIVERS_PRIVATE = 'ou_receivers_private'; + const CFG_REDIRECT_VIEW_MESSAGE_URL = 'redirect_view_message_url'; + + // Templates names + const NOTICE_TEMPLATE_HTML = 'MessageMailHTML'; + const NOTICE_TEMPLATE_TXT = 'MessageMailTXT'; + const NOTICE_TEMPLATE_FALLBACK_HTML = 'templates/mailHTML'; + const NOTICE_TEMPLATE_FALLBACK_TXT = 'templates/mailTXT'; + + const EMAIL_KONTAKT_TYPE = 'email'; // Email kontakt type + const SENT_INFO_NEWLINE = '\n'; // tbl_msg_recipient->sentInfo separator private $_ci; @@ -22,16 +39,12 @@ class MessageLib // Loads message configuration $this->_ci->config->load('message'); - // CI Parser library - $this->_ci->load->library('parser'); - // Loads LogLib - $this->_ci->load->library('LogLib'); // Loads VorlageLib $this->_ci->load->library('VorlageLib'); // Loads Mail library $this->_ci->load->library('MailLib'); - // Loading models + // Loads message models $this->_ci->load->model('system/Message_model', 'MessageModel'); $this->_ci->load->model('system/MsgStatus_model', 'MsgStatusModel'); $this->_ci->load->model('system/Recipient_model', 'RecipientModel'); @@ -42,134 +55,298 @@ class MessageLib // Public methods /** - * getMessage() - returns the specified received message for a specified person + * Returns the specified message for a specified person */ public function getMessage($msg_id, $person_id) { - if (!is_numeric($msg_id)) - return $this->_error('', MSG_ERR_INVALID_MSG_ID); - if (!is_numeric($person_id)) - return $this->_error('', MSG_ERR_INVALID_RECIPIENTS); + if (!is_numeric($msg_id)) return error('The given message id is not valid', MSG_ERR_INVALID_MSG_ID); + if (!is_numeric($person_id)) return error('The given person id is not valid', MSG_ERR_INVALID_RECIPIENTS); return $this->_ci->RecipientModel->getMessage($msg_id, $person_id); } /** - * getMessagesByUID() - will return all messages, including the latest status for specified user. It don´t returns Attachments. + * Sends a message to persons ($receiversPersonId) */ - public function getMessagesByUID($uid, $oe_kurzbz = null, $all = false) + public function sendMessageUser( + $receiversPersonId, $subject, $body, // Required parameters + $sender_id = null, $senderOU = null, $relationmessage_id = null, $priority = MSG_PRIORITY_NORMAL, $multiPartMime = true + ) { - if (isEmptyString($uid)) - return $this->_error('', MSG_ERR_INVALID_MSG_ID); + // Retrieves receiver id and checks that is valid + $receivers = $this->_getReceiversByPersonId($receiversPersonId); + if (isError($receivers)) return $receivers; - return $this->_ci->RecipientModel->getMessagesByUID($uid, $oe_kurzbz, $all); + // Send the message and return the result + return $this->_sendMessage($receivers, null, $subject, $body, $sender_id, $senderOU, $relationmessage_id, $priority, $multiPartMime); } /** - * getMessagesByPerson() - will return all messages, including the latest status for specified user. It don´t returns Attachments. + * Sends a message to persons ($receiversPersonId) */ - public function getMessagesByPerson($person_id, $oe_kurzbz = null, $all = false) + public function sendMessageUserTemplate( + $receiversPersonId, $vorlage, $parseData, // Required parameters + $orgform = null, $sender_id = null, $senderOU = null, $relationmessage_id = null, $priority = MSG_PRIORITY_NORMAL, $multiPartMime = true + ) { - if (!is_numeric($person_id)) - return $this->_error('', MSG_ERR_INVALID_MSG_ID); + // Loads template data + $templateResult = $this->_ci->vorlagelib->loadVorlagetext($vorlage, $senderOU, $orgform, getUserLanguage()); + if (hasData($templateResult)) // if a template is found + { + $template = getData($templateResult)[0]; // template object - return $this->_ci->RecipientModel->getMessagesByPerson($person_id, $oe_kurzbz, $all); + // Parses template subject + $subject = parseText($template->subject, $parseData); + // Parses template text + $body = parseText($template->text, $parseData); + + return $this->sendMessageUser( + $receiversPersonId, $subject, $body, $sender_id, $senderOU, $relationmessage_id, $priority, $multiPartMime + ); + } + elseif (isError($templateResult)) // if an error occured + { + return $templateResult; // return it + } + else // if a template was not found + { + return error('Template was not found', MSG_ERR_INVALID_TEMPLATE); + } } /** - * getSentMessagesByPerson() - Get all sent messages from a person identified by person_id + * Sends a message to all the persons that are enabled to read messages for the given organisation unit ($receiversOU) */ - public function getSentMessagesByPerson($person_id, $oe_kurzbz = null, $all = false) + public function sendMessageOU( + $receiversOU, $subject, $body, // Required parameters + $sender_id = null, $senderOU = null, $relationmessage_id = null, $priority = MSG_PRIORITY_NORMAL, $multiPartMime = true + ) { - if (!is_numeric($person_id)) - return $this->_error('', MSG_ERR_INVALID_MSG_ID); + // If the recipient is an organisation unit that would be possible to send the same message (same message id) + // to the entire organisation unit (one to many functionality) + // In this case the receiver id is a the one present in message configuration + $receiver = new stdClass(); + $receiver->person_id = $this->_ci->config->item(self::CFG_SYSTEM_PERSON_ID); + $receivers = success(array($receiver)); - return $this->_ci->MessageModel->getMessagesByPerson($person_id, $oe_kurzbz, $all); + // Send the message and return the result + return $this->_sendMessage($receivers, $receiversOU, $subject, $body, $sender_id, $senderOU, $relationmessage_id, $priority, $multiPartMime); + } + + //------------------------------------------------------------------------------------------------------------------ + // Public methods called by a job + + /** + * Gets all messages for which notice emails are still not sent from DB and sends for each of them the notice email + * Wrapper for _sendNoticeEmail. + */ + public function sendAllEmailNotices($since, $numberToSent, $numberPerTimeRange, $emailTimeRange, $emailFromSystem) + { + // Overrides MailLib configs with the given parameters + $this->_ci->maillib->overrideConfigs($numberToSent, $numberPerTimeRange, $emailTimeRange, $emailFromSystem); + + // Retrieves a certain amount of NOT sent messages + $messagesResult = $this->_ci->RecipientModel->getNotSentMessages( + $this->_ci->maillib->getEmailNumberToSent(), + $since + ); + + if (isError($messagesResult) || !hasData($messagesResult)) return $messagesResult; + + // Collects all the message ids in an array + $messageIds = array(); + foreach (getData($messagesResult) as $message) + { + $messageIds[] = $message->message_id; + } + + // Send'em all + return $this->_sendNoticeEmails($messageIds); + } + + //------------------------------------------------------------------------------------------------------------------ + // Public methods used by to build the GUI to write messages to user/s + + /** + * Retrieves message vars from view vw_msg_vars_person + */ + public function getMessageVarsPerson() + { + // Retrieves message vars from view vw_msg_vars_person + $messageVarsPerson = $this->_ci->MessageModel->getMessageVarsPerson(); + if (isSuccess($messageVarsPerson)) // if everything is ok + { + $variablesArray = array(); + $tmpVariablesArray = getData($messageVarsPerson); + + // Starts from 1 to skip the first element which is person_id + for ($i = 1; $i < count($tmpVariablesArray); $i++) + { + $variablesArray['{'.str_replace(' ', '_', strtolower($tmpVariablesArray[$i])).'}'] = $tmpVariablesArray[$i]; + } + + return success($variablesArray); + } + + return $messageVarsPerson; // otherwise returns the error } /** - * getMessageByToken + * Retrieves message vars from view vw_msg_vars + */ + public function getMessageVarsPrestudent() + { + // Retrieves message vars from view vw_msg_vars + $messageVars = $this->_ci->MessageModel->getMessageVars(); + if (isSuccess($messageVars)) // if everything is ok + { + $variablesArray = array(); + $tmpVariablesArray = getData($messageVars); + + // Starts from 1 to skip the first element which is person_id + for ($i = 1; $i < count($tmpVariablesArray); $i++) + { + $variablesArray['{'.str_replace(' ', '_', strtolower($tmpVariablesArray[$i])).'}'] = $tmpVariablesArray[$i]; + } + + return success($variablesArray); + } + + return $messageVars; // otherwise returns the error + } + + /** + * Retrieves organisation units for each role that a user plays inside that organisation unit + */ + public function getOeKurzbz($sender_id) + { + $this->_ci->load->model('person/Benutzerfunktion_model', 'BenutzerfunktionModel'); + + // Retrieves organisation units for a user from database + $benutzer = $this->_ci->BenutzerfunktionModel->getActiveFunctionsByPersonId($sender_id); + if (isSuccess($benutzer)) // if everything is ok + { + $ouArray = array(); + + // Copies organisation units in $ouArray array + foreach (getData($benutzer) as $val) $ouArray[] = $val->oe_kurzbz; + + return success($ouArray); + } + + return $benutzer; // otherwise returns the error + } + + //------------------------------------------------------------------------------------------------------------------ + // Public methods used by REST API + + /** + * Return all messages, including the latest status for specified user. It don´t returns Attachments. + * The sender organisation unit may be specified to filter messages + */ + public function getMessagesByUID($uid, $senderOU = null, $all = false) + { + if (isEmptyString($uid)) return error('The given message id is not valid', MSG_ERR_INVALID_MSG_ID); + + return $this->_ci->RecipientModel->getMessagesByUID($uid, $senderOU, $all); + } + + /** + * Return all messages, including the latest status for specified user. It does not return attachments + * The sender organisation unit may be specified to filter messages + */ + public function getMessagesByPerson($person_id, $senderOU = null, $all = false) + { + if (!is_numeric($person_id)) return error('The given message id is not valid', MSG_ERR_INVALID_MSG_ID); + + return $this->_ci->RecipientModel->getMessagesByPerson($person_id, $senderOU, $all); + } + + /** + * Get all sent messages from a person identified by person_id + * The sender organisation unit may be specified to filter messages + */ + public function getSentMessagesByPerson($person_id, $senderOU = null, $all = false) + { + if (!is_numeric($person_id)) return error('The given message id is not valid', MSG_ERR_INVALID_MSG_ID); + + return $this->_ci->MessageModel->getMessagesByPerson($person_id, $senderOU, $all); + } + + /** + * Retrieves a message by its token + * If a message is found with the given token then this message is set as read */ public function getMessageByToken($token) { - if (isEmptyString($token)) - return $this->_error('', MSG_ERR_INVALID_TOKEN); + if (isEmptyString($token)) return error('The given token is not valid', MSG_ERR_INVALID_TOKEN); - $result = $this->_ci->RecipientModel->getMessageByToken($token); - if (hasData($result)) + $messageTokenResult = $this->_ci->RecipientModel->getMessageByToken($token); + if (hasData($messageTokenResult)) { - // Searches for a status that is different from unread - $found = -1; - for ($i = 0; $i < count($result->retval); $i++) + // Searches for a status that is NOT unread + $found = false; + + foreach (getData($messageTokenResult) as $message) { - if ($result->retval[$i]->status > MSG_STATUS_UNREAD) + if ($message->status > MSG_STATUS_UNREAD) { - $found = $i; + $found = true; break; } } - // If not found then insert the read status - if ($found == -1) + // If NOT found then insert the read status + if (!$found) { - $statusKey = array( - 'message_id' => $result->retval[0]->message_id, - 'person_id' => $result->retval[0]->receiver_id, - 'status' => MSG_STATUS_READ + $uid = null; + if (!isEmptyString($messageTokenResult[0]->uid)) + { + $uid = $messageTokenResult[0]->uid; + } + + $statusData = array( + 'message_id' => getData($messageTokenResult)[0]->message_id, + 'person_id' => getData($messageTokenResult)[0]->receiver_id, + 'status' => MSG_STATUS_READ, + 'insertvon' => $uid ); - $resultIns = $this->_ci->MsgStatusModel->insert($statusKey); + $messageTokenResultIns = $this->_ci->MsgStatusModel->insert($statusData); // If an error occured while writing on data base, then return it - if (isError($resultIns)) - { - $result = $resultIns; - } + if (isError($messageTokenResultIns)) $messageTokenResult = $messageTokenResultIns; } } - return $result; + return $messageTokenResult; } /** - * getCountUnreadMessages + * Counts the unread messages for the given user + * The sender organisation unit may be specified to filter messages */ - public function getCountUnreadMessages($person_id, $oe_kurzbz = null) + public function getCountUnreadMessages($person_id, $senderOU = null) { - if (!is_numeric($person_id)) - return $this->_error('', MSG_ERR_INVALID_RECIPIENTS); + if (!is_numeric($person_id)) return error('The given person id is not valid', MSG_ERR_INVALID_RECIPIENTS); - return $this->_ci->RecipientModel->getCountUnreadMessages($person_id, $oe_kurzbz); + return $this->_ci->RecipientModel->getCountUnreadMessages($person_id, $senderOU); } /** - * updateMessageStatus() - will change status on message for particular user - * NOTE: it performs an insert, NOT an update + * Change the message status of the given message specified by message_id and person_id, using the given status + * NOTE: it performs an insert NOT an update */ public function updateMessageStatus($message_id, $person_id, $status) { - if (!is_numeric($message_id)) - { - return $this->_error('', MSG_ERR_INVALID_MSG_ID); - } + if (!is_numeric($message_id)) return error('The given message id is not valid', MSG_ERR_INVALID_MSG_ID); + if (!is_numeric($person_id)) return error('The given person id is not valid', MSG_ERR_INVALID_RECIPIENTS); + if (!is_numeric($status)) return error('The given status is not valid', MSG_ERR_INVALID_STATUS_ID); - if (!is_numeric($person_id)) - { - return $this->_error('', MSG_ERR_INVALID_USER_ID); - } - - // NOTE: Not use empty otherwise if status is 0 it returns an error - if (!isset($status)) - { - return $this->_error('', MSG_ERR_INVALID_STATUS_ID); - } + $this->_ci->MsgStatusModel->resetQuery(); // Reset an eventually already buit query // Searches if the status is already present - $result = $this->_ci->MsgStatusModel->load(array($message_id, $person_id, $status)); - if (hasData($result)) - { - // status already present - } - else + $updMessageStatusResult = $this->_ci->MsgStatusModel->load(array($message_id, $person_id, $status)); + if (!hasData($updMessageStatusResult)) // if not found { // Insert the new status $statusKey = array( @@ -177,820 +354,555 @@ class MessageLib 'person_id' => $person_id, 'status' => $status ); - - $result = $this->_ci->MsgStatusModel->insert($statusKey); + $updMessageStatusResult = $this->_ci->MsgStatusModel->insert($statusKey); } - return $result; - } - - /** - * sendMessage() - sends new internal message. This function will create a new thread - */ - public function sendMessage($sender_id, $receiver_id, $subject, $body, $priority = PRIORITY_NORMAL, $relationmessage_id = null, $oe_kurzbz = null, $multiPartMime = true) - { - if (!is_numeric($sender_id)) - { - $sender_id = $this->_ci->config->item('system_person_id'); - } - - $receivers = $this->_getReceivers($receiver_id, $oe_kurzbz); - - // If everything went ok - if (isSuccess($receivers) && is_array($receivers->retval)) - { - // If no receivers were found for this organization unit - if (count($receivers->retval) == 0) - { - $result = $this->_error($receivers->retval, MSG_ERR_OU_CONTACTS_NOT_FOUND); - } - - // Looping on receivers - for ($i = 0; $i < count($receivers->retval); $i++) - { - $receiver_id = $receivers->retval[$i]->person_id; - - // Checks if the receiver exists - if ($this->_checkReceiverId($receiver_id)) - { - // If the text and the subject of the template are not empty - if (!isEmptyString($subject) && !isEmptyString($body)) - { - $result = $this->_saveMessage($sender_id, $receiver_id, $subject, $body, $relationmessage_id, $oe_kurzbz); - // If no errors were occurred - // Leave the code commented - if (isSuccess($result)) - { - // If the system is configured to send messages immediately - if ($this->_ci->config->item('send_immediately') === true) - { - // Send message by email! - $resultSendEmail = $this->sendOne($result->retval, $subject, $body, $multiPartMime); - } - } - } - else - { - if (isEmptyString($subject)) - { - $result = $this->_error('', MSG_ERR_SUBJECT_EMPTY); - break; - } - elseif (isEmptyString($body)) - { - $result = $this->_error('', MSG_ERR_BODY_EMPTY); - break; - } - } - } - else - { - $result = $this->_error('', MSG_ERR_INVALID_RECEIVER_ID); - break; - } - } - } - // If there was some errors then copy them into the returning variable - else - { - $result = $receivers; - } - - return $result; - } - - /** - * Sends new internal message using a template - */ - public function sendMessageVorlage($sender_id, $receiver_id, $vorlage_kurzbz, $oe_kurzbz, $data, $relationmessage_id = null, $orgform_kurzbz = null, $multiPartMime = true) - { - if (!is_numeric($sender_id)) - { - $sender_id = $this->_ci->config->item('system_person_id'); - } - - $receivers = $this->_getReceivers($receiver_id, $oe_kurzbz); - - // If everything went ok - if (isSuccess($receivers) && is_array($receivers->retval)) - { - // If no receivers were found for this organization unit - if (count($receivers->retval) == 0) - { - $result = $this->_error($receivers->retval, MSG_ERR_OU_CONTACTS_NOT_FOUND); - } - else - { - // Load reveiver data to get its relative language - $this->_ci->load->model('person/Person_model', 'PersonModel'); - } - - // Looping on receivers - for ($i = 0; $i < count($receivers->retval); $i++) - { - $receiver_id = $receivers->retval[$i]->person_id; - - // Checks if the receiver exists - $result = $this->_ci->PersonModel->load($receiver_id); - if (hasData($result)) - { - // Retrieves the language of the logged user - $sprache = getUserLanguage(); - - // Loads template data - $result = $this->_ci->vorlagelib->loadVorlagetext($vorlage_kurzbz, $oe_kurzbz, $orgform_kurzbz, $sprache); - if (isSuccess($result)) - { - // If the text and the subject of the template are not empty - if (is_array($result->retval) && count($result->retval) > 0 && - !isEmptyString($result->retval[0]->text) && !isEmptyString($result->retval[0]->subject)) - { - // Parses template text - $parsedText = $this->_ci->vorlagelib->parseVorlagetext($result->retval[0]->text, $data); - // Parses subject - $subject = $this->_ci->vorlagelib->parseVorlagetext($result->retval[0]->subject, $data); - - // Save message - $result = $this->_saveMessage($sender_id, $receiver_id, $subject, $parsedText, $relationmessage_id, $oe_kurzbz); - // If no errors were occurred - if (isSuccess($result)) - { - // If the system is configured to send messages immediately - if ($this->_ci->config->item('send_immediately') === true) - { - // Send message by email! - $resultSendEmail = $this->sendOne($result->retval, $subject, $parsedText, $multiPartMime); - } - } - } - else - { - // Better message error - if (!is_array($result->retval) || (is_array($result->retval) && count($result->retval) == 0)) - { - $result = $this->_error('', MSG_ERR_TEMPLATE_NOT_FOUND); - break; - } - elseif (is_array($result->retval) && count($result->retval) > 0) - { - if (is_null($result->retval[0]->oe_kurzbz)) - { - $result = $this->_error('', MSG_ERR_TEMPLATE_NOT_FOUND); - break; - } - elseif (isEmptyString($result->retval[0]->text)) - { - $result = $this->_error('', MSG_ERR_INVALID_TEMPLATE); - break; - } - elseif (isEmptyString($result->retval[0]->subject)) - { - $result = $this->_error('', MSG_ERR_INVALID_TEMPLATE); - break; - } - } - } - } - else - { - $result = $this->_error($result->retval, EXIT_ERROR); - break; - } - } - else - { - $result = $this->_error('', MSG_ERR_INVALID_RECEIVER_ID); - break; - } - } - } - // If there was some errors then copy them into the returning variable - else - { - $result = $receivers; - } - - return $result; - } - - /** - * Gets all the messages from DB and sends them via email - */ - public function sendAll($numberToSent = null, $numberPerTimeRange = null, $email_time_range = null, $email_from_system = null) - { - $sent = true; // optimistic expectation - - // Gets standard configs - $cfg = $this->_ci->maillib->getConfigs(); - $cfg->email_number_to_sent = $numberToSent; - $cfg->email_number_per_time_range = $numberPerTimeRange; - $cfg->email_time_range = $email_time_range; - $cfg->email_from_system = $email_from_system; - - // Overrides configs with the parameters - $this->_ci->maillib->overrideConfigs($cfg); - - // Gets a number ($this->_ci->maillib->getMaxEmailToSent()) of unsent messages from DB - // having EMAIL_KONTAKT_TYPE as relative contact type - $result = $this->_ci->RecipientModel->getMessages( - EMAIL_KONTAKT_TYPE, - null, - $this->_ci->maillib->getConfigs()->email_number_to_sent - ); - // Checks if errors were occurred - if (isSuccess($result)) - { - // If data are present - if (is_array($result->retval) && count($result->retval) > 0) - { - // Iterating through the result set, if no errors occurred in the previous iteration - for ($i = 0; $i < count($result->retval) && $sent; $i++) - { - // If the person has an email account - if ((!is_null($result->retval[$i]->receiver) && $result->retval[$i]->receiver != '') - || (!is_null($result->retval[$i]->employeecontact) && $result->retval[$i]->employeecontact != '')) - { - $href = $this->_ci->config->item('message_server').$this->_ci->config->item('message_html_view_url').$result->retval[$i]->token; - - $vorlage = $this->_ci->vorlagelib->loadVorlagetext('MessageMailHTML'); - - if(hasData($vorlage)) - { - // Using a template for the html email body - $body = $this->_ci->parser->parse_string( - $vorlage->retval[0]->text, - array( - 'href' => $href, - 'subject' => $result->retval[$i]->subject, - 'body' => $result->retval[$i]->body - ), - true - ); - } - else - { - // Using a template for the html email body - $body = $this->_ci->parser->parse( - 'templates/mailHTML', - array( - 'href' => $href, - 'subject' => $result->retval[$i]->subject, - 'body' => $result->retval[$i]->body - ), - true - ); - } - if (is_null($body) || $body == '') - { - $this->_ci->loglib->logError('Error while parsing the mail template'); - } - - $vorlage = $this->_ci->vorlagelib->loadVorlagetext('MessageMailTXT'); - if(hasData($vorlage)) - { - // Using a template for the plain text email body - $altBody = $this->_ci->parser->parse_string( - $vorlage->retval[0]->text, - array( - 'href' => $href, - 'subject' => $result->retval[$i]->subject, - 'body' => $result->retval[$i]->body - ), - true - ); - } - else - { - // Using a template for the plain text email body - $altBody = $this->_ci->parser->parse( - 'templates/mailTXT', - array( - 'href' => $href, - 'subject' => $result->retval[$i]->subject, - 'body' => $result->retval[$i]->body - ), - true - ); - } - if (is_null($altBody) || $altBody == '') - { - $this->_ci->loglib->logError('Error while parsing the mail template'); - } - - // If the sender is not an employee, then system-sender is used if empty - $sender = ''; - if (!is_null($result->retval[0]->senderemployeecontact) && $result->retval[0]->senderemployeecontact != '') - { - $sender = $result->retval[0]->senderemployeecontact.'@'.DOMAIN; - } - - $receiverContact = $result->retval[$i]->receiver; - if (!is_null($result->retval[$i]->employeecontact) && $result->retval[$i]->employeecontact != '') - { - $receiverContact = $result->retval[$i]->employeecontact.'@'.DOMAIN; - } - - // Sending email - $sent = $this->_ci->maillib->send( - $sender, - $receiverContact, - $result->retval[$i]->subject, - $body, - null, - null, - null, - $altBody - ); - // If errors were occurred while sending the email - if (!$sent) - { - $this->_ci->loglib->logError('Error while sending an email'); - // Writing errors in tbl_msg_recipient - $sme = $this->setMessageError( - $result->retval[$i]->message_id, - $result->retval[$i]->receiver_id, - 'Error while sending an email', - $result->retval[$i]->sentinfo - ); - if (!$sme) - { - $this->_ci->loglib->logError('Error while updating DB'); - } - } - else - { - // Setting the message as sent in DB - $sent = $this->setMessageSent($result->retval[$i]->message_id, $result->retval[$i]->receiver_id); - // If some errors occurred - if (!$sent) - { - $this->_ci->loglib->logError('Error while updating DB'); - } - } - } - else - { - $this->_ci->loglib->logError('This person does not have an email account'); - // Writing errors in tbl_msg_recipient - $sme = $this->setMessageError( - $result->retval[$i]->message_id, - $result->retval[$i]->receiver_id, - 'This person does not have an email account', - $result->retval[$i]->sentinfo - ); - if (!$sme) - { - $this->_ci->loglib->logError('Error while updating DB'); - } - $sent = true; // Non blocking error - } - } - } - else - { - $this->_ci->loglib->logInfo('There are no email to be sent'); - $sent = false; - } - } - else - { - $this->_ci->loglib->logError('Something went wrong while getting data from DB'); - $sent = false; - } - - return $sent; - } - - /** - * Gets one message from DB and sends it via email - */ - public function sendOne($message_id, $subject = null, $body = null, $multiPartMime = true) - { - $sent = true; // optimistic expectation - - // Get a specific message from DB having EMAIL_KONTAKT_TYPE as relative contact type - $result = $this->_ci->RecipientModel->getMessages( - EMAIL_KONTAKT_TYPE, - null, - null, - $message_id - ); - - // Checks if errors were occurred - if (isSuccess($result)) - { - // If data are present - if (is_array($result->retval) && count($result->retval) > 0) - { - // If the person has an email account - if ((!is_null($result->retval[0]->receiver) && $result->retval[0]->receiver != '') - || (!is_null($result->retval[0]->employeecontact) && $result->retval[0]->employeecontact != '')) - { - // If it is required use a multi-part message in MIME format - if ($multiPartMime === true) - { - // Using a template for the html email body - $href = $this->_ci->config->item('message_server').$this->_ci->config->item('message_html_view_url').$result->retval[0]->token; - - $vorlage = $this->_ci->vorlagelib->loadVorlagetext('MessageMailHTML'); - if(hasData($vorlage)) - { - $bodyMsg = $this->_ci->parser->parse_string( - $vorlage->retval[0]->text, - array( - 'href' => $href, - 'subject' => $result->retval[0]->subject, - 'body' => $result->retval[0]->body - ), - true - ); - } - else - { - $bodyMsg = $this->_ci->parser->parse( - 'templates/mailHTML', - array( - 'href' => $href, - 'subject' => $result->retval[0]->subject, - 'body' => $result->retval[0]->body - ), - true - ); - } - if (is_null($bodyMsg) || $bodyMsg == '') - { - // $body = $result->retval[0]->body; - $this->_ci->loglib->logError('Error while parsing the html mail template'); - } - - // Using a template for the plain text email body - $vorlage = $this->_ci->vorlagelib->loadVorlagetext('MessageMailTXT'); - if(hasData($vorlage)) - { - $altBody = $this->_ci->parser->parse_string( - $vorlage->retval[0]->text, - array( - 'href' => $href, - 'subject' => $result->retval[0]->subject, - 'body' => $result->retval[0]->body - ), - true - ); - } - else - { - $altBody = $this->_ci->parser->parse( - 'templates/mailTXT', - array( - 'href' => $href, - 'subject' => $result->retval[0]->subject, - 'body' => $result->retval[0]->body - ), - true - ); - } - if (is_null($altBody) || $altBody == '') - { - $this->_ci->loglib->logError('Error while parsing the plain text mail template'); - } - } - else - { - $bodyMsg = $altBody = $body; - } - - // If the sender is not an employee, then system-sender is used if empty - $sender = ''; - if (!is_null($result->retval[0]->senderemployeecontact) && $result->retval[0]->senderemployeecontact != '') - { - $sender = $result->retval[0]->senderemployeecontact.'@'.DOMAIN; - } - - $receiverContact = $result->retval[0]->receiver; - if (!is_null($result->retval[0]->employeecontact) && $result->retval[0]->employeecontact != '') - { - $receiverContact = $result->retval[0]->employeecontact.'@'.DOMAIN; - } - - // Sending email - $sent = $this->_ci->maillib->send( - null, - $receiverContact, - is_null($subject) ? $result->retval[0]->subject : $subject, // if parameter subject is not null, use it! - $bodyMsg, - null, - null, - null, - $altBody - ); - // If errors were occurred while sending the email - if (!$sent) - { - $this->_ci->loglib->logError('Error while sending an email'); - // Writing errors in tbl_msg_recipient - $sme = $this->setMessageError( - $result->retval[0]->message_id, - $result->retval[0]->receiver_id, - 'Error while sending an email', - $result->retval[0]->sentinfo - ); - if (!$sme) - { - $this->_ci->loglib->logError('Error while updating DB'); - } - } - else - { - // Setting the message as sent in DB - $sent = $this->setMessageSent($result->retval[0]->message_id, $result->retval[0]->receiver_id); - // If the email has been sent and the DB updated - if (!$sent) - { - $this->_ci->loglib->logError('Error while updating DB'); - } - } - } - else - { - $this->_ci->loglib->logError('This person does not have an email account'); - // Writing errors in tbl_msg_recipient - $sme = $this->setMessageError( - $result->retval[0]->message_id, - $result->retval[0]->receiver_id, - 'This person does not have an email account', - $result->retval[0]->sentinfo - ); - if (!$sme) - { - $this->_ci->loglib->logError('Error while updating DB'); - } - $sent = true; // Non blocking error - } - } - else - { - $this->_ci->loglib->logInfo('There are no email to be sent'); - $sent = false; - } - } - else - { - $this->_ci->loglib->logError('Something went wrong while getting data from DB'); - $sent = false; - } - - return $sent; - } - - /** - * parseMessageText - */ - public function parseMessageText($text, $data = array()) - { - return $this->_ci->parser->parse_string($text, $data, true); - } - - /** - * Gets data for Person from view vw_msg_vars_person - * @param $person_id - */ - public function getMessageVarsPerson() - { - $variablesArray = array(); - - $variables = $this->_ci->MessageModel->getMessageVarsPerson(); - if (isError($variables)) - { - return $variables; - } - elseif (hasData($variables)) - { - $tmpVariablesArray = getData($variables); - // Skip person_id - for ($i = 1; $i < count($tmpVariablesArray); $i++) - { - $variablesArray['{'.str_replace(' ', '_', strtolower($tmpVariablesArray[$i])).'}'] = $tmpVariablesArray[$i]; - } - } - - return success($variablesArray); - } - - /** - * A person may belongs to more organisation units - */ - public function getOeKurzbz($sender_id) - { - $oe_kurzbz = array(); - - $this->_ci->load->model('person/Benutzerfunktion_model', 'BenutzerfunktionModel'); - - $benutzer = $this->_ci->BenutzerfunktionModel->getByPersonId($sender_id); - if (isError($benutzer)) - { - return $benutzer; - } - elseif (hasData($benutzer)) - { - foreach (getData($benutzer) as $val) - { - $oe_kurzbz[] = $val->oe_kurzbz; - } - } - - return success($oe_kurzbz); - } - - /** - * Admin or commoner? - */ - public function getIsAdmin($sender_id) - { - $this->_ci->load->model('system/Benutzerrolle_model', 'BenutzerrolleModel'); - - return $this->_ci->BenutzerrolleModel->isAdminByPersonId($sender_id); + return $updMessageStatusResult; } //------------------------------------------------------------------------------------------------------------------ // Private methods /** - * Update the table tbl_msg_recipient + * */ - private function _updateMessageRecipient($message_id, $receiver_id, $parameters) + private function _getSender($sender_id) { - $updated = false; - - // Updates table tbl_msg_recipient - $resultUpdate = $this->_ci->RecipientModel->update(array($receiver_id, $message_id), $parameters); - // Checks if errors were occurred - if (isSuccess($resultUpdate) && is_array($resultUpdate->retval)) + // By default the sender is defined in message configuration + $sender = success($this->_ci->config->item(self::CFG_SYSTEM_PERSON_ID)); + if ($sender_id != null) // if it was given as parameter { - $updated = true; - } - - return $updated; - } - - /** - * Changes the status of the message from unsent to sent - */ - private function setMessageSent($message_id, $receiver_id) - { - $parameters = array('sent' => 'NOW()', 'sentinfo' => null); - - return $this->_updateMessageRecipient($message_id, $receiver_id, $parameters); - } - - /** - * Sets the sentInfo with the error - */ - private function setMessageError($message_id, $receiver_id, $sentInfo, $prevSentInfo = null) - { - if (!is_null($prevSentInfo) && $prevSentInfo != '') - { - $sentInfo = $prevSentInfo.SENT_INFO_NEWLINE.$sentInfo; - } - - $parameters = array('sent' => null, 'sentinfo' => $sentInfo); - - return $this->_updateMessageRecipient($message_id, $receiver_id, $parameters); - } - - /** - * Gets the receivers id that are enabled to read messages for that oe_kurzbz - */ - private function _getReceiversByOekurzbz($oe_kurzbz) - { - // Load Benutzerfunktion_model - $this->_ci->load->model('person/Benutzerfunktion_model', 'BenutzerfunktionModel'); - // Join with table public.tbl_benutzer on field uid - $this->_ci->BenutzerfunktionModel->addJoin('public.tbl_benutzer', 'uid'); - // Get all the valid receivers id using the oe_kurzbz - $receivers = $this->_ci->BenutzerfunktionModel->loadWhere( - 'oe_kurzbz = '.$this->_ci->db->escape($oe_kurzbz). - ' AND funktion_kurzbz = '.$this->_ci->db->escape($this->_ci->config->item('assistent_function')). - ' AND (NOW() BETWEEN COALESCE(datum_von, NOW()) AND COALESCE(datum_bis, NOW()))' - ); - - return $receivers; - } - - /** - * Gets the receivers id - */ - private function _getReceivers($receiver_id, $oe_kurzbz = null) - { - $receivers = null; - - // If no receiver_id is given... - if (is_null($receiver_id)) - { - // ...a oe_kurzbz must be specified - if (is_null($oe_kurzbz)) + if (is_numeric($sender_id)) // if it valid -> it is a number { - $receivers = $this->_error('', MSG_ERR_INVALID_OU); + $sender = success($sender_id); // return it as a success object } else { - $receivers = $this->_getReceiversByOekurzbz($oe_kurzbz); + // Otherwise returns an error + $sender = error('The given sender is not valid', MSG_ERR_INVALID_SENDER); } } - // Else if the receiver id is given - else - { - $receivers = $this->_success(array(new stdClass())); - $receivers->retval[0]->person_id = $receiver_id; - } - return $receivers; + return $sender; } /** - * Checks if the given receiver id is a valid person + * Checks if the given receiver ids belong to persons in database */ - private function _checkReceiverId($receiver_id) + private function _getReceiversByPersonId($receiver_id) { - // Load Person_model $this->_ci->load->model('person/Person_model', 'PersonModel'); - $result = $this->_ci->PersonModel->load($receiver_id); - if (hasData($result)) - { - return true; - } - return false; + // Reset an eventually already buit query + $this->_ci->PersonModel->resetQuery(); + + // Get only this columns + $this->_ci->PersonModel->addSelect('person_id'); + + // Loads from database the person by its person_id + $personResult = $this->_ci->PersonModel->load($receiver_id); + if (hasData($personResult)) // if data are retrieved + { + return $personResult; // return them + } + else // otherwise an error occurred (blocking error or data not found) + { + return error('The given person id is not valid', MSG_ERR_INVALID_RECIPIENTS); + } } /** - * Save a message in DB - **/ - private function _saveMessage($sender_id, $receiver_id, $subject, $body, $relationmessage_id, $oe_kurzbz) + * Save a new message in DB + */ + private function _saveMessage($sender_id, $senderOU, $receiver_id, $receiverOU, $subject, $body, $priority, $relationmessage_id) { - // Starts db transaction + // Starts database transaction $this->_ci->db->trans_start(false); - // Save Message - $msgData = array( + $this->_ci->load->model('person/Benutzer_model', 'BenutzerModel'); + + $uid = null; + $benutzerDB = $this->_ci->BenutzerModel->loadWhere(array('person_id' => $sender_id)); + if (hasData($benutzerDB)) + { + $uid = getData($benutzerDB)[0]->uid; + } + + // Store message information in tbl_msg_message + $messageData = array( 'person_id' => $sender_id, 'subject' => $subject, 'body' => $body, - 'priority' => PRIORITY_NORMAL, + 'priority' => $priority, 'relationmessage_id' => $relationmessage_id, - 'oe_kurzbz' => $oe_kurzbz + 'oe_kurzbz' => $senderOU ); - $result = $this->_ci->MessageModel->insert($msgData); - if (isSuccess($result)) + + $saveMessageResult = $this->_ci->MessageModel->insert($messageData); + if (isSuccess($saveMessageResult)) { - // Link the message with the receiver - $msg_id = $result->retval; + $messageId = getData($saveMessageResult); // Gets the message id generated by database + + // Store message information in tbl_msg_recipient $recipientData = array( 'person_id' => $receiver_id, - 'message_id' => $msg_id, - 'token' => generateToken() + 'message_id' => $messageId, + 'token' => generateToken(), + 'oe_kurzbz' => $receiverOU ); - $result = $this->_ci->RecipientModel->insert($recipientData); - if (isSuccess($result)) + + $saveMessageResult = $this->_ci->RecipientModel->insert($recipientData); + if (isSuccess($saveMessageResult)) { - // Save message status + // Store message information in tbl_msg_status $statusData = array( - 'message_id' => $msg_id, + 'message_id' => $messageId, 'person_id' => $receiver_id, - 'status' => MSG_STATUS_UNREAD + 'status' => MSG_STATUS_UNREAD, + 'insertvon' => $uid ); - $result = $this->_ci->MsgStatusModel->insert($statusData); + $saveMessageResult = $this->_ci->MsgStatusModel->insert($statusData); } } - $this->_ci->db->trans_complete(); + $this->_ci->db->trans_complete(); // Ends database transaction - if ($this->_ci->db->trans_status() === false || isError($result)) + // If the transaction failed... + if ($this->_ci->db->trans_status() === false || isError($saveMessageResult)) { - $this->_ci->db->trans_rollback(); - $result = $this->_error('An error occurred while saving a message', EXIT_ERROR); + $this->_ci->db->trans_rollback(); // ...then rollback + } + else // otherwise commit... + { + $this->_ci->db->trans_commit(); + $saveMessageResult = success($messageId); // ...and returns the message id + } + + return $saveMessageResult; + } + + /** + * Set the message as sent successfully by setting columns 'sent' and 'sentinfo' of table tbl_msg_recipient + * sent column is set with date of delivery + * sentinfo is set to null + */ + private function _setSentSuccess($message_id, $receiver_id) + { + return $this->_ci->RecipientModel->update(array($receiver_id, $message_id), array('sent' => 'NOW()', 'sentinfo' => null)); + } + + /** + * Set the message as sent with error by setting columns 'sent' and 'sentinfo' of table tbl_msg_recipient + * Stores the type of error in 'sentinfo' column keeping en eventual previous error + * sent column is set to null + */ + private function _updatedRecipientNoticeEmailInfo($message_id, $receiver_id, $sentInfo, $prevSentInfo) + { + if (!isEmptyString($prevSentInfo)) + { + $sentInfo .= self::SENT_INFO_NEWLINE.$prevSentInfo; + } + + return $this->_ci->RecipientModel->update(array($receiver_id, $message_id), array('sent' => null, 'sentinfo' => $sentInfo)); + } + + /** + * Returns the notice body. Tries to use the template present in database and then falling back + * on the one present in filesystem. If both fail then an error is returned + */ + private function _getNoticeBody($dbEmailNoticeTemplate, $fsEmailNoticeTemplate, $viewMessageLink, $subject, $body) + { + $noticeBody = null; // pessimistic expectation + + if (!isEmptyString($dbEmailNoticeTemplate)) + { + $noticeBody = parseText( + $dbEmailNoticeTemplate, + array( + 'href' => $viewMessageLink, + 'subject' => $subject, + 'body' => $body + ) + ); } else { - $this->_ci->db->trans_commit(); - $result = $this->_success($msg_id); + $noticeBody = parseText( + $fsEmailNoticeTemplate, + array( + 'href' => $viewMessageLink, + 'subject' => $subject, + 'body' => $body + ) + ); } - return $result; + if (isEmptyString($noticeBody)) return error('An error occurred while generating the notice body'); + + return success($noticeBody); } /** - * Wrapper for function error + * Sends notice emails to the recipient of a message */ - private function _error($retval, $code) + private function _sendNoticeEmails($messageIds) { - return error($retval, $code); + // Retrieves the messages information using the given message ids array + $messagesResult = $this->_ci->RecipientModel->getMessagesById($messageIds); + if (isError($messagesResult)) return $messageRecipientResult; // if an error occured then return it + if (!hasData($messagesResult)) return error('No data found with the given message ids'); // if no data found then return an error + + $messages = array(); // all the worked messages will be added here + + // Loops through $messagesResult and stores data about a message in $message + foreach (getData($messagesResult) as $message) + { + // If the recipient organisation unit is in the list of organisation units that do not receive notice emails + if (array_search($message->receiver_ou, $this->_ci->config->item(self::CFG_OU_RECEIVERS_NO_NOTICE))) + { + // Then there is no need to send a notice email to this organisation unit + } + else // otherwise tries to retrieve the right email contact for the message recipient + { + $message->receiverContact = null; // by default set the recipient contact as null + + // If the message was sent to an organisation unit then retrives degree program email + if ($message->receiver_id == $this->_ci->config->item(self::CFG_SYSTEM_PERSON_ID) && !isEmptyString($message->receiver_ou)) + { + $this->_ci->load->model('organisation/Studiengang_model', 'StudiengangModel'); + + $studiengangResult = $this->_ci->StudiengangModel->loadWhere(array('oe_kurzbz' => $message->receiver_ou)); + if (isError($studiengangResult)) return $studiengangResult; // if an error occured then return it + + // Use the degree program email + if (hasData($studiengangResult)) $message->receiverContact = getData($studiengangResult)[0]->email; + } + // If message was sent from FAS and NOT from infocenter + elseif (!isEmptyString($message->sender_ou) + && !array_search($message->sender_ou, $this->_ci->config->item(self::CFG_OU_RECEIVERS_NO_NOTICE))) + { + // If the recipient organisation unit is NOT in the list of organisation units that sent only to private emails + if (array_search($message->receiver_ou, $this->_ci->config->item(self::CFG_OU_RECEIVERS_PRIVATE)) === false) + { + $this->_ci->load->model('person/Benutzer_model', 'BenutzerModel'); + + // And the receiver has an active account for the given organisation unit + $benutzerResult = $this->_ci->BenutzerModel->getActiveUserByPersonIdAndOrganisationUnit($message->receiver_id, $message->sender_ou); + if (isError($benutzerResult)) return $benutzerResult; // if an error occured then return it + + // Use the uid + domain email + if (hasData($benutzerResult)) $message->receiverContact = getData($benutzerResult)[0]->uid .'@'.DOMAIN; + } + + // Otherwise try with the private email + if (isEmptyString($message->receiverContact)) + { + $privateEmailResult = $this->_getPrivateEmail($message->receiver_id); + if (isError($privateEmailResult)) return $privateEmailResult; // if an error occured then return it + + // Use the private email + if (hasData($privateEmailResult)) $message->receiverContact = getData($privateEmailResult); + } + } + else // the recipient is a person + { + $this->_ci->load->model('person/Benutzer_model', 'BenutzerModel'); + + // The recipient has an active account + $benutzerResult = $this->_ci->BenutzerModel->loadWhere(array('person_id' => $message->receiver_id, 'aktiv' => true)); + if (isError($benutzerResult)) return $benutzerResult; // if an error occured then return it + + // If the user is present and active + if (hasData($benutzerResult)) + { + $this->_ci->load->model('ressource/Mitarbeiter_model', 'MitarbeiterModel'); + + $mitarbeiterResult = $this->_ci->MitarbeiterModel->loadWhere(array('mitarbeiter_uid' => getData($benutzerResult)[0]->uid)); + if (isError($mitarbeiterResult)) return $mitarbeiterResult; // if an error occured then return it + + // If employee + if (hasData($mitarbeiterResult)) + { + $message->receiverContact = getData($benutzerResult)[0]->uid .'@'.DOMAIN; // Use the uid + domain email + } + else // ...otherwise... + { + $this->_ci->load->model('crm/Prestudent_model', 'PrestudentModel'); + + // ...try to get all the prestudent for this receiver + $prestudentResults = $this->_ci->PrestudentModel->getOrganisationunitsByPersonId($message->receiver_id); + if (isError($prestudentResults)) return $prestudentResults; // if an error occured then return it + + // If there are presetudent + if (hasData($prestudentResults)) + { + $inArray = true; + $organisationUnits = getData($prestudentResults); + + // Look if any of the organization units of this prestudent are in the list of the + // organization units that will not send the notice email to the internal account + foreach ($organisationUnits as $organisationUnit) + { + // If the recipient organisation unit is NOT in the list of organisation units that sent only to private emails + if (array_search($organisationUnit, $this->_ci->config->item(self::CFG_OU_RECEIVERS_PRIVATE)) === false) + { + $inArray = false; + break; + } + } + + // If the recipient prestudent organization unit is not in in the list of the + // organization units that will not send the notice email to the internal account + if (!$inArray) + { + // Then use the private email + $privateEmailResult = $this->_getPrivateEmail($message->receiver_id); + if (isError($privateEmailResult)) return $privateEmailResult; // if an error occured then return it + + if (hasData($privateEmailResult)) $message->receiverContact = getData($privateEmailResult); + } + else // Use the most recent UID + domain + { + $this->_ci->BenutzerModel->resetQuery(); + + $this->_ci->BenutzerModel->addOrder('updateamum', 'DESC'); + $this->_ci->BenutzerModel->addOrder('insertamum', 'DESC'); + + $benutzerResult = $this->_ci->BenutzerModel->loadWhere(array('person_id' => $message->receiver_id)); + if (isError($benutzerResult)) return $benutzerResult; // if an error occured then return it + + $message->receiverContact = getData($benutzerResult)[0]->uid .'@'.DOMAIN; // Use the uid + domain email + } + } + } + } + else // otherwise use the private email + { + $privateEmailResult = $this->_getPrivateEmail($message->receiver_id); + if (isError($privateEmailResult)) return $privateEmailResult; // if an error occured then return it + + // Use the private email + if (hasData($privateEmailResult)) $message->receiverContact = getData($privateEmailResult); + } + } + } + + $messages[] = $message; // add new message to be noticed into the messages array + } + + return $this->_sendNoticeEmail($messages); } /** - * Wrapper for function success + * */ - private function _success($retval, $code = null) + private function _getPrivateEmail($person_id) { - return success($retval, $code); + $this->_ci->load->model('person/Kontakt_model', 'KontaktModel'); + + $getPrivateEmail = $this->_ci->KontaktModel->getContactByPersonId($person_id, self::EMAIL_KONTAKT_TYPE); + + if (hasData($getPrivateEmail)) return success(getData($getPrivateEmail)[0]->kontakt); + else return success(); + + return $getPrivateEmail; + } + + /** + * Core method to send one or more email notices for one or more messages + */ + private function _sendNoticeEmail($messages) + { + // Prefix for all links that will be subsequently generated + $prefixLink = $this->_ci->config->item(self::CFG_MESSAGE_SERVER).$this->_ci->config->item(self::CFG_MESSAGE_HTML_VIEW_URL); + + // Loads all the needed templates for HTML and plain text. Main templates from database, fallback templates from file system + $dbEmailNoticeTemplateHTML = $this->_loadDbNoticeEmailTemplate(self::NOTICE_TEMPLATE_HTML); + $dbEmailNoticeTemplateTXT = $this->_loadDbNoticeEmailTemplate(self::NOTICE_TEMPLATE_TXT); + $fsEmailNoticeTemplateHTML = $this->_loadFsNoticeEmailTemplate(self::NOTICE_TEMPLATE_FALLBACK_HTML); + $fsEmailNoticeTemplateTXT = $this->_loadFsNoticeEmailTemplate(self::NOTICE_TEMPLATE_FALLBACK_TXT); + + // Loops through all the messages to be sent + foreach ($messages as $messageData) + { + // Checks if this person has a valid email address where to send the notice email + if (!isEmptyString($messageData->receiverContact)) + { + // Create a link to the controller to view the message using a token + $viewMessageLink = $prefixLink.$messageData->token; + + // Generates notice email body in HTML format + $noticeHTMLBody = $this->_getNoticeBody( + $dbEmailNoticeTemplateHTML, $fsEmailNoticeTemplateHTML, $viewMessageLink, $messageData->subject, $messageData->body + ); + // If an error occured during the generation then the error itself is returned + if (isError($noticeHTMLBody)) return $noticeHTMLBody; + + // Generates notice email body in plain text format + $noticeTXTBody = $this->_getNoticeBody( + $dbEmailNoticeTemplateTXT, $fsEmailNoticeTemplateTXT, $viewMessageLink, $messageData->subject, $messageData->body + ); + // If an error occured during the generation then the error itself is returned + if (isError($noticeTXTBody)) return $noticeTXTBody; + + // Sending email + $sent = $this->_ci->maillib->send( + null, + $messageData->receiverContact, + $messageData->subject, + getData($noticeHTMLBody), + null, + null, + null, + getData($noticeTXTBody) + ); + + // If errors occurred while sending the email + if (!$sent) + { + // Set in database why this email is NOT going to be send + $sse = $this->_updatedRecipientNoticeEmailInfo( + $messageData->message_id, + $messageData->receiver_id, + 'An error occurred while sending the notice email', // current info + $messageData->sentinfo // previous info + ); + + // If database error occurred then return it, otherwise return a logic error + return isError($sse) ? $sse : error('An error occurred while updating the recipient notice email info'); + } + else // success! + { + // Set in database that the notice email was succesfully sent + $sss = $this->_setSentSuccess($messageData->message_id, $messageData->receiver_id); + if (isError($sss)) return $sss; // If database error occurred then return it + } + } + else // Because was not possible to find a valid contact + { + $reason = 'Was not possible to find a valid contact for this user'; // default reason + + // In case that the organisation unit does not receive any email notices + if (!isEmptyString($messageData->receiver_ou)) $reason = 'This organization unit does not receive email notices'; + + // In case that a degree program sent a message to a user without a valid contact or UID + if (!isEmptyString($messageData->sender_ou)) $reason = 'Sent from a degree program to a user that does not have a valid UID or a valid contact'; + + // Set in database why this email is NOT going to be send + $sse = $this->_updatedRecipientNoticeEmailInfo( + $messageData->message_id, + $messageData->receiver_id, + $reason, // current info + $messageData->sentinfo // previous info + ); + + // If database error occurred then return it + if (isError($sse)) return $sse; + } + } + + return success('Notice emails sent successfully'); + } + + /** + * Sends new message core method, may be wrapped by other methods. + * If success then returns an array of successfully saved message ids + */ + private function _sendMessage( + $receivers, $receiversOU, $subject, $body, $sender_id, $senderOU, $relationmessage_id, $priority, $multiPartMime + ) + { + // Checks if sender is fine + $sender = $this->_getSender($sender_id); + if (!hasData($sender)) return $sender; + + // Checks if the sender and receiver organisation unit are valid + if (($receiversOU != null && !$this->_ouExists($receiversOU)) || ($senderOU != null && !$this->_ouExists($senderOU))) + { + return error('The given organisation unit is not valid', MSG_ERR_INVALID_OU); + } + + // Checks subjects + if (isEmptyString($subject)) return error('The given subject is an empty string', MSG_ERR_INVALID_SUBJECT); + // Checks body + if (isEmptyString($body)) return error('The given body is an empty string', MSG_ERR_INVALID_BODY); + + $savedMessages = array(); // This array contains all the message ids of the saved messages + + // Looping on receivers + foreach (getData($receivers) as $receiver) + { + // Save message in database + $saveMessageResult = $this->_saveMessage( + getData($sender), $senderOU, $receiver->person_id, $receiversOU, $subject, $body, $priority, $relationmessage_id + ); + if (isSuccess($saveMessageResult)) // If successfully saved + { + $savedMessages[] = getData($saveMessageResult); // store the message id of the saved message + } + else + { + return $saveMessageResult; // If an error occured while saving + } + } + + // If the system is configured to send messages immediately + if ($this->_ci->config->item(self::CFG_SEND_IMMEDIATELY) === true) + { + // Looping through saved messages ids + foreach ($savedMessages as $message_id) + { + // Send message notice via email! + $sendNotice = $this->_sendNoticeEmails(array($message_id)); + + // If an error occurred then return it + if (isError($sendNotice)) return $sendNotice; + } + } + + return success($savedMessages); + } + + /** + * Checks if the given organisation unit exists in database + */ + private function _ouExists($ou) + { + $this->_ci->load->model('organisation/Organisationseinheit_model', 'OrganisationseinheitModel'); + + // Reset an eventually already buit query + $this->_ci->OrganisationseinheitModel->resetQuery(); + // Get only this columns + $this->_ci->OrganisationseinheitModel->addSelect('oe_kurzbz'); + // Retrieves the given organisation unit from database + $ouResults = $this->_ci->OrganisationseinheitModel->loadWhere(array('oe_kurzbz' => $ou)); + + return hasData($ouResults); + } + + /** + * Loads a the specified template from database + * Returns null if not found or on failure + */ + private function _loadDbNoticeEmailTemplate($dbTemplateName) + { + $emailNoticeTemplate = null; + + $vorlageResult = $this->_ci->vorlagelib->loadVorlagetext($dbTemplateName); + + if (hasData($vorlageResult)) + { + $emailNoticeTemplate = getData($vorlageResult)[0]->text; + } + + return $emailNoticeTemplate; + } + + /** + * Loads a the specified template from database + */ + private function _loadFsNoticeEmailTemplate($fsTemplateName) + { + return $this->_ci->load->view($fsTemplateName, null, true); } } diff --git a/application/libraries/PhrasesLib.php b/application/libraries/PhrasesLib.php index 248727107..dec3d54c0 100644 --- a/application/libraries/PhrasesLib.php +++ b/application/libraries/PhrasesLib.php @@ -165,16 +165,6 @@ class PhrasesLib } /** - * parseVorlagetext() - will parse a Vorlagetext. - */ - public function parseVorlagetext($text, $data = array()) - { - if (isEmptyString($text)) return error('Not a valid text'); - - return $this->_ci->parser->parse_string($text, $data, true); - } - - /** * Retrieves a phrases from the the property _phrases with the given parameters * It also replace parameters inside the phrase if they are provided * @param string $category Category name which is used to categorize the phrase. @@ -201,7 +191,7 @@ class PhrasesLib { if (!is_array($parameters)) $parameters = array(); // if params is not an array - return $this->_ci->parser->parse_string($_phrase->text, $parameters, true); // parsing + return parseText($_phrase->text, $parameters); // parsing } } } diff --git a/application/libraries/VorlageLib.php b/application/libraries/VorlageLib.php index d6c9d6a98..9679dff1c 100644 --- a/application/libraries/VorlageLib.php +++ b/application/libraries/VorlageLib.php @@ -188,18 +188,4 @@ class VorlageLib $vorlagetext = $this->ci->VorlageStudiengangModel->update($vorlagestudiengang_id, $data); return $vorlagetext; } - - /** - * parseVorlagetext() - will parse a Vorlagetext. - * - * @param string $text REQUIRED - * @param array $data REQUIRED - * @return string - */ - public function parseVorlagetext($text, $data = array()) - { - if (isEmptyString($text)) return error('Not a valid text'); - - return $this->ci->parser->parse_string($text, $data, true); - } } diff --git a/application/models/CL/Messages_model.php b/application/models/CL/Messages_model.php index 5f3f40e6d..cbb42543f 100644 --- a/application/models/CL/Messages_model.php +++ b/application/models/CL/Messages_model.php @@ -1,11 +1,33 @@ +
+
+ + On %s %s %s wrote: + +
+
+ %s +
'; + + const NO_AUTH_UID = 'online'; // hard coded uid if no authentication is performed + + // Recipients types + const TYPE_PERSONS = 'persons'; + const TYPE_PRESTUDENTS = 'prestudents'; + + const ALT_OE = 'infocenter'; // alternative organisation unit when no one is found for a presetudent + /** * Constructor */ @@ -14,159 +36,618 @@ class Messages_model extends CI_Model parent::__construct(); // Loads the message library - $this->load->library('MessageLib'); - + $this->load->library('MessageLib'); // MessageModel loaded here! // Loads the person log library $this->load->library('PersonLogLib'); + // Loads the widget library + $this->load->library('WidgetLib'); + // Loads model MessageToken_model $this->load->model('system/MessageToken_model', 'MessageTokenModel'); + // Loads model Benutzerrolle_model + $this->load->model('system/Benutzerrolle_model', 'BenutzerrolleModel'); + // Loads model Prestudent_model + $this->load->model('crm/Prestudent_model', 'PrestudentModel'); } + //------------------------------------------------------------------------------------------------------------------ + // Public methods + /** - * Executes message sending - * @param $sender_id - * @return array wether execution was successfull - error or success + * Set a message as read by its id ($message_id + $person_id) */ - public function send($msgVarsData, $relationmessage_id = null, $oe_kurzbz = null, $vorlage_kurzbz = null, $msgVars = null) + public function setMessageRead($message_id, $person_id) { - $subject = $this->input->post('subject'); - $body = $this->input->post('body'); + // Checks parameters + if (!is_numeric($message_id) || !is_numeric($person_id)) return error('Invalid setMessageRead parameters'); - $authUser = $this->getAuthUser(); + // Loads needed models + $this->load->model('system/MsgStatus_model', 'MsgStatusModel'); - if (isError($authUser)) return $authUser; + $statuResult = $this->MsgStatusModel->loadWhere( + array( + 'message_id' => $message_id, + 'person_id' => $person_id, + 'status' => MSG_STATUS_READ + ) + ); - $sender_id = getData($authUser)[0]->person_id; - - // Send message(s) - if (hasData($msgVarsData)) + if (isError($statuResult)) return $statuResult; + if (!hasData($statuResult)) { - for ($i = 0; $i < count(getData($msgVarsData)); $i++) - { - $parsedText = ""; - $msgVarsDataArray = $this->replaceKeys((array)getData($msgVarsData)[$i]); // replaces array keys - - // Send without vorlage - if (isEmptyString($vorlage_kurzbz)) - { - $parsedText = $this->messagelib->parseMessageText($body, $msgVarsDataArray); - $msg = $this->messagelib->sendMessage($sender_id, $msgVarsDataArray['person_id'], $subject, $parsedText, PRIORITY_NORMAL, $relationmessage_id, $oe_kurzbz); - } - // Send with vorlage - else - { - if (is_array($msgVars)) - { - // Additional message variables - foreach ($msgVars as $key => $msgvar) - { - $msgVarsDataArray[$key] = $msgvar; - } - } - $msg = $this->messagelib->sendMessageVorlage($sender_id, $msgVarsDataArray['person_id'], $vorlage_kurzbz, $oe_kurzbz, $msgVarsDataArray); - } - - if (isError($msg)) return $msg; - - // Write log entry - $personLog = $this->personloglib->log( - $msgVarsDataArray['person_id'], - 'Action', - array( - 'name' => 'Message sent', - 'message' => 'Message sent from person '.$sender_id.' to '.$msgVarsDataArray['person_id'].', messageid '.getData($msg), - 'success' => 'true' - ), - 'kommunikation', - 'core', - null, - getAuthUID() - ); - - if (isError($personLog)) return $personLog; - } - - return success('Messages sent successfully'); + // Set date used to insert + return $this->MsgStatusModel->insert( + array( + 'message_id' => $message_id, + 'person_id' => $person_id, + 'status' => MSG_STATUS_READ, + 'insertvon' => getAuthUID() + ) + ); // insert and return result } else { - return $msgVarsData; + return success('Already set as read'); } } /** - * Send a reply + * Prepares data for the view system/messages/ajaxWrite */ - public function sendReply($subject, $body, $persons, $relationmessage_id, $token) + public function prepareAjaxWrite() { - $relationmsg = $this->MessageTokenModel->getMessageByToken($token); - if (!hasData($relationmsg) || $relationmessage_id !== getData($relationmsg)[0]->message_id) - { - show_error('Error while sending reply'); - } + $ouResult = $this->PrestudentModel->getOrganisationunitsByPersonId(getAuthPersonId()); - // Get sender (receiver of previous msg) - $sender_id = getData($relationmsg)[0]->receiver_id; + if (isError($ouResult)) show_error('An error occurred while loading this page, please contact the site administrator'); - // Get message data of persons - $data = $this->MessageTokenModel->getPersonData($persons); - if (hasData($data)) + $ouOptions = ''; + + if (hasData($ouResult)) { - for ($i = 0; $i < count(getData($data)); $i++) + foreach (getData($ouResult) as $ou) { - $dataArray = (array)getData($data)[$i]; - - $msg = $this->messagelib->sendMessage($sender_id, $dataArray['person_id'], $subject, $body, PRIORITY_NORMAL, $relationmessage_id, null); - if (isError($msg)) return $msg; - - // Logs person data - $personLog = $this->personloglib->log( - $sender_id, - 'Action', - array( - 'name' => 'Message sent', - 'message' => 'Message sent from person '.$sender_id.' to '.$dataArray['person_id'].', messageid '.getData($msg), - 'success' => 'true' - ), - 'kommunikation', - 'core', - null, - 'online' + $ouOptions .= sprintf( + "\n".'', + is_numeric($ou->prestudent_id) ? $ou->oe_kurzbz : self::ALT_OE, + $ou->bezeichnung . (is_numeric($ou->prestudent_id) ? '' : ' *') ); - - // Unpark bewerber after he sends message - $personLog = $this->personloglib->unPark($sender_id); - - if (isError($personLog)) return $personLog; } } - return success('Reply sent'); + return array('organisationUnitOptions' => $ouOptions); } /** - * + * Prepares data for the view system/messages/ajaxWriteReply */ - public function getAuthUser() + public function prepareAjaxWriteReply($token) { - $sender_id = null; + if (isEmptyString($token)) show_error('The given token is not valid'); - $this->load->model('person/Person_model', 'PersonModel'); - $authUser = $this->PersonModel->getByUid(getAuthUID()); + // Retrieves message using the given token + $messageResult = $this->MessageTokenModel->getMessageByToken($token); + if (isError($messageResult)) show_error('An error occurred while loading this page, please contact the site administrator'); - if (!hasData($authUser)) $authUser = error('The current logged user person_id is not defined'); + if (hasData($messageResult)) + { + $message = getData($messageResult)[0]; // Found message data - return $authUser; + // Retrieves message sender information + $senderResult = $this->MessageTokenModel->getSenderData($message->sender_id); + if (isError($senderResult)) show_error('An error occurred while loading this page, please contact the site administrator'); + + if (hasData($senderResult)) + { + $sender = getData($senderResult)[0]; // Found sender data + + $replySubject = self::REPLY_SUBJECT_PREFIX.$message->subject; + $replyBody = $this->_getReplyBody($message->body, $sender->vorname, $sender->nachname, $message->sent); + + return array ( + 'receiver' => $sender->vorname.' '.$sender->nachname, // yep! the sender of the sent message is the receiver of the reply message + 'subject' => $replySubject, + 'body' => $replyBody, + 'receiver_id' => $message->sender_id, + 'relationmessage_id' => $message->message_id, + 'token' => $token + ); + } + } } /** - * + * Prepares data for the view system/messages/ajaxRead + * If everything is fine returns a list of received messages (objects) */ - public function replaceKeys($data) + public function prepareAjaxReadReceived() + { + // Retrieves received messages for the logged user and its organisation units + $receivedMessagesResult = $this->RecipientModel->getReceivedMessages( + getAuthPersonId(), + $this->config->item(MessageLib::CFG_OU_RECEIVERS) + ); + // If an error occurred return it + if (isError($receivedMessagesResult)) return $receivedMessagesResult; + + // If data were found + if (hasData($receivedMessagesResult)) + { + $jsonArray = array(); // array that contains all the received messages + + // Collect'em all in the array $jsonArray + foreach (getData($receivedMessagesResult) as $receivedMessage) + { + $jsonRecord = new stdClass(); + $jsonRecord->message_id = $receivedMessage->message_id; + $jsonRecord->subject = $receivedMessage->subject; + $jsonRecord->body = $receivedMessage->body; + $jsonRecord->from = $receivedMessage->vorname.' '.$receivedMessage->nachname; + $sentDate = new DateTime($receivedMessage->sent); + $jsonRecord->sent = $sentDate->format('d/m/Y H:i:s'); + $jsonRecord->status = $receivedMessage->status; + $jsonRecord->statusPersonId = $receivedMessage->statuspersonid; + $jsonRecord->token = $receivedMessage->token; + + $jsonArray[] = $jsonRecord; + } + + return success(json_encode($jsonArray)); // return as an json encoded string + } + + return success('No messages were found'); // NOT a blocking error + } + + /** + * Prepares data for the view system/messages/ajaxRead + * If everything is fine returns a list of sent messages (objects) + */ + public function prepareAjaxReadSent() + { + // Retrieves sent messages from the logged user + $sentMessagesResult = $this->RecipientModel->getSentMessages(getAuthPersonId()); + if (isError($sentMessagesResult)) return $sentMessagesResult; // If an error occurred return it + + if (hasData($sentMessagesResult)) + { + $jsonArray = array();// array that contains all the sent messages + + // Collect'em all in the array $jsonArray + foreach (getData($sentMessagesResult) as $sentMessage) + { + $jsonRecord = new stdClass(); + $jsonRecord->message_id = $sentMessage->message_id; + $jsonRecord->subject = $sentMessage->subject; + $jsonRecord->body = $sentMessage->body; + $sentDate = new DateTime($sentMessage->sent); + $jsonRecord->sent = $sentDate->format('d/m/Y H:i:s'); + $jsonRecord->status = $sentMessage->status; + $jsonRecord->statusPersonId = $sentMessage->statuspersonid; + $jsonRecord->token = $sentMessage->token; + + if ($sentMessage->person_id == $this->config->item(MessageLib::CFG_SYSTEM_PERSON_ID)) + { + $jsonRecord->to = $sentMessage->oe; + } + else + { + $jsonRecord->to = $sentMessage->vorname.' '.$sentMessage->nachname; + } + + $jsonArray[] = $jsonRecord; + } + + return success(json_encode($jsonArray)); // return as an json encoded string + } + + return success('No messages were found'); // NOT a blocking error + } + + /** + * Prepares data for the view system/messages/htmlRead using a token that identifies a single message + */ + public function prepareHtmlRead($token) + { + if (isEmptyString($token)) show_error('The given token is not valid'); + + // Retrieves message using the given token + $messageResult = $this->MessageTokenModel->getMessageByToken($token); + if (isError($messageResult)) show_error(getError($messageResult)); + if (!hasData($messageResult)) show_error('No message found with the given token'); + + $message = getData($messageResult)[0]; // Found message data + + // Set message as read + $srmsbtResult = $this->MessageTokenModel->setReadMessageStatusByToken($token); + if (isError($srmsbtResult)) show_error(getError($srmsbtResult)); + + // Retrieves message sender information + $senderResult = $this->MessageTokenModel->getSenderData($message->sender_id); + if (isError($senderResult)) show_error(getError($senderResult)); + if (!hasData($senderResult)) show_error('No sender information found'); + + $sender = getData($senderResult)[0]; // Found sender data + + // Check if the receiver is an employee + $isEmployee = false; // not by default + $isEmployeeResult = $this->MessageTokenModel->isEmployee($message->receiver_id); + if (isError($isEmployeeResult)) show_error(getError($isEmployeeResult)); + if (hasData($isEmployeeResult)) $isEmployee = true; + + // If the sender is not an employee and are present configurations to reply + $hrefReply = ''; + if (!$isEmployee && !isEmptyString($this->config->item(MessageLib::CFG_REDIRECT_VIEW_MESSAGE_URL))) + { + $hrefReply = $this->config->item(MessageLib::CFG_MESSAGE_SERVER). + $this->config->item(MessageLib::CFG_REDIRECT_VIEW_MESSAGE_URL). + $token; + } + + return array ( + 'sender' => $sender, + 'message' => $message, + 'hrefReply' => $hrefReply + ); + } + + /** + * Prepares data for the view system/messages/htmlWriteReply using a token that identifies a single message + */ + public function prepareHtmlWriteReply($token) + { + if (isEmptyString($token)) show_error('The given token is not valid'); + + // Retrieves message using the given token + $messageResult = $this->MessageTokenModel->getMessageByToken($token); + if (isError($messageResult)) show_error(getError($messageResult)); + if (!hasData($messageResult)) show_error('No message found with the given token'); + + $message = getData($messageResult)[0]; // Found message data + + // Retrieves message sender information + $senderResult = $this->MessageTokenModel->getSenderData($message->sender_id); + if (isError($senderResult)) show_error(getError($senderResult)); + if (!hasData($senderResult)) show_error('No sender information found'); + + $sender = getData($senderResult)[0]; // Found sender data + + $replySubject = self::REPLY_SUBJECT_PREFIX.$message->subject; + $replyBody = $this->_getReplyBody($message->body, $sender->vorname, $sender->nachname, $message->sent); + + return array ( + 'receiver' => $sender->vorname.' '.$sender->nachname, // yep! the sender of the sent message is the receiver of the reply message + 'subject' => $replySubject, + 'body' => $replyBody, + 'receiver_id' => $message->sender_id, + 'relationmessage_id' => $message->message_id, + 'token' => $token + ); + } + + /** + * Prepares data for the view system/messages/htmlWriteTemplate using person ids as main parameter + * Wrap method to _prepareHtmlWriteTemplate + */ + public function prepareHtmlWriteTemplatePersons($persons, $message_id = null, $recipient_id = null) + { + // Retrieves persons information + $msgVarsData = $this->MessageModel->getMsgVarsDataByPersonId($persons); + + return $this->_prepareHtmlWriteTemplate($msgVarsData, $message_id, $recipient_id); + } + + /** + * Prepares data for the view system/messages/htmlWriteTemplate using prestudent ids as main parameter + * Wrap method to _prepareHtmlWriteTemplate + */ + public function prepareHtmlWriteTemplatePrestudents($prestudents, $message_id = null, $recipient_id = null) + { + // Retrieves prestudents information + $msgVarsData = $this->MessageModel->getMsgVarsDataByPrestudentId($prestudents); + + return $this->_prepareHtmlWriteTemplate($msgVarsData, $message_id, $recipient_id); + } + + /** + * Sends a new message or a reply to a message (if $relationmessage_id is given) + * using the template stored in the subject and body + */ + public function sendImplicitTemplate($type, $recipients_ids, $subject, $body, $relationmessage_id = null) + { + // Retrieves the sender id + $sender_id = getAuthPersonId(); + if (!is_numeric($sender_id)) show_error('The current logged user person_id is not defined'); + + $msgVarsData = error('No persons nor prestudents were provided'); + // Retrieves message vars data for the given user/s + if ($type == self::TYPE_PERSONS) // if persons were given + { + $msgVarsData = $this->MessageModel->getMsgVarsDataByPersonId($recipients_ids); + } + elseif ($type == self::TYPE_PRESTUDENTS) // otherwise prestudents were given + { + $msgVarsData = $this->MessageModel->getMsgVarsDataByPrestudentId($recipients_ids); + + // Retrieve organisation unit for the recipients + $organisationUnitsResult = $this->PrestudentModel->getOrganisationunits($recipients_ids); + if (isError($organisationUnitsResult)) return $organisationUnitsResult; + if (hasData($organisationUnitsResult)) $senderOUArray = getData($organisationUnitsResult); + } + if (isError($msgVarsData)) show_error(getError($msgVarsData)); + if (!hasData($msgVarsData)) show_error('No recipients were given'); + + $senderOU = null; // sender organisation unit only for presetudents + $receiversCounter = 0; // a counter + + // Looping on receivers data + foreach (getData($msgVarsData) as $receiver) + { + $msgVarsDataArray = $this->_lowerReplaceSpaceArrayKeys((array)$receiver); // replaces array keys + $parsedSubject = parseText($subject, $msgVarsDataArray); + $parsedBody = parseText($body, $msgVarsDataArray); + + // If exist an organisation unit for this prestudent and it is valid + if (isset($senderOUArray[$receiversCounter]) + && isset($senderOUArray[$receiversCounter]->oe_kurzbz) + && !isEmptyString($senderOUArray[$receiversCounter]->oe_kurzbz)) + { + $senderOU = $senderOUArray[$receiversCounter]->oe_kurzbz; + } + else + { + $senderOU = null; + } + + $message = $this->messagelib->sendMessageUser( + $msgVarsDataArray['person_id'], // receiverPersonId + $parsedSubject, // subject + $parsedBody, // body + $sender_id, // sender_id + $senderOU, // senderOU + $relationmessage_id, // relationmessage_id + MSG_PRIORITY_NORMAL // priority + ); + + if (isError($message)) return $message; + if (!hasData($message)) return error('No messages were saved in database'); + + // Write log entry only if persons were given + if ($type == self::TYPE_PERSONS) + { + $personLog = $this->_personLog($sender_id, $msgVarsDataArray['person_id'], getData($message)[0]); + if (isError($personLog)) return $personLog; + } + + $receiversCounter++; // increment the counter + } + + return success('Messages sent successfully'); + } + + /** + * Sends a new message using the given template and information present in parameter prestudents + * Extra variables can be added using parameter $msgVars + */ + public function sendExplicitTemplate($prestudents, $oe_kurzbz, $vorlage_kurzbz, $msgVars) + { + // Retrieves the sender id + $sender_id = getAuthPersonId(); + if (!is_numeric($sender_id)) show_error('The current logged user person_id is not defined'); + + // Retrieves message vars data for the given user/s + $msgVarsData = $this->MessageModel->getMsgVarsDataByPrestudentId($prestudents); + if (isError($msgVarsData)) show_error(getError($msgVarsData)); + if (!hasData($msgVarsData)) show_error('No recipients were given'); + + $prestudentsData = $this->PrestudentModel->getOrganisationunits($prestudents); + + // Adds the organisation unit to each prestudent + if (isEmptyString($oe_kurzbz) && hasData($msgVarsData) && hasData($prestudentsData)) + { + $this->CLMessagesModel->_addOeToPrestudents($msgVarsData, $prestudentsData); + } + + foreach (getData($msgVarsData) as $receiver) + { + $msgVarsDataArray = $this->_lowerReplaceSpaceArrayKeys((array)$receiver); // replaces array keys + + // Additional message variables + if (is_array($msgVars)) $msgVarsDataArray = array_merge($msgVarsDataArray, $msgVars); + + $message = $this->messagelib->sendMessageUserTemplate( + $msgVarsDataArray['person_id'], // receiversPersonId + $vorlage_kurzbz, // vorlage + $msgVarsDataArray, // parseData + null, // orgform + $sender_id, // sender_id + $oe_kurzbz // senderOU + ); + + if (isError($message)) return $message; + + // Write log entry + $personLog = $this->_personLog($sender_id, $msgVarsDataArray['person_id'], getData($message)[0]); + if (isError($personLog)) return $personLog; + } + + return success('Messages sent successfully'); + } + + /** + * Send a reply to a single recipient for a message identified by a token (no templates are used) + * NOTE: this method could be also called from not authenticated controllers + */ + public function sendReply($receiver_id, $subject, $body, $relationmessage_id, $token) + { + // Retrieves message sender information + $senderResult = $this->MessageTokenModel->getSenderData($receiver_id); + if (isError($senderResult)) show_error(getError($senderResult)); + if (!hasData($senderResult)) show_error('No sender information found'); + + $sender = getData($senderResult)[0]; // Found sender data + + $messageResult = $this->MessageTokenModel->getMessageByToken($token); + if (isError($messageResult)) show_error(getError($messageResult)); + // Security check! It is possible to reply only to a received message!! + if (!hasData($messageResult) || $relationmessage_id != getData($messageResult)[0]->message_id) + { + show_error('An error occurred while sending your message, please contact the site administrator'); + } + + // If the user is logged then use its person id as sender id, otherwise get the receiver id of the previous message + $sender_id = isLogged() ? getAuthPersonId() : getData($messageResult)[0]->receiver_id; + if (!is_numeric($sender_id)) return error('The sender id is not valid'); + + $message = $this->messagelib->sendMessageUser( + $receiver_id, // receiverPersonId + $subject, // subject + $body, // body + $sender_id, // sender_id, the receiver of the previous message is the sender of the current one + null, // senderOU + $relationmessage_id, // relationmessage_id + MSG_PRIORITY_NORMAL // priority + ); + + if (isError($message)) return $message; + if (!hasData($message)) return error('No messages were saved in database'); + + // Write log entry + // NOTE: $receiver_id and $sender_id are switched!!! Currently this is a workaround + $personLog = $this->_personLog($receiver_id, $sender_id, getData($message)[0]); + if (isError($personLog)) return $personLog; + + return success('Messages sent successfully'); + } + + /** + * Send a message to an organisation unit + */ + public function sendToOrganisationUnit($receiverOU, $subject, $body) + { + if (isEmptyString($receiverOU)) return error('Not a valid organisation unit'); + if (isEmptyString($subject)) return error('Subject is an empty string'); + if (isEmptyString($body)) return error('Body is an empty string'); + + $sender_id = getAuthPersonId(); + if (!is_numeric($sender_id)) return error('The current logged user person_id is not defined'); + + $message = $this->messagelib->sendMessageOU( + $receiverOU, // receiverPersonId + $subject, // subject + $body, // body + $sender_id // sender_id + ); + + if (isError($message)) return $message; + if (!hasData($message)) return error('No messages were saved in database'); + + // Write log entry + $personLog = $this->_personLog($sender_id, $this->config->item(MessageLib::CFG_SYSTEM_PERSON_ID), getData($message)[0], $receiverOU); + if (isError($personLog)) return $personLog; + + return success('Messages sent successfully'); + } + + //------------------------------------------------------------------------------------------------------------------ + // Public methods called by controller system/messages/Messages + + /** + * Returns an object that represent a template store in database + * If no templates are found with the given parameter or the given parameter is an empty string, + * then an error is returned + */ + public function getVorlage($vorlage_kurzbz) + { + $getVorlage = error('The given vorlage_kurzbz is not valid'); + + if (!isEmptyString($vorlage_kurzbz)) + { + $this->load->model('system/Vorlagestudiengang_model', 'VorlagestudiengangModel'); + $this->VorlagestudiengangModel->addOrder('version','DESC'); + + $getVorlage = $this->VorlagestudiengangModel->loadWhere(array('vorlage_kurzbz' => $vorlage_kurzbz)); + } + + return $getVorlage; + } + + /** + * Parse the given given text using data from the given user + * Use the CI parser which performs simple text substitution for pseudo-variable + */ + public function parseMessageTextPerson($person_id, $text) + { + $parseMessageText = error('The given person_id is not a valid number'); + + if (is_numeric($person_id)) $parseMessageText = $this->MessageModel->getMsgVarsDataByPersonId($person_id); + + if (hasData($parseMessageText)) + { + $parseMessageText = success( + parseText( + $text, + $this->_lowerReplaceSpaceArrayKeys((array)getData($parseMessageText)[0]) + ) + ); + } + + return $parseMessageText; + } + + /** + * Parse the given given text using data from the given user + * Use the CI parser which performs simple text substitution for pseudo-variable + */ + public function parseMessageTextPrestudent($prestudent_id, $text) + { + $parseMessageText = error('The given prestudent_id is not a valid number'); + + if (is_numeric($prestudent_id)) $parseMessageText = $this->MessageModel->getMsgVarsDataByPrestudentId($prestudent_id); + + if (hasData($parseMessageText)) + { + $parseMessageText = success( + parseText( + $text, + $this->_lowerReplaceSpaceArrayKeys((array)getData($parseMessageText)[0]) + ) + ); + } + + return $parseMessageText; + } + + /** + * Outputs message data for a message (identified my msg id and receiver id) in JSON format + */ + public function getMessageFromIds($message_id, $receiver_id) + { + $getMessageFromIds = error('The given message id or receiver id are not valid'); + + if (is_numeric($message_id) && is_numeric($receiver_id)) + { + $getMessageFromIds = $this->messagelib->getMessage($message_id, $receiver_id); + } + + if (isError($getMessageFromIds) || !hasData($getMessageFromIds)) + { + return array(); + } + else + { + return array(getData($getMessageFromIds)[0]); + } + } + + //------------------------------------------------------------------------------------------------------------------ + // Private methods + + /** + * Replaces data array keys to a lowercase string with underscores instead of spaces + */ + private function _lowerReplaceSpaceArrayKeys($data) { $tmpData = array(); - // Replaces data array keys to a lowercase without spaces string foreach ($data as $key => $val) { $tmpData[str_replace(' ', '_', strtolower($key))] = $val; @@ -176,9 +657,9 @@ class Messages_model extends CI_Model } /** - * + * Add organisation unit to an array of prestudents (objects) */ - public function addOeToPrestudents(&$msgVarsData, $prestudentsData) + private function _addOeToPrestudents(&$msgVarsData, $prestudentsData) { for ($i = 0; $i < count(getData($msgVarsData)); $i++) { @@ -192,4 +673,171 @@ class Messages_model extends CI_Model } } } + + /** + * Perform a person log after a message is sent + */ + private function _personLog($sender_id, $receiver_id, $message_id, $receiverOU = null) + { + // In case the message is accessed via ViewMessage controller -> no authentication + // If no authentication is performed then use a hard coded uid + $loggedUserUID = isLogged() ? getAuthUID() : self::NO_AUTH_UID; + + $message = 'Message sent from person '.$sender_id.' to '.$receiver_id.', message id: '.$message_id; + if (!isEmptyString($receiverOU)) $message .= ', receiverOU: '.$receiverOU; + + return $this->personloglib->log( + $receiver_id, + 'Action', + array( + 'name' => 'Message sent', + 'message' => $message, + 'success' => 'true' + ), + 'kommunikation', + 'core', + null, + $loggedUserUID + ); + } + + /** + * Quotes the previous message body + */ + private function _getReplyBody($body, $receiverName, $receiverSurname, $sentDate) + { + return sprintf( + self::REPLY_BODY_FORMAT, + date_format(date_create($sentDate), 'd.m.Y H:i'), $receiverName, $receiverSurname, $body + ); + } + + /** + * Prepares data for the view system/messages/htmlWriteTemplate using the given parameters + */ + private function _prepareHtmlWriteTemplate($info, $message_id, $recipient_id) + { + // Checks that info parameter is valid + if (isError($info)) show_error(getError($info)); + if (!hasData($info)) show_error('No recipients were given'); + + // If the message id and recipient id are given, then both they must be valid numbers + if ((is_numeric($message_id) && !is_numeric($recipient_id)) + || (!is_numeric($message_id) && is_numeric($recipient_id))) + { + show_error('If given, message id and recipient id both must be valid numbers'); + } + + // --------------------------------------------------------------------------------------- + // Retrieves the recipients information and builds: + // - recipientsArray: an array that contains objects with id (person_id) and description (Vorname + Nachname) of recipient + // - recipientsList: a string that contains all the recipients descriptions (Vorname + Nachname) separated by ; + // - persons: a string that contains HTML input hidden with alla the receivers id (person_id) + $recipientsArray = array(); + $recipientsList = ''; + $recipients_ids = ''; + + foreach (getData($info) as $receiver) + { + $id = 0; + $recipient = new stdClass(); + $recipient->description = $receiver->Vorname.' '.$receiver->Nachname; + $recipientsList .= $receiver->Vorname.' '.$receiver->Nachname.'; '; + + // If it is a prestudent then + if (isset($receiver->prestudent_id) && is_numeric($receiver->prestudent_id)) + { + $recipient->id = $receiver->prestudent_id; + $id = $receiver->prestudent_id; + } + else // otherwise it is a person + { + $recipient->id = $receiver->person_id; + $id = $receiver->person_id; + } + + $recipients_ids .= ''."\n"; + + $recipientsArray[] = $recipient; + } + + // --------------------------------------------------------------------------------------- + // Retrieves the message to reply to, if it is specified by parameters $message_id and $recipient_id + $replySubject = ''; // message reply subject + $replyBody = ''; // message reply body + $relationmessage = ''; // input hidden that contains the message id to be replied to + // If both are given and they are valid + if (is_numeric($message_id) && is_numeric($recipient_id)) + { + // Retrieves a received message from tbl_msg_recipient + $messageResult = $this->messagelib->getMessage($message_id, $recipient_id); + if (isError($messageResult)) show_error(getError($messageResult)); + if (!hasData($messageResult)) show_error('The selected message does not exist'); + + $message = getData($messageResult)[0]; + + $replySubject = self::REPLY_SUBJECT_PREFIX.$message->subject; + $replyBody = $this->_getReplyBody($message->body, $receiver->Vorname, $receiver->Nachname, $message->sent); + $relationmessage = ''; + } + + // --------------------------------------------------------------------------------------- + // Retrieves message vars from database view vw_msg_vars/vw_msg_vars_person + $variablesResult = null; + $type = ''; + + // If data contains a prestudent id + // NOTE: + // - info is checked at the beginning of this method so it is safe to use getData($info)[0] + // - the provided data inside info are all persons or all prestudents, so it is safe to check only the first one + if (isset(getData($info)[0]->prestudent_id) && is_numeric(getData($info)[0]->prestudent_id)) + { + $variablesResult = $this->messagelib->getMessageVarsPrestudent(); + $type = ''; + } + else + { + $variablesResult = $this->messagelib->getMessageVarsPerson(); + $type = ''; + } + if (isError($variablesResult)) show_error(getError($variablesResult)); + + // Then builds an array that contains objects with id (person_id) and description (Vorname + Nachname) of recipient + $variables = array(); + foreach (getData($variablesResult) as $id => $description) + { + $tmpVar = new stdClass(); + $tmpVar->id = $id; + $tmpVar->description = $description; + + $variables[] = $tmpVar; + } + + // --------------------------------------------------------------------------------------- + // Retrieves the sender id + $sender_id = getAuthPersonId(); + if (!is_numeric($sender_id)) show_error('The current logged user person_id is not defined'); + + // --------------------------------------------------------------------------------------- + // Organisation units and a boolean (true if the sender is administrator) are used to get the templates + $organisationUnits = $this->messagelib->getOeKurzbz($sender_id); + if (isError($organisationUnits)) show_error(getError($organisationUnits)); + $senderIsAdmin = $this->BenutzerrolleModel->isAdminByPersonId($sender_id); + if (isError($senderIsAdmin)) show_error(getError($senderIsAdmin)); + + // --------------------------------------------------------------------------------------- + // Returns data as an array + return array ( + 'recipientsList' => $recipientsList, + 'subject' => $replySubject, + 'body' => $replyBody, + 'variables' => $variables, + 'organisationUnits' => getData($organisationUnits), + 'senderIsAdmin' => getData($senderIsAdmin), + 'recipientsArray' => $recipientsArray, + 'recipients_ids' => $recipients_ids, + 'relationmessage_id' => $relationmessage, + 'type' => $type + ); + } } diff --git a/application/models/crm/Prestudent_model.php b/application/models/crm/Prestudent_model.php index d5c52a3c3..b40897d82 100644 --- a/application/models/crm/Prestudent_model.php +++ b/application/models/crm/Prestudent_model.php @@ -521,4 +521,35 @@ class Prestudent_model extends DB_Model } } } + + /** + * Get organisation units for all the prestudents of a person + */ + public function getOrganisationunitsByPersonId($person_id) + { + $query = 'SELECT o.oe_kurzbz, + o.bezeichnung, + (CASE + WHEN sg.typ = \'b\' THEN ps.prestudent_id + WHEN sg.typ = \'m\' THEN p.prestudent_id + ELSE NULL + END) AS prestudent_id + FROM public.tbl_prestudent p + JOIN public.tbl_studiengang sg USING(studiengang_kz) + JOIN public.tbl_organisationseinheit o USING(oe_kurzbz) + LEFT JOIN ( + SELECT prestudent_id + FROM public.tbl_prestudentstatus + WHERE status_kurzbz = \'Bewerber\' + ) ps USING(prestudent_id) + WHERE p.person_id = ? + GROUP BY o.oe_kurzbz, + o.bezeichnung, + sg.typ, + ps.prestudent_id, + p.prestudent_id + ORDER BY o.bezeichnung'; + + return $this->execQuery($query, array($person_id)); + } } diff --git a/application/models/person/Benutzer_model.php b/application/models/person/Benutzer_model.php index dc5b95779..a21811bb4 100644 --- a/application/models/person/Benutzer_model.php +++ b/application/models/person/Benutzer_model.php @@ -18,4 +18,19 @@ class Benutzer_model extends DB_Model return $this->loadWhere(array('person_id' => $person_id, 'aktiv' => true)); } + /** + * + */ + public function getActiveUserByPersonIdAndOrganisationUnit($person_id, $oe_kurzbz) + { + $sql = 'SELECT b.uid + FROM public.tbl_benutzer b + JOIN public.tbl_prestudent ps USING (person_id) + JOIN public.tbl_studiengang sg USING (studiengang_kz) + WHERE ps.person_id = ? + AND sg.oe_kurzbz = ? + AND b.aktiv = TRUE'; + + return $this->execQuery($sql, array($person_id, $oe_kurzbz)); + } } diff --git a/application/models/person/Benutzerfunktion_model.php b/application/models/person/Benutzerfunktion_model.php index ceb427687..fb9b51c1a 100644 --- a/application/models/person/Benutzerfunktion_model.php +++ b/application/models/person/Benutzerfunktion_model.php @@ -11,16 +11,20 @@ class Benutzerfunktion_model extends DB_Model $this->dbTable = 'public.tbl_benutzerfunktion'; $this->pk = 'benutzerfunktion_id'; } - + /** * Get the Benutzerfunktion using the person_id */ - public function getByPersonId($person_id) + public function getActiveFunctionsByPersonId($person_id) { - // Join with the table - $this->addJoin('public.tbl_benutzer', 'uid'); - - return $this->loadWhere(array('person_id' => $person_id)); + $query = 'SELECT bf.* + FROM public.tbl_benutzerfunktion bf + JOIN public.tbl_benutzer b USING (uid) + WHERE b.person_id = ? + AND (bf.datum_von IS NULL OR bf.datum_von <= now()) + AND (bf.datum_bis IS NULL OR bf.datum_bis >= now())'; + + return $this->execQuery($query, array($person_id)); } /** diff --git a/application/models/person/Kontakt_model.php b/application/models/person/Kontakt_model.php index 88a44cbc8..3f27604e8 100644 --- a/application/models/person/Kontakt_model.php +++ b/application/models/person/Kontakt_model.php @@ -8,17 +8,17 @@ class Kontakt_model extends DB_Model public function __construct() { parent::__construct(); - $this->dbTable = "public.tbl_kontakt"; - $this->pk = "kontakt_id"; + $this->dbTable = 'public.tbl_kontakt'; + $this->pk = 'kontakt_id'; } - + public function getWholeKontakt($kontakt_id, $person_id = null, $kontakttyp = null) { $result = null; - - $this->addJoin("public.tbl_standort", "standort_id", "LEFT"); - $this->addJoin("public.tbl_firma", "firma_id", "LEFT"); - + + $this->addJoin('public.tbl_standort', 'standort_id', 'LEFT'); + $this->addJoin('public.tbl_firma', 'firma_id', 'LEFT'); + if (isset($kontakt_id)) { $result = $this->load($kontakt_id); @@ -26,22 +26,37 @@ class Kontakt_model extends DB_Model else { $parametersArray = array(); - + if (!is_null($person_id)) { - $parametersArray["person_id"] = $person_id; + $parametersArray['person_id'] = $person_id; } if (!is_null($kontakttyp)) { - $parametersArray["kontakttyp"] = $kontakttyp; + $parametersArray['kontakttyp'] = $kontakttyp; } - + if (count($parametersArray) > 0) { $result = $this->loadWhere($parametersArray); } } - + return $result; } -} \ No newline at end of file + + /** + * + */ + public function getContactByPersonId($person_id, $kontakttyp) + { + $sql = 'SELECT kontakt + FROM public.tbl_kontakt + WHERE zustellung = TRUE + AND person_id = ? + AND kontakttyp = ? + ORDER BY updateamum, insertamum'; + + return $this->execQuery($sql, array($person_id, $kontakttyp)); + } +} diff --git a/application/models/person/Person_model.php b/application/models/person/Person_model.php index 388f77b0a..d8ddb381c 100644 --- a/application/models/person/Person_model.php +++ b/application/models/person/Person_model.php @@ -213,4 +213,39 @@ class Person_model extends DB_Model return $this->loadWhere(array('uid' => $uid, 'content' => true)); } + + /** + * Checks if a person has a Bewerberstatus and reihungstestangetreten = true + * @param $person_id + * @param $studiensemester_kurzbz + * @return array + */ + public function hasBewerber($person_id, $studiensemester_kurzbz, $studiengangtyp = null) + { + $parametersArray = array($person_id, $studiensemester_kurzbz); + + $qry = "SELECT count(*) AS anzahl_bewerber FROM public.tbl_person + JOIN public.tbl_prestudent USING (person_id) + JOIN public.tbl_prestudentstatus ON tbl_prestudentstatus.prestudent_id = tbl_prestudent.prestudent_id"; + + if (isset($studiengangtyp)) + { + $qry .= " JOIN lehre.tbl_studienplan USING(studienplan_id) + JOIN lehre.tbl_studienordnung USING(studienordnung_id) + JOIN public.tbl_studiengang ON tbl_studienordnung.studiengang_kz = tbl_studiengang.studiengang_kz"; + } + + $qry .= " WHERE person_id = ? + AND studiensemester_kurzbz = ? + AND tbl_prestudentstatus.status_kurzbz = 'Bewerber' + AND reihungstestangetreten"; + + if (isset($studiengangtyp)) + { + $parametersArray[] = $studiengangtyp; + $qry .= " AND tbl_studiengang.typ = ?"; + } + + return $this->execQuery($qry, $parametersArray); + } } diff --git a/application/models/system/MessageToken_model.php b/application/models/system/MessageToken_model.php index cf1745ea6..cd3d8f7d9 100644 --- a/application/models/system/MessageToken_model.php +++ b/application/models/system/MessageToken_model.php @@ -136,24 +136,6 @@ class MessageToken_model extends DB_Model return $this->execQuery($sql, array($person_id)); } - /** - * Get data of a person - */ - public function getPersonData($person_id) - { - $sql = 'SELECT person_id, - vorname as "Vorname", - nachname as "Nachname", - anrede as "Anrede", - titelpost as "TitelPost", - titelpre as "TitelPre", - vornamen as "Vornamen" - FROM public.tbl_person - WHERE person_id %s ?'; - - return $this->execQuery(sprintf($sql, is_array($person_id) ? 'IN' : '='), array($person_id)); - } - /** * Searchs for a person by its person_id and checks if it is an employee */ diff --git a/application/models/system/Recipient_model.php b/application/models/system/Recipient_model.php index 654a9a883..d74d03243 100644 --- a/application/models/system/Recipient_model.php +++ b/application/models/system/Recipient_model.php @@ -25,7 +25,8 @@ class Recipient_model extends DB_Model ks.kontakt, p.nachname, p.vorname, - b.uid + b.uid, + mr.sent FROM public.tbl_msg_recipient mr INNER JOIN public.tbl_msg_message mm USING (message_id) INNER JOIN public.tbl_person p ON (mm.person_id = p.person_id) LEFT JOIN public.tbl_benutzer b ON (mr.person_id = b.person_id) @@ -56,11 +57,13 @@ class Recipient_model extends DB_Model m.oe_kurzbz, s.status, s.statusinfo, - s.insertamum as statusamum + s.insertamum as statusamum, + b.uid FROM public.tbl_msg_recipient r JOIN public.tbl_msg_message m USING (message_id) JOIN ( SELECT * FROM public.tbl_msg_status WHERE status < ? ORDER BY insertamum DESC, status DESC - ) s ON (r.message_id = s.message_id AND r.person_id = s.person_id) + ) s ON (r.message_id = s.message_id AND r.person_id = s.person_id), + LEFT JOIN public.tbl_benutzer b USING(person_id) WHERE r.token = ? LIMIT 1'; @@ -196,74 +199,24 @@ class Recipient_model extends DB_Model } /** - * getMessages + * Gets all messages for which notice emails are still not sent * - * Gets all the messages to be sent - * - * @param kontaktType specifies the type of the kontakt to get - * @param sent specifies the status of the messages to get (NULL never sent, otherwise the shipping date) - * @param limit specifies the number of messages to get - * @param message_id specifies a single message + * @param kontaktType specifies the type of the kontakt to get (email,...) + * @param limit specifies the max number of messages to get + * @param since specifies from which date messages have to be retrieved */ - public function getMessages($kontaktType, $sent, $limit = null, $message_id = null) + public function getNotSentMessages($limit, $since) { - $query = 'SELECT mm.message_id, - ks.kontakt as sender, - kr.kontakt as receiver, - mu.mitarbeiter_uid as employeeContact, - ms.mitarbeiter_uid as senderemployeeContact, - mr.person_id as receiver_id, - mr.token, - mm.subject, - mm.body, - mr.sentinfo - FROM public.tbl_msg_recipient mr INNER JOIN public.tbl_msg_message mm USING (message_id) - LEFT JOIN ( - SELECT person_id, kontakt FROM public.tbl_kontakt WHERE kontakttyp = ? - ) ks ON (ks.person_id = mm.person_id) - LEFT JOIN ( - SELECT person_id, kontakt FROM public.tbl_kontakt WHERE kontakttyp = ? - ) kr ON (kr.person_id = mr.person_id) - LEFT JOIN ( - SELECT b.person_id, - m.mitarbeiter_uid - FROM public.tbl_benutzer b INNER JOIN public.tbl_mitarbeiter m ON(b.uid = m.mitarbeiter_uid) - WHERE b.aktiv = TRUE - ) mu ON (mu.person_id = mr.person_id) - LEFT JOIN ( - SELECT b.person_id, - m.mitarbeiter_uid - FROM public.tbl_benutzer b INNER JOIN public.tbl_mitarbeiter m ON(b.uid = m.mitarbeiter_uid) - WHERE b.aktiv = TRUE - ) ms ON (ms.person_id = mm.person_id)'; + $query = 'SELECT mm.message_id + FROM public.tbl_msg_recipient mr + JOIN public.tbl_msg_message mm USING (message_id) + WHERE mr.sent IS NULL + AND mr.sentinfo IS NULL + AND mm.insertamum > ? + ORDER BY mr.insertamum ASC + LIMIT ?'; - $parametersArray = array($kontaktType, $kontaktType); - - if (is_null($sent) || $sent == '') - { - $query .= ' WHERE mr.sent IS NULL'; - } - else - { - array_push($parametersArray, $sent); - $query .= ' WHERE mr.sent = ?'; - } - - if (!is_null($message_id)) - { - array_push($parametersArray, $message_id); - $query .= ' AND mm.message_id = ?'; - } - - $query .= ' ORDER BY mr.insertamum ASC'; - - if (!is_null($limit)) - { - $query .= ' LIMIT ?'; - array_push($parametersArray, $limit); - } - - return $this->execQuery($query, $parametersArray); + return $this->execQuery($query, array($since, $limit)); } /** @@ -307,4 +260,137 @@ class Recipient_model extends DB_Model return $this->execQuery($sql, $parametersArray); } + + /** + * - Gets the directly recieved messages using the given person id + * - Gets the recieved messages from an organisation unit where this person plays a role given by the parameter functions + */ + public function getReceivedMessages($person_id, $functions) + { + $sql = '-- Messages sent directly to the person + SELECT mr.message_id, + mm.relationmessage_id, + mm.subject, + mm.body, + mm.insertamum AS sent, + p.vorname, + p.nachname, + MAX(ms.status) AS status, + ms.person_id AS statusPersonId, + mr.token + FROM public.tbl_msg_recipient mr + JOIN public.tbl_msg_message mm ON (mm.message_id = mr.message_id) + JOIN public.tbl_msg_status ms ON (ms.message_id = mr.message_id AND ms.person_id = mr.person_id) + JOIN public.tbl_person p ON (p.person_id = mm.person_id) + WHERE mr.person_id = ? + GROUP BY mr.message_id, + mm.relationmessage_id, + mm.subject, + mm.body, + mm.insertamum, + p.vorname, + p.nachname, + ms.person_id, + mr.token + UNION + -- Messages sent to a person that belongs to the recipient organisation unit + SELECT mrou.message_id, + mm.relationmessage_id, + mm.subject, + mm.body, + mm.insertamum AS sent, + pr.vorname, + pr.nachname, + MAX(ms.status) AS status, + ms.person_id AS statusPersonId, + mrou.token + FROM public.tbl_person p + JOIN public.tbl_benutzer b ON (b.person_id = p.person_id) + JOIN ( + SELECT uid, oe_kurzbz + FROM public.tbl_benutzerfunktion + WHERE (datum_von IS NULL OR datum_von <= NOW()) + AND (datum_bis IS NULL OR datum_bis >= NOW()) + AND funktion_kurzbz IN ? + ) bf ON (bf.uid = b.uid) + JOIN public.tbl_msg_recipient mrou ON (mrou.oe_kurzbz = bf.oe_kurzbz) + JOIN public.tbl_msg_message mm ON (mm.message_id = mrou.message_id) + JOIN public.tbl_msg_status ms ON (ms.message_id = mrou.message_id AND ms.person_id = mrou.person_id) + JOIN public.tbl_person pr ON (pr.person_id = mm.person_id) + WHERE p.person_id = ? + GROUP BY mrou.message_id, + mm.relationmessage_id, + mm.subject, + mm.body, + mm.insertamum, + pr.vorname, + pr.nachname, + ms.person_id, + mrou.token + ORDER BY sent DESC'; + + return $this->execQuery($sql, array($person_id, $functions, $person_id)); + } + + /** + * Gets all the sent message by the given person + */ + public function getSentMessages($person_id) + { + $sql = 'SELECT mm.message_id, + mm.relationmessage_id, + mm.subject, + mm.body, + mm.insertamum AS sent, + p.person_id, + p.vorname, + p.nachname, + MAX(ms.status) AS status, + ms.person_id AS statusPersonId, + oe.bezeichnung AS oe, + mr.token + FROM public.tbl_msg_message mm + JOIN public.tbl_msg_recipient mr ON (mr.message_id = mm.message_id) + JOIN public.tbl_msg_status ms ON (ms.message_id = mm.message_id AND ms.person_id = mr.person_id) + JOIN public.tbl_person p ON (p.person_id = mr.person_id) + LEFT JOIN public.tbl_organisationseinheit oe ON (oe.oe_kurzbz = mr.oe_kurzbz) + WHERE mm.person_id = ? + GROUP BY mm.message_id, + mm.relationmessage_id, + mm.subject, + mm.body, + mm.insertamum, + p.person_id, + p.vorname, + p.nachname, + ms.person_id, + oe.bezeichnung, + mr.token + ORDER BY sent DESC'; + + return $this->execQuery($sql, array($person_id)); + } + + /** + * + */ + public function getMessagesById($messageIds) + { + $sql = 'SELECT mm.message_id, + mm.person_id AS sender_id, + mm.subject, + mm.body, + mm.relationmessage_id, + mm.oe_kurzbz AS sender_ou, + mr.person_id AS receiver_id, + mr.token, + mr.sent, + mr.sentinfo, + mr.oe_kurzbz AS receiver_ou + FROM public.tbl_msg_message mm + JOIN public.tbl_msg_recipient mr ON (mr.message_id = mm.message_id) + WHERE mm.message_id IN ?'; + + return $this->execQuery($sql, array($messageIds)); + } } diff --git a/application/views/crm/statusEdit.php b/application/views/crm/statusEdit.php index 5fee3ee92..5f0353acf 100644 --- a/application/views/crm/statusEdit.php +++ b/application/views/crm/statusEdit.php @@ -1,89 +1,89 @@ -load->view('templates/header', array('title' => 'StatusEdit')); - - $s = $status; -?> - -
-
-

Status: status_kurzbz; ?>

-
- - - - - - - - - - - - - - - - - - - - - - -
- beschreibung:

-
-
-   -
- Anmerkung:

-
-
-   -
- Bezeichnung mehrsprachig:

- - - - - sprache; ?>:
- bezeichnung_mehrsprachig[$i])) - { - $val = ''; - } - else - { - $val = $s->bezeichnung_mehrsprachig[$i]; - } - $i++; - ?> -
- - -
-   -
- -
- -
-
-
- - - - - - - +load->view('templates/header', array('title' => 'StatusEdit')); + + $s = $status; +?> + +
+
+

Status: status_kurzbz; ?>

+
+ + + + + + + + + + + + + + + + + + + + + + +
+ beschreibung:

+
+
+   +
+ Anmerkung:

+
+
+   +
+ Bezeichnung mehrsprachig:

+ + + + + sprache; ?>:
+ bezeichnung_mehrsprachig[$i])) + { + $val = ''; + } + else + { + $val = $s->bezeichnung_mehrsprachig[$i]; + } + $i++; + ?> +
+ + +
+   +
+ +
+ +
+
+
+ + + + + + + diff --git a/application/views/crm/statusgrund.php b/application/views/crm/statusgrund.php index e79fa5d05..d4a31aa53 100644 --- a/application/views/crm/statusgrund.php +++ b/application/views/crm/statusgrund.php @@ -1,32 +1,32 @@ - - - - - VileSci - Statusgrund - - - - - - - <body bgcolor="#FFFFFF"> - This application works only with a frames-enabled browser.<br /> - </body> - - - - - <body bgcolor="#FFFFFF"> - This application works only with a frames-enabled browser.<br /> - </body> - - - - <body bgcolor="#FFFFFF"> - This application works only with a frames-enabled browser.<br /> - </body> - - - - - + + + + + VileSci - Statusgrund + + + + + + + <body bgcolor="#FFFFFF"> + This application works only with a frames-enabled browser.<br /> + </body> + + + + + <body bgcolor="#FFFFFF"> + This application works only with a frames-enabled browser.<br /> + </body> + + + + <body bgcolor="#FFFFFF"> + This application works only with a frames-enabled browser.<br /> + </body> + + + + + diff --git a/application/views/crm/statusgrundEdit.php b/application/views/crm/statusgrundEdit.php index ddbd1ff0a..9fa91b6d5 100644 --- a/application/views/crm/statusgrundEdit.php +++ b/application/views/crm/statusgrundEdit.php @@ -1,107 +1,107 @@ -load->view('templates/header', array('title' => 'StatusgrundEdit')); - - $sg = $statusgrund; -?> - -
-
-

Statusgrund: status_kurzbz; ?>

-
"> - - - - - - - - - - - - - - - - - - - - - - - -
- Bezeichnung mehrsprachig:

- - - sprache; ?>:
- bezeichnung_mehrsprachig[$i])) - { - $val = ""; - } - else - { - $val = $sg->bezeichnung_mehrsprachig[$i]; - } - $i++; - ?> -
- - -
-   -
- Beschreibung:

- - - sprache; ?>:
- beschreibung[$i])) - { - $val = ""; - } - else - { - $val = $sg->beschreibung[$i]; - } - $i++; - ?> -
- -
-   -
- Aktiv: - - aktiv) && $sg->aktiv === true ? "checked" : ""; ?> /> -
-   -
- -
- " /> -
-
-
- - - - - - - +load->view('templates/header', array('title' => 'StatusgrundEdit')); + + $sg = $statusgrund; +?> + +
+
+

Statusgrund: status_kurzbz; ?>

+
"> + + + + + + + + + + + + + + + + + + + + + + + +
+ Bezeichnung mehrsprachig:

+ + + sprache; ?>:
+ bezeichnung_mehrsprachig[$i])) + { + $val = ""; + } + else + { + $val = $sg->bezeichnung_mehrsprachig[$i]; + } + $i++; + ?> +
+ + +
+   +
+ Beschreibung:

+ + + sprache; ?>:
+ beschreibung[$i])) + { + $val = ""; + } + else + { + $val = $sg->beschreibung[$i]; + } + $i++; + ?> +
+ +
+   +
+ Aktiv: + + aktiv) && $sg->aktiv === true ? "checked" : ""; ?> /> +
+   +
+ +
+ " /> +
+
+
+ + + + + + + diff --git a/application/views/crm/statusgrundNew.php b/application/views/crm/statusgrundNew.php index bd2ebe7d7..ffcd18429 100644 --- a/application/views/crm/statusgrundNew.php +++ b/application/views/crm/statusgrundNew.php @@ -1,66 +1,66 @@ -load->view('templates/header', array('title' => 'StatusgrundNew')); -?> - -
-
-

Neuer Statusgrund

-
"> - - - - - - - - - - - - - - - - - - - - - - - -
- Bezeichnung mehrsprachig:

- - - sprache; ?>:
-
- - -
-   -
- Beschreibung:

- - - sprache; ?>:
-
- -
-   -
- Aktiv: - - -
-   -
- -
- -
-
-
- - - +load->view('templates/header', array('title' => 'StatusgrundNew')); +?> + +
+
+

Neuer Statusgrund

+
"> + + + + + + + + + + + + + + + + + + + + + + + +
+ Bezeichnung mehrsprachig:

+ + + sprache; ?>:
+
+ + +
+   +
+ Beschreibung:

+ + + sprache; ?>:
+
+ +
+   +
+ Aktiv: + + +
+   +
+ +
+ +
+
+
+ + + diff --git a/application/views/lehre/lehrauftrag/acceptLehrauftrag.php b/application/views/lehre/lehrauftrag/acceptLehrauftrag.php index 14ebacecb..a4116e8d0 100644 --- a/application/views/lehre/lehrauftrag/acceptLehrauftrag.php +++ b/application/views/lehre/lehrauftrag/acceptLehrauftrag.php @@ -69,13 +69,11 @@ $this->load->view( - - @@ -148,9 +146,6 @@ $this->load->view( - @@ -166,12 +161,13 @@ $this->load->view(
-
- - - - -
+
+ + + + + +

@@ -195,7 +191,7 @@ $this->load->view(
- +
diff --git a/application/views/lehre/lehrauftrag/acceptLehrauftragData.php b/application/views/lehre/lehrauftrag/acceptLehrauftragData.php index 2a9cc4245..6ac3abbdc 100644 --- a/application/views/lehre/lehrauftrag/acceptLehrauftragData.php +++ b/application/views/lehre/lehrauftrag/acceptLehrauftragData.php @@ -170,7 +170,7 @@ FROM /* filter active organisationseinheiten */ AND oe.aktiv = TRUE /* filter vertragsstatus to avoid showing before status is bestellt */ - AND vvs.vertragsstatus_kurzbz IN (\'bestellt\', \'erteilt\', \'akzeptiert\') + AND vvs.vertragsstatus_kurzbz IN (\'erteilt\', \'akzeptiert\') ) tmp_lehrauftraege UNION @@ -182,8 +182,8 @@ FROM (SELECT uid FROM - public.tbl_benutzer JOIN public.tbl_mitarbeiter ma - ON tbl_benutzer.uid = ma.mitarbeiter_uid + public.tbl_benutzer JOIN public.tbl_mitarbeiter ma + ON tbl_benutzer.uid = ma.mitarbeiter_uid WHERE person_id = tmp_projektbetreuung.person_id ORDER BY aktiv DESC, updateaktivam DESC -- accept inactive as some person_ids have no active, but order them last @@ -285,8 +285,8 @@ FROM AND lv.aktiv = TRUE /* filter active organisationseinheiten */ AND oe.aktiv = TRUE - /* filter vertragsstatus to avoid showing before status is bestellt */ - AND vvs.vertragsstatus_kurzbz IN (\'bestellt\', \'erteilt\', \'akzeptiert\') + /* filter vertragsstatus to avoid showing before status is erteilt */ + AND vvs.vertragsstatus_kurzbz IN (\'erteilt\', \'akzeptiert\') ) tmp_projektbetreuung ) auftraege ORDER BY "akzeptiert" NULLS FIRST, "erteilt" NULLS LAST, "bestellt" diff --git a/application/views/system/fas_udf.php b/application/views/system/fas_udf.php index d4a01b9e9..3efc61abc 100644 --- a/application/views/system/fas_udf.php +++ b/application/views/system/fas_udf.php @@ -1,150 +1,150 @@ -load->view("templates/header", array("title" => "UDF", "widgetsCSS" => true)); ?> - - - - -
- Saved! -
- -
- -
- Error while saving! -
-
-
-retval; - if(is_array($errors)) - { - foreach ($errors as $error) - { - foreach ($error as $fieldError) - { - echo $fieldError->code . ': ' . $fieldError->retval . '
'; - } - } - } - else - echo $result->retval; -?> -
- -
-
-
- - - -
-
-
- Zusatzfelder -
-
-
-
-   -
-
-
- -
- udflib->UDFWidget( - array( - UDFLib::SCHEMA_ARG_NAME => 'public', - UDFLib::TABLE_ARG_NAME => 'tbl_person', - UDFLib::UDFS_ARG_NAME => $personUdfs - ) - ); - ?> -
-
-   -
- - -
- udflib->UDFWidget( - array( - UDFLib::SCHEMA_ARG_NAME => 'public', - UDFLib::TABLE_ARG_NAME => 'tbl_prestudent', - UDFLib::UDFS_ARG_NAME => $prestudentUdfs - ) - ); - ?> -
- -
-
-
-   -
-
-
- -
-   -
-
-   -
- -
- -
-
-
- - - - - - - - - - - - -load->view("templates/footer"); ?> +load->view("templates/header", array("title" => "UDF", "widgetsCSS" => true)); ?> + + + + +
+ Saved! +
+ +
+ +
+ Error while saving! +
+
+
+retval; + if(is_array($errors)) + { + foreach ($errors as $error) + { + foreach ($error as $fieldError) + { + echo $fieldError->code . ': ' . $fieldError->retval . '
'; + } + } + } + else + echo $result->retval; +?> +
+ +
+
+
+ + + +
+
+
+ Zusatzfelder +
+
+
+
+   +
+
+
+ +
+ udflib->UDFWidget( + array( + UDFLib::SCHEMA_ARG_NAME => 'public', + UDFLib::TABLE_ARG_NAME => 'tbl_person', + UDFLib::UDFS_ARG_NAME => $personUdfs + ) + ); + ?> +
+
+   +
+ + +
+ udflib->UDFWidget( + array( + UDFLib::SCHEMA_ARG_NAME => 'public', + UDFLib::TABLE_ARG_NAME => 'tbl_prestudent', + UDFLib::UDFS_ARG_NAME => $prestudentUdfs + ) + ); + ?> +
+ +
+
+
+   +
+
+
+ +
+   +
+
+   +
+ +
+ +
+
+
+ + + + + + + + + + + + +load->view("templates/footer"); ?> diff --git a/application/views/system/infocenter/infocenterDetails.php b/application/views/system/infocenter/infocenterDetails.php index ab4e3533e..11b8ef094 100644 --- a/application/views/system/infocenter/infocenterDetails.php +++ b/application/views/system/infocenter/infocenterDetails.php @@ -22,7 +22,7 @@ 'customJSs' => array( 'public/js/bootstrapper.js', 'public/js/tablesort/tablesort.js', - 'public/js/messaging/messageList.js', + 'public/js/infocenter/messageList.js', 'public/js/infocenter/infocenterDetails.js' ), 'phrases' => array( @@ -154,7 +154,7 @@
load->view('system/messages/messageList.php', $messages); + $this->load->view('system/infocenter/messageList.php', $messages); ?>
diff --git a/application/views/system/infocenter/logs.php b/application/views/system/infocenter/logs.php index de97d5055..8005bf4f7 100644 --- a/application/views/system/infocenter/logs.php +++ b/application/views/system/infocenter/logs.php @@ -1,19 +1,19 @@ -
Alle
Alle Lehraufträge mit jedem Status
Bestellt
Nur bestellte UND bestellte Lehraufträge, die in Bearbeitung sind
Erteilt
Nur erteilte UND geänderte Lehraufträge, die in Bearbeitung sind
Angenommen
Nur von Ihnen angenommene Lehraufträge
- - - - - - - - - - - - - - - - +
p->t('global', 'datum')) ?>p->t('global', 'aktivitaet')) ?>User
zeitpunkt), 'd.m.Y H:i:s') ?>logdata->name) ? $log->logdata->name : '' ?>insertvon ?>
+ + + + + + + + + + + + + + + +
p->t('global', 'datum')) ?>p->t('global', 'aktivitaet')) ?>User
zeitpunkt), 'd.m.Y H:i:s') ?>logdata->name) ? $log->logdata->name : '' ?>insertvon ?>
\ No newline at end of file diff --git a/application/views/system/messages/messageList.php b/application/views/system/infocenter/messageList.php similarity index 97% rename from application/views/system/messages/messageList.php rename to application/views/system/infocenter/messageList.php index d666e32fe..18b859314 100644 --- a/application/views/system/messages/messageList.php +++ b/application/views/system/infocenter/messageList.php @@ -1,37 +1,37 @@ - 0; -$widthColumn = $msgExists === true ? 8 : 12; -?> -
- - - - - - - - - - - - - - - - - - - - - -
p->t('global','gesendetAm')) ?>p->t('global','sender')) ?>p->t('global','empfaenger')) ?>p->t('global','betreff')) ?>p->t('global','gelesenAm')) ?>
insertamum) ? date_format(date_create($message->insertamum), 'd.m.Y H:i:s') : '' ?>sevorname.' '.$message->senachname ?>revorname.' '.$message->renachname ?>subject ?>statusamum) ? date_format(date_create($message->statusamum), 'd.m.Y H:i:s') : '' ?>
-
- -
-
-
-
- -
-
- + 0; +$widthColumn = $msgExists === true ? 8 : 12; +?> +
+ + + + + + + + + + + + + + + + + + + + + +
p->t('global','gesendetAm')) ?>p->t('global','sender')) ?>p->t('global','empfaenger')) ?>p->t('global','betreff')) ?>p->t('global','gelesenAm')) ?>
insertamum) ? date_format(date_create($message->insertamum), 'd.m.Y H:i:s') : '' ?>sevorname.' '.$message->senachname ?>revorname.' '.$message->renachname ?>subject ?>statusamum) ? date_format(date_create($message->statusamum), 'd.m.Y H:i:s') : '' ?>
+
+ +
+
+
+
+ +
+
+ diff --git a/application/views/system/infocenter/notizen.php b/application/views/system/infocenter/notizen.php index 13f7bb6e1..b28f7939a 100644 --- a/application/views/system/infocenter/notizen.php +++ b/application/views/system/infocenter/notizen.php @@ -1,20 +1,20 @@ - - - - - - - - - - - - - - - - - - +
p->t('global', 'datum')) ?>p->t('global', 'notiz')) ?>User
insertamum), 'd.m.Y H:i:s') ?>titel) ?>verfasser_uid ?>
+ + + + + + + + + + + + + + + + +
p->t('global', 'datum')) ?>p->t('global', 'notiz')) ?>User
insertamum), 'd.m.Y H:i:s') ?>titel) ?>verfasser_uid ?>
\ No newline at end of file diff --git a/application/views/system/infocenter/stammdaten.php b/application/views/system/infocenter/stammdaten.php index 2b481692e..a80439bfe 100644 --- a/application/views/system/infocenter/stammdaten.php +++ b/application/views/system/infocenter/stammdaten.php @@ -113,7 +113,7 @@
-
+  p->t('ui','nachrichtSenden'); ?> diff --git a/application/views/system/messages/ajaxRead.php b/application/views/system/messages/ajaxRead.php new file mode 100644 index 000000000..1ed1b7f40 --- /dev/null +++ b/application/views/system/messages/ajaxRead.php @@ -0,0 +1,61 @@ +load->view( + 'templates/FHC-Header', + array( + 'title' => 'Read personal messages', + 'jquery' => true, + 'jqueryui' => true, + 'bootstrap' => true, + 'fontawesome' => true, + 'sbadmintemplate' => true, + 'momentjs' => true, + 'tabulator' => true, + 'ajaxlib' => true, + 'dialoglib' => true, + 'tinymce' => true, + 'phrases' => array('global', 'ui'), + 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/message.css'), + 'customJSs' => array('public/js/bootstrapper.js', 'public/js/messaging/read.js') + ) + ); +?> + + +
+ + + + + + + + + + + + + + + + + + + +
+ + +
+ +
+ + + +load->view("templates/FHC-Footer"); ?> diff --git a/application/views/system/messages/ajaxWrite.php b/application/views/system/messages/ajaxWrite.php new file mode 100644 index 000000000..fe9b9e897 --- /dev/null +++ b/application/views/system/messages/ajaxWrite.php @@ -0,0 +1,100 @@ +load->view( + 'templates/FHC-Header', + array( + 'title' => 'Write a new message', + 'jquery' => true, + 'jqueryui' => true, + 'bootstrap' => true, + 'fontawesome' => true, + 'sbadmintemplate' => true, + 'ajaxlib' => true, + 'dialoglib' => true, + 'tinymce' => true, + 'phrases' => array('global', 'ui'), + 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/message.css'), + 'customJSs' => array('public/js/bootstrapper.js', 'public/js/messaging/write.js') + ) + ); +?> + +
+
+
+
+
+ +
+
+
+
+
+ +
+
+ +
+
+
+
+
+
+ +
+   +
+ +
+
+
+
+
+
+ + + +
+ +
+ + p->t('ui', 'altRecipientNote'); ?> + +
+
+
+
+
+
+ +
+
+
+
+
+ + +load->view("templates/FHC-Footer"); ?> diff --git a/application/views/system/messages/ajaxWriteReply.php b/application/views/system/messages/ajaxWriteReply.php new file mode 100644 index 000000000..3721565e9 --- /dev/null +++ b/application/views/system/messages/ajaxWriteReply.php @@ -0,0 +1,101 @@ +load->view( + 'templates/FHC-Header', + array( + 'title' => 'Reply to a message', + 'jquery' => true, + 'jqueryui' => true, + 'bootstrap' => true, + 'fontawesome' => true, + 'sbadmintemplate' => true, + 'ajaxlib' => true, + 'dialoglib' => true, + 'tinymce' => true, + 'phrases' => array('global', 'ui'), + 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/message.css'), + 'customJSs' => array('public/js/bootstrapper.js', 'public/js/messaging/writeReply.js') + ) + ); +?> + +
+
+
+
+
+ +
+
+
+
+
+ +
+
+ + + +
+
+
+
+
+
+ +
+   +
+ + + +
+
+
+
+
+
+ + +
+
+
+
+
+ + + + + + +
+
+
+
+
+ + +load->view("templates/FHC-Footer"); ?> diff --git a/application/views/system/messages/messageReplySent.php b/application/views/system/messages/htmlMessageSentError.php similarity index 59% rename from application/views/system/messages/messageReplySent.php rename to application/views/system/messages/htmlMessageSentError.php index 88fc945b0..90191fcf0 100644 --- a/application/views/system/messages/messageReplySent.php +++ b/application/views/system/messages/htmlMessageSentError.php @@ -2,12 +2,12 @@ $this->load->view( 'templates/FHC-Header', array( - 'title' => 'MessageSent', + 'title' => 'Message sent failure - Fehler beim Senden der Nachricht', 'jquery' => true, 'bootstrap' => true, 'fontawesome' => true, 'sbadmintemplate' => true, - 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/messageSent.css') + 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/message.css') ) ); ?> @@ -20,47 +20,31 @@
- +
- +
+
- Message sent successfully! + An error occurred while sending your message, please try later.
- Nachricht erfolgreich versandt! + Beim Senden Ihrer Nachricht ist ein Fehler aufgetreten. Bitte versuchen Sie es später erneut.
+
-
-
- - Thank you for your message. - - - We will get back to you shortly. - -
-
- - Herzlichen Dank für Ihre Nachricht. - - - Wir werden uns schnellstmöglich um Ihr Anliegen kümmern. - -
-

@@ -72,18 +56,12 @@ Sie können dieses Fenster schließen.
+
-
-
- Your InfoCenter@FHTW Team -
-
- Ihr InfoCenter@FHTW Team -
-
-
+
+

@@ -93,6 +71,7 @@

+
diff --git a/application/views/system/messages/messageSent.php b/application/views/system/messages/htmlMessageSentSuccess.php similarity index 92% rename from application/views/system/messages/messageSent.php rename to application/views/system/messages/htmlMessageSentSuccess.php index 674ccd5a0..48409a5f4 100644 --- a/application/views/system/messages/messageSent.php +++ b/application/views/system/messages/htmlMessageSentSuccess.php @@ -2,12 +2,12 @@ $this->load->view( 'templates/FHC-Header', array( - 'title' => 'MessageSent', + 'title' => 'Message sent successfully - Nachricht erfolgreich versandt!', 'jquery' => true, 'bootstrap' => true, 'fontawesome' => true, 'sbadmintemplate' => true, - 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/messageSent.css') + 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/message.css') ) ); ?> @@ -17,11 +17,6 @@
- -
@@ -79,11 +74,6 @@
- - -
diff --git a/application/views/system/messages/messageHTML.php b/application/views/system/messages/htmlRead.php similarity index 65% rename from application/views/system/messages/messageHTML.php rename to application/views/system/messages/htmlRead.php index 0ae6c3866..5413af9f4 100644 --- a/application/views/system/messages/messageHTML.php +++ b/application/views/system/messages/htmlRead.php @@ -1,75 +1,104 @@ - load->view( - 'templates/FHC-Header', - array( - 'title' => 'MessageSent', - 'jquery' => true, - 'bootstrap' => true, - 'fontawesome' => true, - 'sbadmintemplate' => true, - 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/messageReply.css') - ) - ); - ?> - -
-
-
-
-
- -
-
-
-
-
-
- subject; ?> -
-
- - - - - - - - - - - - - -
- From: - - vorname.' '.$sender->nachname; ?> -
- Subject: - - subject; ?> -
- Message: - - body; ?> -
-
- -
-
-
-
-
-
- - load->view("templates/FHC-Footer"); ?> \ No newline at end of file +load->view( + 'templates/FHC-Header', + array( + 'title' => 'Read message - Lies die Nachricht', + 'jquery' => true, + 'bootstrap' => true, + 'fontawesome' => true, + 'sbadmintemplate' => true, + 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/message.css') + ) + ); +?> + +
+
+
+
+
+ +
+
+
+
+
+
+ + subject; ?> + +
+
+ + + + + + + + + + + + + +
+ + + p->t('ui', 'from')); ?>: + + + + + vorname.' '.$sender->nachname; ?> + +
+ + + p->t('global', 'betreff')); ?>: + + + + + subject; ?> + +
+ + + p->t('global', 'nachricht')); ?>: + + + + + body; ?> + +
+
+ +
+
+
+
+
+
+ + +load->view("templates/FHC-Footer"); ?> diff --git a/application/views/system/messages/htmlWriteReply.php b/application/views/system/messages/htmlWriteReply.php new file mode 100644 index 000000000..fa3390bfa --- /dev/null +++ b/application/views/system/messages/htmlWriteReply.php @@ -0,0 +1,93 @@ +load->view( + 'templates/FHC-Header', + array( + 'title' => 'Reply to a message', + 'jquery' => true, + 'bootstrap' => true, + 'fontawesome' => true, + 'tinymce' => true, + 'sbadmintemplate' => true, + 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/message.css'), + 'customJSs' => array('public/js/bootstrapper.js', 'public/js/messaging/messageWriteReply.js') + ) + ); +?> + +
+
+
+
+
+ +
+
+ +
+
+
+ +
+
+ + + +
+
+
+
+
+
+ +
+   +
+ +
+
+
+
+
+
+ + +
+
+
+
+
+ +
+
+ + + + + + +
+
+
+ + +load->view("templates/FHC-Footer"); ?> diff --git a/application/views/system/messages/htmlWriteTemplate.php b/application/views/system/messages/htmlWriteTemplate.php new file mode 100644 index 000000000..b6876dc91 --- /dev/null +++ b/application/views/system/messages/htmlWriteTemplate.php @@ -0,0 +1,170 @@ +load->view( + 'templates/FHC-Header', + array( + 'title' => 'Write a new message or reply using templates', + 'jquery' => true, + 'jqueryui' => true, + 'bootstrap' => true, + 'ajaxlib' => true, + 'fontawesome' => true, + 'tinymce' => true, + 'sbadmintemplate' => true, + 'dialoglib' => true, + 'widgets' => true, + 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/message.css'), + 'customJSs' => array('public/js/bootstrapper.js', 'public/js/messaging/messageWrite.js') + ) + ); +?> + +
+ + +load->view("templates/FHC-Footer"); ?> diff --git a/application/views/system/messages/messageForm.php b/application/views/system/messages/messageForm.php deleted file mode 100644 index d1436a492..000000000 --- a/application/views/system/messages/messageForm.php +++ /dev/null @@ -1,81 +0,0 @@ -
-
-
- -
-
- 1 && $i % 10 == 0) - { - echo '
'; - } - echo $receiver->Vorname." ".$receiver->Nachname."; "; - } - ?> -
-
-
-
-
-
- -
  - subject; - } - ?> -
- -
-
-
-
-
-
- -

On '.date_format(date_create($message->sent), 'd.m.Y H:i').' '.$receivers[0]->Vorname.' '.$receivers[0]->Nachname.' wrote:'.'
'; - $body .= '
'; - $body .= $message->body.'
'; - } - ?> - -
- -
-
- - -
-
- -
-
-
-
- -
-
\ No newline at end of file diff --git a/application/views/system/messages/messageWrite.php b/application/views/system/messages/messageWrite.php deleted file mode 100644 index 93caaf861..000000000 --- a/application/views/system/messages/messageWrite.php +++ /dev/null @@ -1,183 +0,0 @@ -load->view( - 'templates/FHC-Header', - array( - 'title' => 'Write a message', - 'jquery' => true, - 'jqueryui' => true, - 'bootstrap' => true, - 'ajaxlib' => true, - 'fontawesome' => true, - 'tinymce' => true, - 'sbadmintemplate' => true, - 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/messageWrite.css'), - 'customJSs' => array('public/js/bootstrapper.js', 'public/js/messaging/messageWrite.js') - ) -); -?> - -
- - -load->view("templates/FHC-Footer"); ?> diff --git a/application/views/system/messages/messageWriteReply.php b/application/views/system/messages/messageWriteReply.php deleted file mode 100644 index 344871b2d..000000000 --- a/application/views/system/messages/messageWriteReply.php +++ /dev/null @@ -1,63 +0,0 @@ -load->view( - 'templates/FHC-Header', - array( - 'title' => 'MessageReply', - 'jquery' => true, - 'bootstrap' => true, - 'fontawesome' => true, - 'tinymce' => true, - 'sbadmintemplate' => true, - 'customCSSs' => array('public/css/sbadmin2/admintemplate_contentonly.css', 'public/css/messaging/messageWrite.css'), - 'customJSs' => array('public/js/bootstrapper.js', 'public/js/messaging/messageWriteReply.js') - ) -); -?> - - -
-
-
-
-
- -
-
-
- load->view('system/messages/messageForm.php'); - - for ($i = 0; $i < count($receivers); $i++) - { - $receiver = $receivers[$i]; - $receiverid = $receiver->person_id; - $fieldname = 'persons[]'; - - echo ''."\n"; - } - ?> - - - - - - - -
-
-
-
- - -load->view("templates/FHC-Footer"); ?> diff --git a/application/views/system/phrases/phrases.php b/application/views/system/phrases/phrases.php index 2409fcc83..f884cd04e 100644 --- a/application/views/system/phrases/phrases.php +++ b/application/views/system/phrases/phrases.php @@ -1,20 +1,20 @@ - - - - - VileSci - Phrasen - - - - - - - - <body bgcolor="#FFFFFF"> - This application works only with a frames-enabled browser.<br /> - <a href="PhrasesList">Use without frames</a> - </body> - - - - + + + + + VileSci - Phrasen + + + + + + + + <body bgcolor="#FFFFFF"> + This application works only with a frames-enabled browser.<br /> + <a href="PhrasesList">Use without frames</a> + </body> + + + + diff --git a/application/views/system/phrases/phrasesEdit.php b/application/views/system/phrases/phrasesEdit.php index d967dee83..19710b957 100644 --- a/application/views/system/phrases/phrasesEdit.php +++ b/application/views/system/phrases/phrasesEdit.php @@ -1,17 +1,17 @@ -load->view('templates/header', array('title' => 'PhrasesEdit')); -?> -
-
-

Phrase: phrase_id; ?>

-
- Bezeichnung: - - -
- -
-
- - - +load->view('templates/header', array('title' => 'PhrasesEdit')); +?> +
+
+

Phrase: phrase_id; ?>

+
+ Bezeichnung: + + +
+ +
+
+ + + diff --git a/application/views/system/phrases/phrasesinhaltList.php b/application/views/system/phrases/phrasesinhaltList.php index f212d440f..5f496a503 100644 --- a/application/views/system/phrases/phrasesinhaltList.php +++ b/application/views/system/phrases/phrasesinhaltList.php @@ -1,54 +1,54 @@ -load->view('templates/header', array('title' => 'PhrasenInhaltList', 'tablesort' => true, 'tableid' => 't1', 'headers' => '5:{sorter:false}')); -?> - -
-
-

Phrase Inhalt -

-
- - -
- - - - - - - - - - - - - - - - - - - - - - - - - - -
IDSpracheOrgEinheitOrgFormTextBeschreibung
phrasentext_id; ?>sprache; ?>orgeinheit_kurzbz; ?>orgform_kurzbz; ?>text; ?>description; ?>edit - delete -
-
-
- - -load->view('templates/footer'); -?> +load->view('templates/header', array('title' => 'PhrasenInhaltList', 'tablesort' => true, 'tableid' => 't1', 'headers' => '5:{sorter:false}')); +?> + +
+
+

Phrase Inhalt -

+
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
IDSpracheOrgEinheitOrgFormTextBeschreibung
phrasentext_id; ?>sprache; ?>orgeinheit_kurzbz; ?>orgform_kurzbz; ?>text; ?>description; ?>edit + delete +
+
+
+ + +load->view('templates/footer'); +?> diff --git a/application/views/system/vorlage/templates.php b/application/views/system/vorlage/templates.php index c2130c267..7767962ce 100644 --- a/application/views/system/vorlage/templates.php +++ b/application/views/system/vorlage/templates.php @@ -1,20 +1,20 @@ - - - - - VileSci - Vorlage - - - - - - - - <body bgcolor="#FFFFFF"> - This application works only with a frames-enabled browser.<br /> - <a href="VorlageList">Use without frames</a> - </body> - - - - + + + + + VileSci - Vorlage + + + + + + + + <body bgcolor="#FFFFFF"> + This application works only with a frames-enabled browser.<br /> + <a href="VorlageList">Use without frames</a> + </body> + + + + diff --git a/application/views/system/vorlage/templatetextPreview.php b/application/views/system/vorlage/templatetextPreview.php index 2f53868a9..1f5b6948d 100644 --- a/application/views/system/vorlage/templatetextPreview.php +++ b/application/views/system/vorlage/templatetextPreview.php @@ -1,3 +1,3 @@ - \ No newline at end of file diff --git a/application/views/templates/FHC-Header.php b/application/views/templates/FHC-Header.php index 03ee011b7..5eec10f43 100644 --- a/application/views/templates/FHC-Header.php +++ b/application/views/templates/FHC-Header.php @@ -34,6 +34,7 @@ $tablewidget = isset($tablewidget) ? $tablewidget : false; $tabulator = isset($tabulator) ? $tabulator : false; $tinymce = isset($tinymce) ? $tinymce : false; + $widgets = isset($widgets) ? $widgets : false; ?> @@ -63,6 +64,9 @@ // Font Awesome CSS if ($fontawesome === true) generateCSSsInclude('vendor/components/font-awesome/css/font-awesome.min.css'); + // PivotUI CSS + if ($pivotui === true) generateCSSsInclude('vendor/nicolaskruchten/pivottable/dist/pivot.min.css'); + // SB Admin 2 template CSS if ($sbadmintemplate === true) { @@ -73,12 +77,6 @@ // Securimage CSS if ($captcha === true) generateCSSsInclude('vendor/dapphp/securimage/securimage.css'); - // PivotUI CSS - if ($pivotui === true) - { - generateCSSsInclude('vendor/nicolaskruchten/pivottable/dist/pivot.min.css'); - } - // Table sorter CSS if ($tablesorter === true) { @@ -93,6 +91,9 @@ generateCSSsInclude('public/css/Tabulator.css'); } + // Tinymce CSS + if ($tinymce === true) generateCSSsInclude('public/css/TinyMCE.css'); + // -------------------------------------------------------------------------------------------------------- // From public folder @@ -108,11 +109,12 @@ // NavigationWidget CSS if ($navigationwidget === true) generateCSSsInclude('public/css/NavigationWidget.css'); + // HTML Widget CSS + if ($widgets === true) generateCSSsInclude('public/css/Widgets.css'); + // Eventually required CSS generateCSSsInclude($customCSSs); // Eventually required CSS - // CSS End - // -------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------- // Javascripts @@ -140,11 +142,7 @@ // jQuery checkboxes // NOTE: keep it after jQuery includes - if ($jquerycheckboxes === true) - { - generateJSsInclude('vendor/rmariuzzo/jquery-checkboxes/dist/jquery.checkboxes-1.0.7.min.js'); - } - + if ($jquerycheckboxes === true) generateJSsInclude('vendor/rmariuzzo/jquery-checkboxes/dist/jquery.checkboxes-1.0.7.min.js'); // jQuery treetable // NOTE: keep it after jQuery includes if ($jquerytreetable === true) generateJSsInclude('vendor/ludo/jquery-treetable/jquery.treetable.js'); @@ -173,10 +171,7 @@ } // PivotUI JS - if ($pivotui === true) - { - generateJSsInclude('vendor/nicolaskruchten/pivottable/dist/pivot.min.js'); - } + if ($pivotui === true) generateJSsInclude('vendor/nicolaskruchten/pivottable/dist/pivot.min.js'); // Table sorter JS if ($tablesorter === true) diff --git a/application/views/templates/mailHTML.php b/application/views/templates/mailHTML.php index c2e072f68..32d544c5a 100644 --- a/application/views/templates/mailHTML.php +++ b/application/views/templates/mailHTML.php @@ -1,12 +1,12 @@ - This is not the email template, this is a tribute + Notification of personal message reception
diff --git a/application/views/templates/mailTXT.php b/application/views/templates/mailTXT.php index cd55aeb06..09634e6ae 100644 --- a/application/views/templates/mailTXT.php +++ b/application/views/templates/mailTXT.php @@ -1,3 +1,7 @@ -Follow the following link to read the message. +Notification of personal message reception -{href} \ No newline at end of file +A new message is available + +Click here to view the message + +{href} diff --git a/application/views/templates/vilesci.php b/application/views/templates/vilesci.php index 0d55734c7..4f54a9dc8 100644 --- a/application/views/templates/vilesci.php +++ b/application/views/templates/vilesci.php @@ -1,42 +1,42 @@ - - - - <?php echo $this->template->title->default("Default title"); ?> - - - - template->meta; ?> - template->stylesheet; ?> - - - -template->widget("navigation", array('title' => 'Project name')); -?> - -
- - template->content; - ?> - -
- -
-

- template->footer->prepend("© Special Company 2012 - "); - ?> -

-
- -
- - -template->javascript; ?> - - + + + + <?php echo $this->template->title->default("Default title"); ?> + + + + template->meta; ?> + template->stylesheet; ?> + + + +template->widget("navigation", array('title' => 'Project name')); +?> + +
+ + template->content; + ?> + +
+ +
+

+ template->footer->prepend("© Special Company 2012 - "); + ?> +

+
+ +
+ + +template->javascript; ?> + + \ No newline at end of file diff --git a/application/views/widgets/dropdown.php b/application/views/widgets/dropdown.php index c1bdbf5c8..d9faf1978 100644 --- a/application/views/widgets/dropdown.php +++ b/application/views/widgets/dropdown.php @@ -11,7 +11,7 @@ $align = "valign-top"; } ?> -
+