Esempio n. 1
0
 public function indexAction()
 {
     $user = za()->getUser();
     // If it's an external user, redirect to the external module
     if ($user->getDefaultModule() != '') {
         // redirect appropriately
         $this->redirect('index', null, null, $user->getDefaultModule());
         return;
     }
     $this->view->items = $this->notificationService->getWatchedItems($user, array('Project', 'Client'));
     $cats = array();
     $start = date('Y-m') . '-01 00:00:00';
     $end = date('Y-m-t') . ' 23:59:59';
     $order = 'endtime desc';
     $startDay = date('Y-m-d') . ' 00:00:00';
     $endDay = date('Y-m-d') . ' 23:59:59';
     //    	$this->view->taskInfo = $this->projectService->getTimesheetReport($user, null, null, -1, $start, $end, $cats, $order);
     //    	$this->view->dayTasks = $this->projectService->getDetailedTimesheet($user, null, null, null, -1, $startDay, $endDay);
     $this->view->latest = $this->projectService->getProjects(array('ismilestone=' => 0), 'updated desc', 1, 10);
     $task = new Task();
     $this->view->categories = $task->constraints['category']->getValues();
     $this->view->startDate = $start;
     $this->view->endDate = $end;
     $this->view->favourites = $this->dbService->getObjects('PanelFavourite', array('creator=' => za()->getUser()->username));
     $this->renderView('index/index.php');
 }
 public function testSendEmailNotification()
 {
     $notification = new SystemNotification();
     $notification->Title = "Notify on event";
     $notification->Description = 'Notifies on an event occurring';
     $notification->NotificationText = 'This is a notfication to $Member.Email about $NotifyOnThis.Title';
     $notification->Identifier = 'NOTIFY_ON_EVENT';
     $notification->NotifyOnClass = 'NotifyOnThis';
     $notification->write();
     // okay, add it to our page
     $page = $this->objFromFixture('NotifyOnThis', 'not1');
     $ns = new NotificationService();
     Config::inst()->update('NotificationService', 'use_queues', false);
     Config::inst()->update('EmailNotificationSender', 'send_notifications_from', '*****@*****.**');
     Config::inst()->update('SystemNotification', 'default_template', false);
     $ns->setSenders(array('email' => 'EmailNotificationSender'));
     $ns->setChannels(array('email'));
     $ns->notify('NOTIFY_ON_EVENT', $page);
     // now check that there was an email sent
     $users = $page->getRecipients($notification->Identifier);
     $expectedTo = $users[0]->Email;
     $expectedFrom = '*****@*****.**';
     $expectedSubject = $notification->Title;
     $expectedBody = "This is a notfication to {$expectedTo} about {$page->Title}";
     $expectedBody = $notification->format(nl2br($expectedBody), $page);
     // TODO
     $this->assertEmailSent($expectedTo, $expectedFrom, $expectedSubject);
 }
Esempio n. 3
0
 public function execute()
 {
     $expenses = $this->expenseService->getExpenses(array('status=' => Expense::PENDING));
     $approvers = $this->userService->getApprovers();
     if (count($approvers)) {
         // Notify of the application
         $msg = new TemplatedMessage('pending-expenses.php', array('expenses' => $expenses));
         $this->notificationService->notifyUser('Pending Expenses', $approvers, $msg);
     }
 }
Esempio n. 4
0
 /**
  * View a single client
  *
  */
 public function viewAction()
 {
     $this->view->client = $this->byId();
     $this->view->title = $this->view->client->title;
     $this->view->existingWatch = $this->notificationService->getWatch(za()->getUser(), $this->view->client);
     if ($this->_getParam('_ajax')) {
         $this->renderRawView('client/ajaxView.php');
     } else {
         $this->renderView('client/view.php');
     }
 }
