/woka.php
PHP | 1702 lines | 1298 code | 201 blank | 203 comment | 301 complexity | cd61c00c5539bbfb0d9755ae032ea863 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?php
- //Following constants are the DEBUG levels
- define( 'DEBUG_OFF', 0 );
- define( 'DEBUG_CATCHS', 1 ); //Only messages from try/catch blocks will log
- define( 'DEBUG_FULL', 2 ); //all info messages will be logged
- if (isset( $argv [0] )) {
- define( 'CONSOLE', 1 ); //constant indicates its running from console to index.php
- //--------------------------------------
- //Whith this we include the zend context
- require_once ('index.php');
- NotificationsWorker::getInstance();
- }
- class NotificationsWorker {
- const MAX_EXECUTION_TIME = 3660;
- const WORKER_FUNCTION_SEND_NOTIFICATIONS = 'sendNotifications';
- const MAX_JOBS = 3660;
- const MAX_THUMBS_TO_SHOW = 2;
- private $shutdown; // this variable is set by the signal handler when it recieves SIGTERM
- //maps the type of the incoming message with the DB types
- private static $typeMapping = array (
- 'text' => 'notes',
- 'video' => 'messages',
- 'image' => 'messages',
- 'assignment' => 'assignments',
- 'system' => 'messages',
- 'comment' => 'replies',
- 'alert' => 'alerts',
- 'grade' => 'messages',
- 'poll' => 'messages',
- 'quiz' => 'quizzes',
- );
- private $worker;
- private static $starttime;
- private static $jobcount;
- private static $replyTo = NOTIFY_EMAIL;
- private static $log;
- private static $msgID = 0;
- private static $msgType = '';
- private static $expectedWorkersNumber;
- //self::logActions is incharge of logging according to DEBUG level
- /**
- * Setup the Notifications worker object
- *
- */
- private function __construct() {
- // install signal handler
- declare(ticks = 1)
- ;
- pcntl_signal( SIGTERM, array ($this, "sig_handler" ) );
- $this->shutdown = FALSE;
- self::$starttime = time();
- self::$jobcount=0;
- try {
- $this->worker = new GearmanWorker();
- $gearman_obj = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'gearman');
- $gearman_job_server_conf = $gearman_obj->get('job_server')->toArray();
- $added= $this->worker->addServer($gearman_job_server_conf['host'], $gearman_job_server_conf['port']);
- $gearman_workers_conf = $gearman_obj->get('workers')->toArray();
- self::$expectedWorkersNumber = $gearman_workers_conf['expected_worker_count'];
- $this->worker->addFunction( 'sendNotifications', 'NotificationsWorker::send_notifications' );
- //$this->worker->setOptions(GEARMAN_WORKER_NON_BLOCKING,TRUE); // causes the function GearmanWorker::work() to not block the caller. However, it also causes the worker to not process any jobs! is this a bug?
- } catch ( exception $e ) {
- self::logActions( "\n" . '__construct:ERROR on setup ' . $e->getMessage(), DEBUG_CATCHS );
- self::writeLog( 'c_' );
- }
- try {
- do {
- // check to see if we have recieved a SIGTERM signal
- if ($this->shutdown) {
- self::logActions( "Recieved kill command. Exiting gracefully", DEBUG_FULL );
- self::writeLog();
- exit( 0 );
- }
- // check to see if we have been running too long
- $runningtime = time() -self::$starttime;
- if ($runningtime > self::MAX_EXECUTION_TIME ) {
- self::logActions( "exiting after $runningtime seconds", DEBUG_FULL );
- self::writeLog();
- // ensure that enough workers are running then exit gracefully
- self::watchAndRaiseWorkers();
- exit( 0 );
- }
- // check to see if we have executed too many jobs
- if (self::$jobcount > self::MAX_JOBS ) {
- self::logActions( "exiting after running ".self::$jobcount.' jobs ', DEBUG_FULL );
- self::writeLog();
- // ensure that enough workers are running then exit gracefully
- self::watchAndRaiseWorkers();
- exit( 0 );
- }
- $this->worker->work();
- if (! ($this->worker->returnCode() == GEARMAN_IO_WAIT || $this->worker->returnCode() == GEARMAN_NO_JOBS || $this->worker->returnCode() == 0)) {
- self::logActions( "an error ocurred " . $this->worker->returnCode(), DEBUG_FULL );
- self::writeLog();
- }
- } while ( TRUE );
- } catch ( exception $e ) {
- //self::sendWarningEmail();
- self::logActions( "\n" . '__contruct:**** I Finished Working **** ' . $e->getMessage(), DEBUG_CATCHS );
- self::writeLog( 'cw_' );
- }
- }
- function __destruct() {
- try {
- //self::sendWarningEmail();
- self::logActions( "\n ---- I Died!!! ----\n", DEBUG_CATCHS );
- self::writeLog( 'd_' );
- } catch ( exception $e ) {
- //do nothing
- }
- }
- /**
- *
- * @return object GearmanHelper instance
- */
- static function getInstance() {
- static $instance;
- $instance = new self();
- return $instance;
- }
- /**
- * Main function to process and send correct notifications for an action
- * @param array $job serialized object from Gearman call
- * @return
- */
- public static function send_notifications($job) {
- try {
- if (empty( self::$starttime )) {
- self::$starttime = time();
- }
- if(empty(self::$jobcount)){
- self::$jobcount=0;
- }
- self::$jobcount++;
- self::logActions( '-------------------------------' . "\n" . 'NotificationsWorker::send_notifications' . "\n", DEBUG_CATCHS );
- $myProccessId = getmypid(); //Get self proccess ID
- self::logActions( "\n" . 'send_notifications:: Proccess ID : ' . $myProccessId . "\n\n", DEBUG_CATCHS );
- try {
- $workerObject = $job->workload(); //will bring the desired message
- $workerArray = unserialize( $workerObject );
- $errors=error_get_last();
- if(isset($errors['type']) && $errors['type']==2 && isset($errors['message']) && strstr($errors['message'],'unserialize') ){
- // fix the SimpleXML bug
- $tokens=explode(';',$workerObject);
- foreach($tokens as $i=>$token){
- if($token=='O:16:"SimpleXMLElement":1:{i:0'){
- $tokens[$i+2]=substr($tokens[$i+2],1);
- unset($tokens[$i]);
- }
- }
- $workerObject=implode(';',$tokens);
- $workerArray = unserialize( $workerObject );
- }
- if(empty($workerArray)){
- trigger_error('Unable to process job '.$job->handle());
- trigger_error($workerObject);
- return;
- }
- $selectedReceivers = $workerArray ['selected_receivers'];
- $accountInfo = $workerArray ['account_info'];
- $messageData = $workerArray ['message_data'];
- self::$msgID = isset($messageData['message_id']) ? $messageData['message_id']: null;
- self::$msgType = $messageData ['type'];
- } catch ( exception $e ) {
- self::logActions( "\n" . 'send_notifications: ERROR: Constructing Notification: ' . $e->getMessage() . "\n", DEBUG_CATCHS );
- }
- //--------------------------------
- // Log some Data
- $initialLogMsg = '$workerArray: ' . print_r( $workerArray, true ) . "\n";
- self::logActions( $initialLogMsg, DEBUG_FULL );
- //verify that a connection to the database is active
- self::ensureActiveDBConnection();
- try {
- //Call Main proccess
- self::process_notifications( $workerArray, $selectedReceivers, $accountInfo, $messageData );
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'send_notifications: ERROR processing notifications ' . $e->getMessage(), DEBUG_CATCHS );
- self::writeLog();
- }
- } catch ( exception $e ) {
- //--------------------------------
- // Log the Exception
- self::logActions( "\n" . 'send_notifications: ERROR: An Exception was thrown: ' . $e->getMessage(), DEBUG_CATCHS );
- self::writeLog();
- }
- }
- private static function ensureActiveDBConnection(){
- $write_db_registry_name = 'zendmodo_db';
- $readonly_db_registry_name = 'zendmodo_readonly_db';
- $databases = Zend_Registry::get('databases');
- $db=NULL;
- if (Zend_Registry::isRegistered($write_db_registry_name)) {
- $db = Zend_Registry::get($write_db_registry_name);
- }
- if (empty($db)) {
- $db_obj = $databases->db->get('zendmodo');
- if(empty($db_obj)){
- throw new Exception("no configuration defined for db");
- }
- $db = Zend_Db::factory($db_obj->adapter, $db_obj->config->toArray());
- if (empty($db)) {
- throw new Exception("failed to connect to db using configuration");
- } else {
- Zend_Registry::set($write_db_registry_name, $db);
- }
- }
- try{
- $now=$db->fetchOne('select now()');
- }catch(Zend_Db_Statement_Exception $e){
- if($e->getMessage()=="SQLSTATE[HY000]: General error: 2006 MySQL server has gone away"){
- trigger_error('MySQL server has gone away. Reconnecting...',E_USER_WARNING);
- //try to reconnect
- $db->closeConnection();
- $db->getConnection();
- $now=$db->fetchOne('select now()');
- trigger_error('Reconnected to database',E_USER_NOTICE); //write this message to the log so that we know when successful reconnects happen.
- }else{
- throw $e; // some other exception happened that we arent going to handle here.
- }
- }
- // check and reconnect to readonly database
- $readonly_db=NULL;
- if (Zend_Registry::isRegistered($readonly_db_registry_name)) {
- $readonly_db = Zend_Registry::get($readonly_db_registry_name);
- }
- if (empty($readonly_db)) {
- $readonly_db_obj = $databases->db->get('zendmodo_readonly');
- if(empty($readonly_db_obj)){
- throw new Exception("no configuration defined for readonly db");
- }
- $readonly_db = Zend_Db::factory($readonly_db_obj->adapter, $readonly_db_obj->config->toArray());
- if(empty($readonly_db)){
- throw new Exception("failed to connect to readonly db using configuration");
- }else{
- Zend_Registry::set($readonly_db_registry_name, $readonly_db);
- }
- }
- try{
- $now=$readonly_db->fetchOne('select now()');
- }catch(Zend_Db_Statement_Exception $e){
- if($e->getMessage()=="SQLSTATE[HY000]: General error: 2006 MySQL server has gone away"){
- trigger_error('Readonly MySQL server has gone away. Reconnecting...',E_USER_WARNING);
- //try to reconnect
- $readonly_db->closeConnection();
- $readonly_db->getConnection();
- $now=$readonly_db->fetchOne('select now()');
- trigger_error('Reconnected to readonly database',E_USER_NOTICE); //write this message to the log so that we know when successful reconnects happen.
- }else{
- throw $e; // some other exception happened that we arent going to handle here.
- }
- }
- }
- /**
- * Aux function to process and send correct notifications for an action
- * @param array $workerArray unserialized object from Gearman call
- * @param array $selectedReceivers the receivers of the message
- * @param array $accountInfo info from the sender
- * @param array $messageData the message data to be send
- * @return
- */
- private function process_notifications($workerArray, $selectedReceivers, $accountInfo, $messageData) {
- $allRecipients = array ();
- $membersOfGroup = array ();
- $parentsOfGroup = array ();
- $adminRecipients = array();
- $parentsGroups = array();
- try {
- //This case if for new restricted messages to only receivers that have commented
- if (isset( $selectedReceivers ['notification_receivers'] )) {
- self::logActions( '$selectedReceivers[\'notification_receivers\'] Getting through the first if', DEBUG_FULL );
- try {
- foreach ( $selectedReceivers ['notification_receivers'] as $receiver => $receiverId ) {
- array_push( $allRecipients, $receiverId );
- }
- //check if this user that answered is an admin
- if (is_array( $selectedReceivers ['locations'] )) {
- foreach ( $selectedReceivers ['locations'] as $location ) {
- $inst_admins = array();
- if ($location ['type'] == 'school' || $location ['type'] == 'school_vip') {
- $inst_admins = Schools::getInstance()->getAllSchoolAdmins( $location ['id'] );
- $messageData['posted_in_school'] = 1;
- }
- if ($location ['type'] == 'district' || $location ['type'] == 'district_vip') {
- $inst_admins = Districts::getInstance()->getDistrictMembers( $location ['id'] ,false,'admins','',true);
- }
- foreach($inst_admins as $admin)
- {
- if(isset($admin['admin_notifications']) && !empty($admin['admin_notifications']) && in_array($admin ['user_id'],$selectedReceivers ['notification_receivers']))
- {
- array_push( $adminRecipients, $admin ['user_id'] );
- }
- }
- unset( $inst_admins );
- }
- }
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'process_notifications:ERROR creating receiver list ' . $e->getMessage(), DEBUG_CATCHS );
- }
- } //This is for direct messages to get notification when they answered my message,etc
- else if (is_array( $selectedReceivers ['people'] ) && count( $selectedReceivers ['people'] ) == 1 &&
- (! is_array( $selectedReceivers ['locations'] ) || count( $selectedReceivers ['locations'] ) == 0) && $messageData ['type'] == 'comment') {
- self::logActions( 'process_notifications: Going through direct reply', DEBUG_FULL );
- try {
- //do direct reply answer
- $originalSenderInfo = Messages::getInstance()->getSenderInfoByMessageId( $messageData ['comment_to'] );
- if ( $originalSenderInfo['send_notifications'] != '0' ){
- if ($originalSenderInfo ['user_id'] == $accountInfo ['user_id'])
- $newReceiver = $selectedReceivers ['people'] [0];
- else
- $newReceiver = $originalSenderInfo ['user_id'];
- array_push( $allRecipients, $newReceiver );
- }
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'process_notifications:ERROR creating direct reply receiver ' . $e->getMessage(), DEBUG_CATCHS );
- }
- } //This is the normal case to fetch all receivers on groups, individuals, etc
- else { //THERE COULD BE A PROBLEM HERE IF notifications_receivers is empty, or other conditions default to "else" when its not expected
- try {
- self::logActions( 'process_notifications: Going through normal case', DEBUG_FULL );
- try {
- //search recipients
- $possible_students_tmp = array ();
- foreach ( $selectedReceivers ['people'] as $recipient => $userId ) {
- array_push( $allRecipients, $userId );
- array_push( $possible_students_tmp, $userId );
- }
- //Parents notifications on assignments, find possible parents for this users
- self::logActions( 'process_notifications: type ' . $messageData ['type'], DEBUG_FULL );
- if ($messageData ['type'] == 'assignment' || $messageData ['type'] == 'alert') {
- $parents_ids = ParentsStudents::getInstance()->getParentsForStudents( $possible_students_tmp, true );
- self::logActions( 'process_notifications: parent ids ' . print_r( $parents_ids, true ), DEBUG_FULL );
- $allRecipients = array_merge( $allRecipients, $parents_ids );
- }
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'process_notifications:ERROR with People array ' . $e->getMessage(), DEBUG_CATCHS );
- }
- try {
- //adds recipients from groups
- if (is_array( $selectedReceivers ['locations'] )) {
- foreach ( $selectedReceivers ['locations'] as $location ) {
- if ($location ['type'] == 'group') {
- $tmpUserIds = Groups::getInstance()->getGroupMembersToNotify( $location ['id'] );
- $tmpName = Groups::getInstance()->getGroup( $location ['id'], false, true );
- foreach ( $tmpUserIds as $user_id ) {
- array_push( $allRecipients, $user_id );
- array_push( $membersOfGroup, array ($user_id => $tmpName ['title'] ) );
- $messageData['parent_group_title'] = $tmpName['parent_group_title'];
- }
- //Parents notifications on assignments, find possible parents for this groups
- self::logActions( 'process_notifications: group type ' . $messageData ['type'], DEBUG_FULL );
- if ( $messageData ['type'] == 'assignment' || $messageData ['type'] == 'alert') {
- $parents_ids = ParentsStudents::getInstance()->getParents( $location ['id'], true );
- self::logActions( 'process_notifications: group parent ids ' . print_r( $parents_ids, true ), DEBUG_FULL );
- if (count( $parents_ids )) {
- foreach ( $parents_ids as $parent ) {
- array_push( $allRecipients, $parent ['parent_id'] );
- if (! array_key_exists( $parent ['parent_id'], $parentsOfGroup ))
- $parentsOfGroup [$parent ['parent_id']] = $tmpName ['title'];
- }
- }
- }
- }
- if ($location ['type'] == 'group_parents')
- {
- $tmpName = Groups::getInstance()->getGroup( $location ['id'] );
- //Parents notifications on assignments, find possible parents for this groups
- self::logActions( 'process_notifications: group type ' . $messageData ['type'], DEBUG_FULL );
- if ($messageData ['type'] == 'text' || $messageData ['type'] == 'comment' || $messageData ['type'] == 'assignment' || $messageData ['type'] == 'alert') {
- $parents_ids = ParentsStudents::getInstance()->getParents( $location ['id'], true );
- self::logActions( 'process_notifications: group parent ids ' . print_r( $parents_ids, true ), DEBUG_FULL );
- if (count( $parents_ids )) {
- foreach ( $parents_ids as $parent ) {
- array_push( $allRecipients, $parent ['parent_id'] );
- if (! array_key_exists( $parent ['parent_id'], $parentsOfGroup ))
- $parentsOfGroup [$parent ['parent_id']] = $tmpName ['title'];
- if (! array_key_exists( $parent ['parent_id'], $parentsGroups ))
- $parentsGroups [$parent ['parent_id']] = $location ['id'];
- }
- }
- }
- }
- if ($location ['type'] == 'all-groups')
- {
- $groups = Groups::getInstance()->getUserGroups($accountInfo['user_id'],false,false);
- foreach( $groups as $group)
- {
- if ($group['read_only'] == 1) {
- // Do not send email notifications to a group that the user
- // cannot post to.
- continue;
- }
-
- $group_id = $group['group_id'];
- $tmpUserIds = Groups::getInstance()->getGroupMembersToNotify( $group_id );
- $tmpName = Groups::getInstance()->getGroup( $group_id, false, true );
- foreach ( $tmpUserIds as $user_id ) {
- array_push( $allRecipients, $user_id );
- array_push( $membersOfGroup, array ($user_id => $tmpName ['title']) );
- $messageData['parent_group_title'] = $tmpName['parent_group_title'];
- }
- //Parents notifications on assignments, find possible parents for this groups
- self::logActions( 'process_notifications: group type ' . $messageData ['type'], DEBUG_FULL );
- if ( $messageData ['type'] == 'assignment' || $messageData ['type'] == 'alert') {
- $parents_ids = ParentsStudents::getInstance()->getParents( $location ['id'], true );
- self::logActions( 'process_notifications: group parent ids ' . print_r( $parents_ids, true ), DEBUG_FULL );
- if (count( $parents_ids )) {
- foreach ( $parents_ids as $parent ) {
- array_push( $allRecipients, $parent ['parent_id'] );
- if (! array_key_exists( $parent ['parent_id'], $parentsOfGroup ))
- $parentsOfGroup [$parent ['parent_id']] = $tmpName ['title'];
- }
- }
- }
- }
- }
- //Will add recipients from institution admins
- $inst_admins = array();
- if ($location ['type'] == 'school' || $location ['type'] == 'school_vip') {
- $inst_admins = Schools::getInstance()->getAllSchoolAdmins( $location ['id'] );
- $messageData['posted_in_school'] = 1;
- }
- if ($location ['type'] == 'district' || $location ['type'] == 'district_vip') {
- $inst_admins = Districts::getInstance()->getDistrictMembers( $location ['id'] ,false,'admins','',true);
- }
- foreach($inst_admins as $admin)
- {
- if(isset($admin['admin_notifications']) && !empty($admin['admin_notifications']))
- {
- array_push( $allRecipients, $admin ['user_id'] );
- array_push( $adminRecipients, $admin ['user_id'] );
- }
- }
- unset( $inst_admins );
- }
- foreach ( $parentsOfGroup as $key => $parent ) {
- self::logActions( 'process_notifications: group parents ' . print_r( array ($key => $parent ), true ), DEBUG_FULL );
- //we insert the parent as a member of the group to hack the subject behaviour
- array_push( $membersOfGroup, array ($key => $parent ) );
- }
- self::logActions( 'process_notifications: group members ' . print_r( $parentsOfGroup, true ), DEBUG_FULL );
- } else {
- self::logActions( '$selectedReceivers[\'locations\'] is not an array... Workflow ended unexpectedly', DEBUG_FULL );
- }
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'process_notifications:ERROR adding recipients from groups ' . $e->getMessage(), DEBUG_CATCHS );
- }
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'process_notifications:ERROR on Normal Case ' . $e->getMessage(), DEBUG_CATCHS );
- }
- }
- //removes repeated recipients
- $uniqueRecipients = array_unique( $allRecipients );
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'process_notifications:ERROR general recipients fail ' . $e->getMessage(), DEBUG_CATCHS );
- }
- //--------------------------------
- // Log some Data
- self::logActions( '$uniqueRecipients: ' . print_r( $uniqueRecipients, true ), DEBUG_FULL );
- self::logActions( '$membersOfGroup: ' . print_r( $membersOfGroup, true ), DEBUG_FULL );
- try {
- //check settings for recipients
- //PREVENT ERROR ON EMPTY ARRAY
- if(isset($uniqueRecipients) && !empty($uniqueRecipients) && count($uniqueRecipients) > 0)
- {
- $notificationsSettings = Notifications::getInstance()->getNotificationsForUsers( $uniqueRecipients );
- }
- else
- {
- $notificationsSettings = array();
- self::logActions( "\n" . 'process_notifications:ERROR: empty uniqueRecipients: ' , DEBUG_FULL);
- }
- } catch ( exception $e ) {
- //--------------------------------
- // Log the Exception
- self::logActions( "\n" . 'process_notifications:ERROR: on getNotificationsForUsers: ' . $e->getMessage(), DEBUG_CATCHS );
- $notificationsSettings = array ();
- }
- try {
- //check if incoming type is correct in db
- $tmpType = self::$typeMapping [$workerArray['message_data']['type']];
- //avoid joing group type
- if (self::isJoinGruoup( $messageData ) == false) {
- //call functions for notifications
- foreach ( $notificationsSettings as $notification ) {
- $recipientInfo = Users::getInstance()->getUserInfoWithSubdomain( $notification ['user_id'] );
- if ($recipientInfo['type'] == 'PARENT')
- {
- $recipientInfo['parent_groups'] = $parentsGroups;
- }
- $contents = self::prepareSubject( $messageData, $accountInfo, $recipientInfo, $membersOfGroup );
- $contents['group_id'] = $tmpName['group_id'];
- self::logActions( "\n" . 'Attempt to send with IF params: ' . $notification [$tmpType] . ' | ' . $accountInfo ['user_id'] . ' | ' . $notification ['user_id'], DEBUG_FULL);
- $contents['isDirect'] = self::isDirectMessage( $notification, $selectedReceivers );
- $is_admin_notification = self::isAdminNotification( $notification, $messageData, $adminRecipients );
- self::logActions( "\n" . 'adminRecipients ' . print_r($adminRecipients, true), DEBUG_FULL);
- //Will send if notification is valid and not admin, or is direct message, or admin settings are correct
- if ((($notification [$tmpType] == 1 && !in_array($notification['user_id'],$adminRecipients)) || $contents ['isDirect'] || $is_admin_notification) && ($accountInfo ['user_id'] != $notification ['user_id'])) {
- //call service notification func
- switch ($notification ['type']) {
- case 'TWITTER':
- self::postOnTwitter( $notification, $contents );
- break;
- case 'EMAIL':
- $messageData['is_admin_notification'] = $is_admin_notification;
- self::sendEmail( $contents, $recipientInfo, $messageData, $workerArray ['server_name'], $notification, $accountInfo );
- break;
- case 'SMS':
- self::sendSms( $notification, $contents, $recipientInfo );
- break;
- default :
- break;
- }
- }
- }
- } else {
- self::logActions( "\n" . 'Did not sent message - was join group', DEBUG_FULL );
- }
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'process_notifications:ERROR on for each notificationsSettings ' . $e->getMessage(), DEBUG_CATCHS );
- }
- self::logActions( "\n" . 'NotificationsWorker::Finished Logging' . "\n" . '-------------------------------' . "\n", DEBUG_CATCHS );
- self::writeLog();
- try {
- //Trying to free memory, cant do it outside here becuase reference is no good
- //unset seems to not force garbage collection according to the manual,
- $notificationsSettings = array ();
- $allRecipients = array ();
- $membersOfGroup = array ();
- self::$log = NULL;
- unset( $notificationsSettings );
- unset( $allRecipients );
- unset( $membersOfGroup );
- } catch ( exception $e ) {
- //EMPTY CATCH, CANT LOG ANYTHING HERE, LOGGING ERROR
- }
- }
- private function getSalutationName($recipient_language, $first_name, $last_name, $user_type, $title = 'NONE')
- {
- $registryKey = 'th-' . $recipient_language;
- if (Zend_Registry::isRegistered($registryKey)) {
- $translator = Zend_Registry::get($registryKey);
- } else {
- $translator = TranslationHelper::getInstance(PATH2_LANGUAGES . 'email-subjects.tmx', $recipient_language);
- Zend_Registry::set($registryKey, $translator);
- }
- $salutation_name = ucwords($first_name);
- switch($user_type)
- {
- case 'STUDENT':
- // if mbstring extension is installed, use it to handle multibyte strings
- if (function_exists('mb_substr')) {
- $last_initial = mb_substr($last_name, 0, 1, 'UTF-8');
- } else {
- $last_initial = substr($last_name, 0, 1);
- }
- $salutation_name = ucwords($first_name) . ' ' . strtoupper($last_initial) . '.';
- break;
- case 'TEACHER':
- $new_title = ($title == 'NONE') ? $first_name : $translator->_($title) . '.';
- $salutation_name = ucwords(strtolower($new_title)) . ' ' . ucwords($last_name);
- break;
- }
- return $salutation_name;
- }
- private function getSimpleSentTo($language, $recipient_id, $message_id, $message_recipients = null)
- {
- $to = null;
- if (!$message_recipients)
- {
- $message_recipients = Messages::getInstance()->getMessageRecipients($message_id);
- }
- foreach ($message_recipients as $recipient)
- {
- if ('group' == trim(ArrayHelper::elem($recipient, 'posted_in')))
- {
- if (UsersGroups::getInstance()->userIsMemberOfGroup($recipient_id, $recipient['posted_in_id']))
- {
- $group = Groups::getInstance()->find($recipient['posted_in_id'])->current()->toArray();
- $to = ArrayHelper::elem($group, 'title');
- }
- }
- if ($to)
- {
- break;
- }
- }
- $registryKey = 'th-' . $recipient_language;
- if (Zend_Registry::isRegistered($registryKey)) {
- $translator = Zend_Registry::get($registryKey);
- } else {
- $translator = TranslationHelper::getInstance(PATH2_LANGUAGES . 'email-subjects.tmx', $recipient_language);
- Zend_Registry::set($registryKey, $translator);
- }
- if ($to)
- {
- $to = $translator->_('reply-to-group') . ' ' . $to;
- }
- else
- {
- $to = $translator->_('reply-to-you');
- }
- return $to;
- }
- /**
- * Prepares the content of the message with correct title, subject, and language
- * @param array $messageData the info of the original sent message
- * @param array $senderInfo information from the sender
- * @param array $destinationInfo information for this destination
- * @return array the subject, first line, and content of the message
- */
- private function prepareSubject($messageData, $senderInfo, $destinationInfo, $membersOfGroup) {
- $retSubject = '';
- $senderTitle = '';
- $replied = '';
- $bodyText = '';
- $links_text = '';
- $replied_to = '';
- $replied_to_type = '';
- $other_reply_count = 0;
- $other_reply_count_text = '';
- try {
- $registryKey = 'th-' . $destinationInfo['language'];
- if (Zend_Registry::isRegistered($registryKey)) {
- $translator = Zend_Registry::get($registryKey);
- } else {
- $translator = TranslationHelper::getInstance(PATH2_LANGUAGES . 'email-subjects.tmx', $destinationInfo['language']);
- Zend_Registry::set($registryKey, $translator);
- }
- $senderTitle = ucwords($senderInfo['first_name']);
- //Sender Title
- if ($senderInfo['type'] == 'STUDENT') {
- // if mbstring extension is installed, use it to handle multibyte strings
- if (function_exists('mb_substr')) {
- $last_initial = mb_substr($senderInfo['last_name'], 0, 1, 'UTF-8');
- } else {
- $last_initial = substr($senderInfo['last_name'], 0, 1);
- }
- $firstLine = ucwords( $senderInfo ['first_name'] ) . ' ' . strtoupper( $last_initial );
- $senderTitle = $firstLine . '.';
- }
- if ($senderInfo ['type'] == 'TEACHER') {
- $displayTitle = (!$senderInfo ['title'] || $senderInfo ['title'] == 'NONE') ? $senderInfo ['first_name'] . ' ' : $translator->_( $senderInfo ['title'] ) . '. ';
- $firstLine = ucwords( strtolower( $displayTitle ) ) . ucwords( $senderInfo ['last_name'] );
- $senderTitle = $firstLine;
- }
- $possibleGroupName = self::checkGroupArray($destinationInfo, $membersOfGroup);
- //subject
- if ($messageData['comment_to'] != NULL) {
- $other_reply_count = ArrayHelper::elem($messageData, 'other_reply_count', 0);
- if ($other_reply_count > 0)
- {
- if ($other_reply_count == 1)
- {
- $other_reply_count_text = $translator->_('one-more-reply');
- }
- else
- {
- $other_reply_count_text = $other_reply_count . ' ' . $translator->_('multiple-more-replies');
- }
- }
- $commentToInfo = Messages::getInstance()->getMessageInfo($messageData['comment_to']);
- $commentToType = $commentToInfo['type'];
- $replied_to_a = $translator->_('replied-to-a');
- $replied_to_type = $translator->_('direct-' . $commentToType);
- $retSubject = $senderTitle . " " . $replied_to_a . $translator->_('direct-' . $commentToType);
- self::logActions('prepareSubject: The type is ' . $commentToType . ' subject: ' . $retSubject . "\n", DEBUG_FULL);
- } else if ($possibleGroupName != false) {
- $groupName = $possibleGroupName;
- //modifyng subject on assigments for parents, they come as members of the group
- if ($destinationInfo ['type'] == 'PARENT' && ($messageData ['type'] == 'assignment' || $messageData ['type'] == 'alert' || $messageData ['type'] == 'text' || $messageData ['type'] == 'comment')) {
- if(isset($destinationInfo['parent_groups']) && count($destinationInfo['parent_groups']) > 0)
- {
- $group_id = $destinationInfo['parent_groups'][$destinationInfo['user_id']];
- $student_ids = ParentsStudents::getInstance()->getParentStudentsByGroup($destinationInfo['user_id'],$group_id);
- }
- else
- {
- $students_info = ParentsHandler::getInstance()->getParentStudentsInfo( $destinationInfo );
- $student_ids = $students_info ['student_ids'];
- }
- $groupName = MessagingHelper::getInstance()->addChildrensNames( $groupName, $student_ids); //$destinationInfo['language']
- self::logActions('prepareSubject: group Name ' . $groupName . "\n", DEBUG_FULL);
- }
- $retSubject = $senderTitle . " " . $translator->_('sent-a') . $translator->_('direct-' . $messageData['type']) . " " . $translator->_('to') . " " . $groupName;
- } else {
- $retSubject = $senderTitle . " " . $translator->_( 'sent-you-a' ) . $translator->_( 'direct-' . $messageData ['type'] );
- }
- self::logActions( 'prepareSubject: subject: ' . $retSubject, DEBUG_FULL );
- $replied = ($messageData ['comment_to'] == NULL) ? '' : ' ' . $translator->_('replied');
- //body
- switch($messageData ['type'])
- {
- case 'assignment' :
- $bodyText = $messageData ['assignment'];
- break;
- case 'quiz' :
- $bodyText = $messageData ['quiz_title'];
- break;
- case 'poll':
- $bodyText = $messageData ['poll_question'];
- break;
- default:
- $msg = $messageData ['message'];
- if (strpos( $msg, 'new-group:' ) !== false) {
- $grp_id = str_replace( 'new-group:', '', $msg );
- $grp_info = Groups::getInstance()->getGroup( $grp_id );
- $msg = $translator->_( 'you-created-the-group' ) . " " . $grp_info ['title'] . "\n" . $translator->_( 'the-group-code-is' ) . " " . $grp_info ['code'];
- }
- $bodyText = MessagingHelper::formatDBString($msg,true,true,false,true);
- //self::logActions( "\n" . 'TEXT: ' . $bodyText, DEBUG_FULL );
- break;
- }
- if ($messageData['type'] == 'text' && isset( $messageData['links']) && is_array($messageData['links'])) {
- $links_text = '';
- foreach ( $messageData['links'] as $link ) {
- if (!isset($link['type']) || $link['type'] != 'embed') {
- $link_title = trim($link['desc']);
- $link_title = ($link_title && !filter_var($link_title, FILTER_VALIDATE_URL) ? $link_title : 'Link');
- if(LinkHandler::isEdmodoPostUrl($link['url']))
- {
- if(strpos($link_title,'Edmodo | Where Learning Happens') === false)
- {
- $links_text .= $link_title ;
- }
- else
- {
- $link_title = $translator->_( 'edmodo-post' );
- $links_text .= "<a href='{$link['url']}'>{$link_title}</a>\n";
- }
- }
- else
- {
- $links_text .= "<a href='{$link['url']}'>{$link_title}</a>\n";
- }
- }
- }
- }
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'prepareSubject: processing subject ' . $e->getMessage(), DEBUG_CATCHS );
- }
- $emailContents = array ('subject' => $retSubject, 'sender_title' => $senderTitle, 'first-line' => $senderTitle . $replied . ':', 'content' => $bodyText, 'links_text' => $links_text, 'replied_to_a' => $replied_to_a, 'replied_to_type' => $replied_to_type, 'other_reply_count' => $other_reply_count, 'other_reply_count_text' => $other_reply_count_text, 'group_name' => $groupName);
- return $emailContents;
- }
- private function formatMessageLink($contents, $messageData, $language, $recipientInfo, $serverName) {
- try {
- $formattedLink = MailHandler::getInstance()->formatEmailUrl($serverName, $recipientInfo, $messageData);
- self::logActions( "\n" . 'formatMessageLink: recipientInfo ' . print_r( $recipientInfo, true ), DEBUG_FULL );
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'formatMessageLink: formatting server name ' . $e->getMessage(), DEBUG_CATCHS );
- }
- $spotlightType = '';
- $registryKey='th-'.$language;
- if(false && Zend_Registry::isRegistered($registryKey)){
- $translator=Zend_Registry::get($registryKey);
- }else{
- // $translator = new TranslationHelper( new Zend_Translate( 'tmx', PATH2_LANGUAGES . 'email-subjects.tmx', $language ) );
- $translator = TranslationHelper::getInstance(PATH2_LANGUAGES . 'email-subjects.tmx', 'en');
- $englishType = $translator->_('link-' . $messageData['type']);
- $translator = TranslationHelper::getInstance(PATH2_LANGUAGES . 'email-subjects.tmx', $language);
- Zend_Registry::set($registryKey, $translator);
- }
- $translatedType = $translator->_( 'link-' . $messageData ['type'] );
- try {
- self::logActions( "\n" . 'formatMessageLink: Will format: ' . $contents ['isDirect'] . ' type: ' . $messageData ['type'] . ' comment-to: ' . $messageData ['comment_to'], DEBUG_FULL );
- if ($messageData ['comment_to'] != NULL) {
- $formattedLink .= '/post/' . $messageData ['comment_to'];
- $translatedType = $translator->_( 'comment-to' );
- } else if (!empty($messageData ['message_id'])) {
- $formattedLink .= '/post/' . $messageData ['message_id'];
- }
- else {
- //No spotlight type, just go to home
- $formattedLink .= '';
- }
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'formatMessageLink: formatting link ' . $e->getMessage(), DEBUG_CATCHS );
- }
- $formattedArray = array(
- 'formattedLink' => $formattedLink,
- 'translatedType' => $translatedType,
- 'type' => $englishType,
- );
- self::logActions( "\n Formated Link: \n" . $formattedLink, DEBUG_FULL );
- return $formattedArray;
- }
- /**
- * Searches for the group name for a user that belongs to that group
- * @param array $destinationInfo the info for the user to search
- * @param array $membersOfGroup ids from all users members to this group
- * @return string group Name or false
- */
- private function checkGroupArray($destinationInfo, $membersOfGroup) {
- $answer = false;
- try {
- foreach ( $membersOfGroup as $key => $member ) {
- if (array_key_exists( $destinationInfo ['user_id'], $member )) {
- $answer = $member [$destinationInfo ['user_id']];
- break;
- }
- }
- } catch ( exception $e ) {
- self::logActions( "\n" . 'FAILURE: MSGID: ' . self::$msgID . ', MSGTYPE: ' . self::$msgType, DEBUG_CATCHS );
- self::logActions( "\n" . 'checkGroupArray:ERROR on for each membersOfGroup ' . $e->getMessage(), DEBUG_CATCHS );
- }
- return $answer;
- }
- /**
- * current way of knowing if a message is from "joining a group"
- * @param array $messageData the info for the user to search
- * @return boolean if message is of type "join group"
- */
- private function isJoinGruoup($messageData) {
- $answer = false;
- if ($messageData ['type'] == 'system') {
- if (stristr( $messageData ['message'], 'joined' ) && stristr( $messageData ['message'], 'group' ))
- $answer = true;
- }
- return $answer;
- }
- //Checks if a user is an admin and has the right settings to receive notifications
- private function isAdminNotification($notification, $message_data, $admin_recipients)
- {
- $is_admin = false;
- if(!empty($notification['admin_notifications']))
- {
- if(!empty($notification['admin_notes']) && $message_data['type'] == 'text' && in_array($notification['user_id'],$admin_recipients))
- {
- $is_admin = true;
- }
- if(!empty($notification['admin_replies']) && $message_data['type'] == 'comment' && in_array($notification['user_id'],$admin_recipients))
- {
- $is_admin = true;
- }
- self::logActions( "\n isAdminNotification::$is_admin ,admin_notes: " . $notification['admin_notes'] ." admin_replies: " . $notification['admin_replies'] . " type: " . $message_data['type'] . " \n" , DEBUG_FULL );
- }
- return $is_admin;
- }
- /**
- * Determines if a user n…
Large files files are truncated, but you can click here to view the full file