function loop_through_filters_and_create_notifications($db, $filters, $params)
{
    $report = 'library/occdelta/filterable_occdelta_count';
    $notificationCounter = 0;
    //Supply 1 as the user id to give the code maximum privileges. Also force the main database connection
    //to allow access to the temporary occdelta table.
    $reportEngine = new ReportEngine(array($params['website_id']), 1, $db);
    //When creating notifications keep a track of user's we have created notifications for per verification page, this allows us to
    //avoid creating multiple notifications per user without having to check the database.
    $alreadyCreatedNotification = array();
    //Go through each filter for users who don't have an outstanding VT/PT notification.
    foreach ($filters as $filterIdx => $filter) {
        $extraParams = array('sharing' => $params['sharingFilterFullName']);
        if ($params['notificationSourceType'] === 'VT') {
            //Only look for completed record_status, we don't want to pick up V for instance, as these records are already verified
            $extraParams = array_merge($extraParams, array('record_status' => 'C'));
        } else {
            //If we are only interested in detecting Pending records then provide a release_status P parameter, this will
            //override the release_status R parameter that automatically appears in the report.
            $extraParams = array_merge($extraParams, array('release_status' => 'P'));
        }
        $reportParams = json_decode($filter['definition'], true) + $extraParams;
        try {
            // don't run the filter unless we we haven't already created a notification for that user
            if (!in_array($filter['user_id'], $alreadyCreatedNotification)) {
                //Get the report data for all new occurrences that match the filter.
                //Use the filter as the params
                $output = $reportEngine->requestReport("{$report}.xml", 'local', 'xml', $reportParams);
                //If records are returned then continue
                if ($output['content']['records'][0]['count'] > 0) {
                    //Save the new notification
                    $notificationObj = ORM::factory('notification');
                    $notificationObj->source = $params['notificationSource'];
                    $notificationObj->acknowledged = 'false';
                    $notificationObj->triggered_on = date("Ymd H:i:s");
                    $notificationObj->user_id = $filter['user_id'];
                    //Use VT "Verifier Task" or PT "Pending Record Task" notification type as we are informing the verifier that they need to perform a task.
                    $notificationObj->source_type = $params['notificationSourceType'];
                    $notificationObj->data = json_encode(array('username' => $params['title'], 'comment' => "<a href=\"{$params['url']}\">{$params['notificationComment']}</a>", 'auto_generated' => 't'));
                    $notificationObj->save();
                    $notificationCounter++;
                    $alreadyCreatedNotification[] = $filter['user_id'];
                }
            }
        } catch (Exception $e) {
            echo $e->getMessage();
            error::log_error('Error occurred when creating notifications based on new occurrences and user\'s filters.', $e);
        }
    }
    //Display message to show how many notifications were created.
    if ($notificationCounter == 0) {
        echo $params['noNotificationsCreatedMessage'] . '</br>';
    } elseif ($notificationCounter == 1) {
        echo $notificationCounter . ' ' . $params['oneNotificationCreatedMessage'] . '</br>';
    } else {
        echo $notificationCounter . ' ' . $params['multipleNotificationsCreatedMessage'] . '</br>';
    }
}
 /**
  * Compares any recently entered or edited records with the notifications registered on the system, looking
  * for matches. If found, then the notification's actions are fired.
  */
 protected function checkTriggers()
 {
     self::msg("Checking triggers");
     kohana::log('info', "Checking triggers");
     // Get a list of all the triggers that have at least one action
     $result = $this->getTriggerQuery();
     // For each trigger, we need to get the output of the report file which defines the trigger
     foreach ($result as $trigger) {
         $params = json_decode($trigger->params_json, true);
         $params['date'] = $this->last_run_date;
         $reportEngine = new ReportEngine();
         $data = $reportEngine->requestReport($trigger->trigger_template_file . '.xml', 'local', 'xml', $params);
         if (!isset($data['content']['records'])) {
             kohana::log('error', 'Error in trigger file ' . $trigger->trigger_template_file . '.xml');
             continue;
         }
         if (count($data['content']['records'] > 0)) {
             $parsedData = $this->parseData($data);
             self::msg($trigger->name . ": " . count($data['content']['records']) . " records found");
             //Note escaping disabled in where clause to permit use of CAST expression
             $actions = $this->db->select('trigger_actions.type, trigger_actions.param1, trigger_actions.param2, trigger_actions.param3, users.default_digest_mode, people.email_address, users.core_role_id')->from('trigger_actions, users')->join('people', 'people.id', 'users.person_id')->where(array('trigger_id' => $trigger->id, 'type' => "'E'", 'users.id' => 'CAST(param1 AS INT)', 'trigger_actions.deleted' => "'f'", 'users.deleted' => "'f'", 'people.deleted' => "'f'"), NULL, false)->get();
             foreach ($actions as $action) {
                 if ($action->core_role_id !== 1) {
                     // if not a core admin, we will need to do a filter on websites the user has access to.
                     $userWebsites = $this->db->select('website_id')->from('users_websites')->where('user_id', $action->param1)->get();
                 }
                 // Insert data in notifications table, either for the user to manually acknowledge, or for a digest mail to be built.
                 // First build a list of data for the user's websites
                 if ($action->core_role_id == 1) {
                     // core admin can see any data
                     $allowedData = $parsedData['websiteRecordData'];
                 } else {
                     $allowedData = array();
                     foreach ($userWebsites as $allowedWebsite) {
                         if (isset($parsedData['websiteRecordData'][$allowedWebsite->website_id])) {
                             $allowedData[$allowedWebsite->website_id] = $parsedData['websiteRecordData'][$allowedWebsite->website_id];
                         }
                     }
                 }
                 if (count($allowedData) > 0) {
                     $this->db->insert('notifications', array('source' => $trigger->name, 'source_type' => 'T', 'data' => json_encode(array('headings' => $parsedData['headingData'], 'data' => $allowedData)), 'user_id' => $action->param1, 'digest_mode' => $action->param2 === null ? $action->default_digest_mode : $action->param2, 'cc' => $action->param3));
                 }
             }
         }
     }
 }