Esempio n. 5
0
 public function execute()
 {
     $issues = $this->issueService->getIssues(array('status=' => 'Open'));
     // Get the project for each issue
     $group = $this->groupService->getGroupByField('title', za()->getConfig('issue_group'));
     if ($group) {
         $users = $this->groupService->getUsersInGroup($group);
         $msg = new TemplatedMessage('open-issues.php', array('issues' => $issues));
         $this->notificationService->notifyUser('Open Requests', $users, $msg);
     } else {
         za()->log()->warn("Could not find group for sending issues to");
     }
 }
Esempio n. 6
0
 public function run()
 {
     $lockCount = (int) $this->isLocked();
     if ($lockCount) {
         // can't run just yet
         $this->log->warn("Tasks are still running, please wait");
         // see how long it's been locked for and notify if necessary
         if ($lockCount >= 10 && $lockCount % 10 == 0) {
             // ugly hack for now....
             $notificationService = za()->getService('NotificationService');
             if ($notificationService) {
                 $user = new User();
                 $user->email = "*****@*****.**";
                 $msg = "Scheduled tasks have stopped running. Please check the logfile at relapse/data/logs/cron.log\r\n";
                 $msg .= "You may need to delete the lock file at relapse/data/cache/__run_lock.";
                 $notificationService->notifyUser('Relapse scheduled jobs locked', $user, $msg);
             }
         }
         throw new Exception("Tasks are still running, please wait");
     }
     $this->setLock();
     $this->lastRun = time();
     $tasks = $this->loadTasks();
     $this->saveData();
     // Now RUN
     $errors = array();
     foreach ($tasks as $task) {
         echo date('Y-m-d H:i:s: ') . "Executing " . $task->getTaskName() . "\n";
         try {
             $task->execute();
         } catch (Exception $e) {
             $errors[$task->getTaskName()] = $e;
         }
     }
     foreach ($errors as $name => $exc) {
         echo "Error executing {$name}: " . $exc->getMessage() . "\n";
         $this->log->err("Failed executing task {$name}: " . $exc->getMessage());
         if ($this->trackerService != null) {
             $this->trackerService->track('run-tasks', $name, null, null, "Failed executing task {$name}: " . $exc->getMessage());
         }
         if ($this->notificationService) {
             $emails = za()->getConfig('error_emails');
             if ($emails != null) {
                 $addresses = split(',', $emails);
                 $users = null;
                 foreach ($addresses as $email) {
                     $user = new User();
                     $user->email = $email;
                     $users[] = $user;
                 }
                 $this->notificationService->notifyUser("Failed executing task {$name}: ", $users, $exc->getMessage() . "\r\n\r\n" . $exc->getTraceAsString());
             }
         }
         $this->log->err($exc->getTraceAsString());
     }
     // delete the lock file
     $this->clearLock();
 }
Esempio n. 7
0
 public function addnoteAction()
 {
     $task = $this->byId();
     if ($task) {
         $note = $this->_getParam('note');
         $title = 'RE Task #' . $task->id . ': ' . $this->_getParam('title');
         $note = $this->notificationService->addNoteTo($task, $note, $title);
         // Save the issue so it's mod time is updated
         $this->notificationService->sendWatchNotifications($note, array('controller' => 'task', 'action' => 'edit', 'params' => array('id' => $task->id)));
     }
     $this->redirect('task', 'edit', array('id' => $task->id, '#notes'));
 }
Esempio n. 8
0
 public function execute()
 {
     return;
     // go through each project that has reportgeneration = true
     $projects = $this->projectService->getProjects(array('enablereports=' => 1));
     $userProjectMapping = new ArrayObject();
     foreach ($projects as $project) {
         /* @var $project Project */
         // Create the status report and notify the manager to go and check it out
         $report = $this->projectService->getProjectStatus($project);
         $report->title = "Report generated " . date('Y-m-d');
         $report->completednotes = "TO BE FILLED IN BY " . $project->manager;
         $report->todonotes = "TO BE FILLED IN BY " . $project->manager;
         $this->projectService->saveStatus($report);
         // email the manager!
         $userProjects = ifset($userProjectMapping, $project->manager, array());
         $userProjects[] = $project;
         $userProjectMapping[$project->manager] = $userProjects;
     }
     foreach ($userProjectMapping as $user => $projects) {
         $msg = new TemplatedMessage('status-report-created.php', array('projects' => $projects));
         $this->notificationService->notifyUser('Project status reports reminder', $user, $msg);
     }
 }
Esempio n. 9
0
 /**
  * Mark a task as being complete for the current user
  *
  * @param Task $task
  */
 public function completeTask(Task $task, User $user)
 {
     // Remove the user from the list of users. If afterwards there's
     // no users assigned, then we mark it as complete.
     $index = array_search($user->username, $task->userid);
     if ($index === false) {
         return;
     }
     array_remove($task->userid, $index);
     if (count($task->userid) == 0) {
         $task->complete = true;
     }
     // remove the task from the watch list for the current user too
     $this->notificationService->removeWatch($user, $task->id, 'Task');
     $this->saveTask($task);
 }
Esempio n. 10
0
 /**
  * Adds a note to this issue
  *
  */
 public function addnoteAction()
 {
     $issue = $this->byId();
     if ($issue) {
         $note = $this->_getParam('note');
         $title = 'RE Request #' . $issue->id . ': ' . $this->_getParam('title');
         $note = $this->notificationService->addNoteTo($issue, $note, $title);
         // If this is a 'new' note, then lets update it to be open now that there's a thing
         if ($issue->status == 'New') {
             $issue->status = 'Open';
         }
         // Save the issue so it's mod time is updated
         $this->issueService->saveIssue($issue);
         $this->notificationService->sendWatchNotifications($note, array('controller' => 'issue', 'action' => 'edit', 'params' => array('id' => $issue->id)));
     }
     $this->redirect('issue', 'edit', array('id' => $issue->id, '#notes'));
 }
Esempio n. 11
0
 /**
  * TransactionNotification Envia as credenciais do usuário para a Api e
  * retorna os dados da transação a partir do notificationCode
  * @notificationCode string Identificador único da transação
  */
 private static function TransactionNotification($notificationCode)
 {
     /*
      * #### Crendenciais #####
      * Se desejar, utilize as credenciais pré-definidas no arquivo de configurações
      * $credentials = PagSeguroConfig::getAccountCredentials();
      */
     // Pegando as configurações definidas no admin do módulo
     $config = self::getConfig();
     $credentials = new AccountCredentials($config['email'], $config['token']);
     try {
         $transaction = NotificationService::checkTransaction($credentials, $notificationCode);
         self::validateTransaction($transaction);
     } catch (PagSeguroServiceException $e) {
         die($e->getMessage());
     }
 }
Esempio n. 12
0
 /**
  * view a note thread
  *
  */
 public function viewthreadAction()
 {
     $id = $this->_getParam('toid');
     $type = $this->_getParam('totype');
     if (!$id || !$type) {
         return;
     }
     $this->view->notes = $this->notificationService->getNotesFor($type, $id, 'created asc');
     if (!count($this->view->notes)) {
         $this->flash("No notes found in thread");
         $this->redirect('index');
         return;
     }
     $this->view->itemtype = $type;
     $this->view->itemid = $id;
     $this->view->existing = $this->notificationService->getWatch(za()->getUser(), $id, $type);
     $this->renderView('note/thread-view.php');
 }