/**
 * When the scheduled task is run, we need to send a notification to all users who have passed a new milestone
 */
function milestones_scheduled_task($last_run_date, $db)
{
    //Get a list of distinct user/website combinations and  milestones that each combination will need testing for,
    //these are milestones associated with each website the user is associated with, where the milestone has not been
    //awarded yet)
    $occurrenceMilestonesToCheck = get_user_website_combinations_with_unawarded_milestones_for_changed_occurrences($db);
    $mediaMilestonesToCheck = get_user_website_combinations_with_unawarded_milestones_for_changed_occ_media($db);
    //Supply a config of which websites to take into account.
    try {
        $website_ids = kohana::config('milestones.website_ids');
        //Handle config file not present
    } catch (Exception $e) {
        $website_ids = array();
    }
    //handle if config file present but option is not supplied
    if (empty($website_ids)) {
        $website_ids = array();
    }
    //Supply 1 as the user id to give the code maximum privileges
    $reportEngine = new ReportEngine($website_ids, 1);
    $notificationCount = 0;
    //Cycle through all the occurrence media milestones that haven't been awarded yet and could potentially need to be awarded since last run.
    foreach ($mediaMilestonesToCheck as $milestoneToCheck) {
        $report = 'library/occurrences/filterable_occurrence_media_counts_per_user_website';
        $params = json_decode($milestoneToCheck['definition'], true);
        $params['user_id'] = $milestoneToCheck['created_by_id'];
        $params['website_id'] = $milestoneToCheck['website_id'];
        try {
            //Get the report data for all new occurrences that match the filter,user,website.
            $data = $reportEngine->requestReport("{$report}.xml", 'local', 'xml', $params);
        } catch (Exception $e) {
            echo $e->getMessage();
            error::log_error('Error occurred when creating verification notifications based on new occurrences and user\'s filters.', $e);
        }
        foreach ($data['content']['records'] as $milestoneCountData) {
            if ($milestoneCountData['count'] >= $milestoneToCheck['count']) {
                create_milestone_reached_notification($milestoneToCheck);
                $notificationCount++;
            }
        }
    }
    //Cycle through all the occurrence taxa/occurrence milestones that haven't been awarded yet and could potentially need to be awarded since the last run
    foreach ($occurrenceMilestonesToCheck as $milestoneToCheck) {
        if ($milestoneToCheck['milestone_entity'] == 'T') {
            $report = 'library/occurrences/filterable_taxa_counts_per_user_website';
        } else {
            $report = 'library/occurrences/filterable_occurrence_counts_per_user_website';
        }
        $params = json_decode($milestoneToCheck['definition'], true);
        $params['user_id'] = $milestoneToCheck['created_by_id'];
        $params['website_id'] = $milestoneToCheck['website_id'];
        try {
            //Get the report data for all new occurrences that match the filter/user/website
            $data = $reportEngine->requestReport("{$report}.xml", 'local', 'xml', $params);
        } catch (Exception $e) {
            echo $e->getMessage();
            error::log_error('Error occurred when creating verification notifications based on new occurrences and user\'s filters.', $e);
        }
        foreach ($data['content']['records'] as $milestoneCountData) {
            if ($milestoneCountData['count'] >= $milestoneToCheck['count']) {
                create_milestone_reached_notification($milestoneToCheck);
                $notificationCount++;
            }
        }
    }
    if ($notificationCount == 0) {
        echo 'No new milestone notifications have been created.</br>';
    } elseif ($notificationCount == 1) {
        echo '1 new milestone notification has been created.</br>';
    } else {
        echo $notificationCount . ' new milestone notifications have been created.</br>';
    }
}
Exemple #4
0
function generateStateWiseReport()
{
    $re = new ReportEngine();
    $dao = new DAO();
    $allBrand = $dao->getAllBrands();
    $allState = array();
    $dataSet = $re->getStateWiseSalesData($_REQUEST);
    $dataSetDateWise = $re->getStateWiseSalesDataDateWise($_REQUEST);
    $arrLitre = array();
    $totalArrLitres = array();
    $arrAmount = array();
    $totalArrAmount = array();
    $arrState = array();
    foreach ($dataSetDateWise as $key => $data) {
        $arrLitre[$data['month']][$data['state']] = $data['litre'];
        $arrLitre[$data['month']]['month'] = $data['month'];
        $arrState[$data['state']] = 1;
    }
    foreach ($arrState as $key => $data) {
        $allState[] = array("state" => $key);
    }
    foreach ($arrLitre as $key => $data) {
        $totalArrLitres[] = $data;
    }
    foreach ($dataSetDateWise as $key => $data) {
        $arrAmount[$data['month']][$data['state']] = $data['amount'];
        $arrAmount[$data['month']]['month'] = $data['month'];
    }
    foreach ($arrAmount as $key => $data) {
        $totalArrAmount[] = $data;
    }
    $inputGraphDataLitres = json_encode($totalArrLitres);
    $inputGraphDataAmount = json_encode($totalArrAmount);
    include "../view/generatedStateWiseReport.php";
}