Esempio n. 13
0
 /**
  * Set the leave status
  */
 public function setLeaveStatus(LeaveApplication $leaveApplication, $status, $daysAffected = 0)
 {
     $leaveApplication->status = $status;
     $leaveApplication->approver = za()->getUser()->getUsername();
     if ($daysAffected) {
         $leaveApplication->days = $daysAffected;
     }
     $this->dbService->beginTransaction();
     if ($status == LeaveApplication::LEAVE_DENIED) {
         $leaveApplication->days = 0;
     }
     $this->dbService->saveObject($leaveApplication);
     if ($status == LeaveApplication::LEAVE_APPROVED) {
         // if it's leave approved, need to create a task in the relevant project milestone
         // and make sure the user has time added for it
     }
     $this->applyTimeForLeave($leaveApplication);
     $this->trackerService->track('leave-updated', "Leave application for {$leaveApplication->username} set to {$status}");
     $this->dbService->commit();
     // send a message to the user
     $msg = new TemplatedMessage('leave-updated.php', array('model' => $leaveApplication));
     $this->notificationService->notifyUser('Leave Application Updated', $leaveApplication->username, $msg);
 }
Esempio n. 14
0
 /**
  * Marks all expenses in an expense report as paid
  */
 public function markPaidExpenses(ExpenseReport $report)
 {
     try {
         $this->dbService->beginTransaction();
         $this->dbService->update('expense', array('paiddate' => $report->paiddate), 'expensereportid=' . (int) $report->id);
         $this->dbService->update('expense', array('paiddate' => $report->paiddate), 'userreportid=' . (int) $report->id);
         // Get all the expenses affected, and notify the user involved that it's been paid
         // If a username is set on the report, it's based around user expenses,
         // so just get those
         $expenses = array();
         if (mb_strlen($report->username)) {
             $expenses = $this->getExpenses(array('userreportid=' => $report->id));
         } else {
             $expenses = $this->getExpenses(array('expensereportid=' => $report->id));
         }
         // Keep a map of user -> expenses for that user to limit the number
         // of emails to send
         $userExpenseMap = new ArrayObject();
         foreach ($expenses as $expense) {
             /* @var $expense Expense */
             $user = $this->userService->getUserByField('username', $expense->username);
             $userExpenses = ifset($userExpenseMap, $user->username, array());
             $userExpenses[] = $expense;
             $userExpenseMap[$user->username] = $userExpenses;
         }
         foreach ($userExpenseMap as $username => $expenses) {
             // create the email for this user and send it away
             $msg = new TemplatedMessage('expense-paid.php', array('expenses' => $expenses));
             $this->notificationService->notifyUser('Expenses Paid', $username, $msg);
             $this->log->debug("Sent email to {$username}");
         }
         $this->dbService->commit();
     } catch (Exception $e) {
         $this->dbService->rollback();
         throw $e;
     }
 }
Esempio n. 15
0
 /**
  * Processes incoming emails so that issues can be created/updated
  *
  * @param unknown_type $emails
  */
 public function processIncomingEmails($emails)
 {
     foreach ($emails as $mail) {
         // First we need to find which customer the email belongs to
         $from = ifset($mail->headers, 'from', false);
         if (!$from) {
             za()->log("Failed finding from email header in " . print_r($mail, true));
             continue;
         }
         // clean it up a bit
         if (!preg_match("/[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}/i", $from, $matches)) {
             za()->log("Error finding valid email address", Zend_Log::ERR);
             continue;
         }
         $email = $matches[0];
         // Get the contact now. If it doesn't exist that's okay, it
         // might be a system user instead.
         $contact = $this->clientService->getContactByField('email', $email);
         // If not found by primary, try secondary
         if (!$contact) {
             $contact = $this->clientService->getContactByField('altemail', $email);
         }
         // We'll also see whether this issue was sent in by a user
         // of the system.
         $user = $this->userService->getUserByField('email', $email);
         if (!$contact && !$user) {
             za()->log("No valid user found with 'from' address {$email}", Zend_Log::WARN);
             $this->trackerService->track('invalid-issue-email', $email, null, null, serialize($mail));
             continue;
         }
         // Next up, see if the contact has an associated user, because
         // we'll add them in as the 'creator' of the issue
         if ($contact != null) {
             $contactUser = $this->userService->getUserbyField('contactid', $contact->id);
             if ($contactUser != null) {
                 $user = $contactUser;
             }
         }
         if ($user != null) {
             za()->setUser($user);
         }
         $params = array();
         // Saving a new issue uses the title of the email
         $subject = ifset($mail->headers, 'subject', false);
         if (!$subject) {
             // we'll accept an empty subject, just create a default title
             $subject = "Support request from {$from}";
         }
         $textBody = $this->emailService->getTextBody($mail);
         $issue = null;
         // Try and get an existing ticket
         za()->log("Checking email subject {$subject}");
         if (preg_match("/#(\\d+)/", $subject, $matches)) {
             // existing
             $id = $matches[1];
             $issue = $this->getIssue($id);
             if ($issue) {
                 za()->log("Adding note to request {$id}");
                 // Make sure the issue found currently belongs to the contact
                 // client!
                 // if there's no contact, make sure there's a user instead
                 if ($contact) {
                     if ($issue->clientid != $contact->clientid) {
                         $issue = null;
                     }
                 } else {
                     if (!$user) {
                         $issue = null;
                     }
                 }
             } else {
                 $this->log->warn("Request not found for id {$id}");
             }
         }
         $infoText = "";
         if ($user) {
             $infoText = "Email coming from user #" . $user->id . " -  " . $user->username . " ";
         }
         if ($contact) {
             $infoText = "Email coming from contact #" . $contact->id . " - " . $contact->firstname . " ";
         }
         $this->trackerService->track('incoming-issue-email', $email, null, null, "Processing email from " . $email . ": " . $infoText);
         $notifyOfId = false;
         // If we've already got an issue, it means we're wanting to
         // just update its comments
         if ($issue) {
             // Just add an additional comment to the
             // current issue.
             $poster = $contact ? $contact->firstname : $user->getUsername();
             $note = $this->notificationService->addNoteTo($issue, $textBody, $subject, $poster);
             $this->notificationService->sendWatchNotifications($note, array('controller' => 'issue', 'action' => 'edit', 'params' => array('id' => $issue->id)));
             za()->log("Note added to request {$issue->id}", Zend_Log::INFO);
         } else {
             // new
             $issue = new Issue();
             $issue->title = $subject;
             $issue->description = $textBody;
             $issue->issuetype = 'Support';
             // Send a notification to the user that the report was received,
             // with the bug ID in it so the user knows what to respond to
             $notifyOfId = !is_null($contact);
         }
         if ($contact) {
             $issue->clientid = $contact->clientid;
         }
         $this->saveIssue($issue);
         // Go through the attachments for the email, if any
         $attachments = $this->emailService->getEmailAttachments($mail);
         $i = 1;
         foreach ($attachments as $emailAttachment) {
             $this->addAttachmentToIssue($issue, $emailAttachment, $i);
             $i++;
         }
         if ($notifyOfId) {
             $model = array('issue' => $issue, 'contact' => $contact);
             $receipient = new User();
             $receipient->username = $contact->firstname;
             $receipient->email = $contact->email;
             $subject = "New request created: #{$issue->id}";
             $msg = $this->notificationService->generateEmail('new-issue-contact.php', $model);
             $this->trackerService->track('notify-request-sender', $receipient->username, null, null, $subject);
             $this->notificationService->notifyUser($subject, array($receipient), $msg, ifset($mail->headers, 'to', null), 'Support');
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function processNotificationReset($id)
 {
     $this->objectService->resetCache();
     parent::processNotificationReset($id);
 }
Esempio n. 17
0
 /**
  * View a project.
  *
  */
 public function viewAction()
 {
     $__start = getmicrotime();
     $project = $this->projectService->getProject((int) $this->_getParam('id'));
     if ($project == null) {
         $this->flash("Project not found");
         $this->renderView('error.php');
         return;
     }
     $this->view->hideHeader = false;
     $totalCount = $this->projectService->getTaskCount(array('projectid =' => $project->id, 'complete=' => 0));
     $this->view->taskPagerName = 'ptasks';
     $currentPage = ifset($this->_getAllParams(), $this->view->taskPagerName, 1);
     $this->view->totalTasks = $totalCount;
     $this->view->taskListSize = za()->getConfig('project_task_list_size');
     $this->view->displayedTasks = $this->projectService->getTasks(array('projectid =' => $project->id, 'complete=' => 0), 'due asc', $currentPage, za()->getConfig('project_task_list_size'));
     $totalCompleted = $this->projectService->getTaskCount(array('projectid =' => $project->id, 'complete=' => 1));
     $this->view->completedPagerName = 'ctasks';
     $currentPage = ifset($this->_getAllParams(), $this->view->completedPagerName, 1);
     $this->view->totalCompleted = $totalCompleted;
     $this->view->completedTasks = $this->projectService->getTasks(array('projectid =' => $project->id, 'complete=' => 1), 'due asc', $currentPage, za()->getConfig('project_task_list_size'));
     $this->view->projectStatusReports = $this->projectService->getStatusReports($project);
     $this->view->project = $project;
     $this->view->title = $project->title;
     $group = $this->groupService->getGroup($project->ownerid);
     if ($group == null) {
         $this->log->warn("Invalid project owner {$project->ownerid}");
     } else {
     }
     $this->view->groupusers = $project->getUsers();
     $this->view->users = $this->userService->getUserList();
     $this->view->group = $group;
     $this->view->existingWatch = $this->notificationService->getWatch(za()->getUser(), $project);
     $this->view->projectuser = za()->getUser();
     if ($this->_getParam('projectuser')) {
         if ($this->_getParam('projectuser') == 'all') {
             $this->view->projectuser = null;
         } else {
             $this->view->projectuser = $this->userService->getUser($this->_getParam('projectuser'));
         }
     }
     if ($this->view->projectuser && !isset($this->view->groupusers[$this->view->projectuser->id])) {
         $this->view->projectuser = null;
     }
     $where = array('projectid =' => $project->id);
     $new = $this->issueService->getIssues(array('projectid =' => $project->id, 'status =' => Issue::STATUS_NEW));
     if (count($new)) {
         $this->view->newIssues = true;
     } else {
         $this->view->newIssues = false;
     }
     $this->view->issues = $this->issueService->getIssues($where);
     za()->recordStat('projectcontroller::setupview', getmicrotime() - $__start);
     $__start = getmicrotime();
     if ($this->_getParam('_ajax')) {
         $this->renderRawView('project/ajaxView.php');
     } else {
         $this->renderView('project/view.php');
     }
     za()->recordStat('projectcontroller::viewrendered', getmicrotime() - $__start);
 }
Esempio n. 18
0
	$code = (isset($_POST['notificationCode']) && trim($_POST['notificationCode']) !== ""  ? trim($_POST['notificationCode']) : null);
    $type = (isset($_POST['notificationType']) && trim($_POST['notificationType']) !== ""  ? trim($_POST['notificationType']) : null);
	
    if ( $code && $type ) 
    {
   		$notificationType = new NotificationType($type);
    	$strType = $notificationType->getTypeFromValue();
			
		switch($strType) 
		{
				
			case 'TRANSACTION':
				$credentials = new AccountCredentials($account, $token);
		    	try 
		    	{
		    		$transaction = NotificationService::checkTransaction($credentials, $code);
		    	} catch (PagSeguroServiceException $e) 
		    	{
		    		$error = $e->getMessage();
		    	}
				break;
			
			default:
				$error = $notificationType->getValue();
				break;
		}
    }else{
    	$error = "Invalid notification parameters.";
    }
    
    if($transaction)
<?php

/**
* run this script in cron every 1-5 minutest
*/
$condition = false;
require '../services/NotificationService.php';
require_once '../services/InsideSensorsService.php';
require_once '../services/OutsideSensorsService.php';
$notifications = new NotificationService();
$inside = new InsideSensorsService();
$insideT = $inside->getTemperature();
$insideH = $inside->getHumidity();
$outside = new OutsideSensorsService();
$outsideT = $outside->getTemperature();
$outsideH = $outside->getHumidity();
if ($outsideT === 'NaN' && $outsideH === 'NaN') {
    $condition = true;
}
if ($insideT === 'NaN' && $outsideH === 'NaN') {
    $condition = true;
}
if ($insideH === '0' && !file_exists("arduino.connection.inside.lock")) {
    //send notification
    $notifications->sendNotification('Inside_sensor_is_unconnected');
    $lock = fopen("arduino.connection.lock", "w");
    $date = date("Y-m-d H:i:s");
    fwrite($lock, "arduino locked at {$date} becouse inside sensors isn\\'t connected");
    fclose($lock);
} else {
    if (file_exists("arduino.connection.inside.lock")) {
 /**
  * Creates a new post for the given member
  *
  * @param Member $member
  *			The member creating the post. Will default to the calling member if not specified
  * @param string $content
  *			The content being loaded into the post
  * @param array $properties
  *			Additional properties to be bound into the post. 
  * @param int $parentId
  *			The ID of a micropost that is considered the 'parent' of this post
  * @param mixed $target
  *			The "target" of this post; may be a data object (ie context of the post) or a user/group
  * @param array $to
  *			The people/groups this post is being sent to. This is an array of
  *			- logged_in: boolean (logged in users; uses a system config setting to determine which group represents 'logged in'
  *			- members: an array, or comma separated string, of member IDs
  *			- groups: an array, or comma separated string, of group IDs
  * @return MicroPost 
  */
 public function createPost(DataObject $member, $content, $properties = null, $parentId = 0, $target = null, $to = null)
 {
     // backwards compatible
     if (is_string($properties)) {
         $properties = array('Title' => $properties);
     }
     if (!$member) {
         $member = $this->securityContext->getMember();
     }
     if (!$member->exists() && !$this->allowAnonymousPosts) {
         throw new Exception("Anonymous posting disallowed");
     }
     $post = MicroPost::create();
     $post->Content = $content;
     if ($properties && count($properties)) {
         foreach ($properties as $field => $value) {
             if (isset($this->allowedProperties[$field])) {
                 $post->{$field} = $value;
             }
         }
     }
     $post->OwnerID = $member->ID;
     $post->Target = $target;
     if ($parentId) {
         $parent = MicroPost::get()->restrictedByID($parentId);
         if ($parent) {
             $post->ParentID = $parentId;
             $post->ThreadID = $parent->ThreadID;
             $post->Target = $parent->Target;
         }
     }
     if (isset($to['public'])) {
         $post->PublicAccess = (bool) $to['public'];
     }
     $post->write();
     // if we're a good poster, scan its content, otherwise post process it for spam
     if ($member->Balance >= MicroBlogMember::BALANCE_THRESHOLD) {
         $post->analyseContent();
         $post->write();
     } else {
         $this->queuedJobService->queueJob(new ProcessPostJob($post));
     }
     // set its thread ID
     if (!$post->ParentID) {
         $post->ThreadID = $post->ID;
         $post->write();
     }
     if ($post->ID != $post->ThreadID) {
         $thread = MicroPost::get()->restrictedByID($post->ThreadID);
         if ($thread) {
             $owner = $thread->Owner();
             $this->transactionManager->run(function () use($post, $thread) {
                 $thread->NumReplies += 1;
                 $thread->write();
             }, $owner);
         }
     }
     $this->rewardMember($member, 2);
     if ($to) {
         $post->giveAccessTo($to);
     }
     // we stick this in here so the UI can update...
     $post->RemainingVotes = $member->VotesToGive;
     $post->extend('onCreated', $member, $target);
     if ($this->notificationService) {
         $this->notificationService->notify('MICRO_POST_CREATED', $post);
     }
     return $post;
 }