Beispiel #1
0
 public function beforeSave(Entity $entity)
 {
     if ($entity->get('type') == 'Post') {
         $post = $entity->get('post');
         $this->addMentionData($entity);
     }
 }
Beispiel #2
0
 protected function getDuplicateWhereClause(Entity $entity)
 {
     $data = array('OR' => array(array('firstName' => $entity->get('firstName'), 'lastName' => $entity->get('lastName'))));
     if ($entity->get('emailAddress')) {
         $data['OR'][] = array('emailAddress' => $entity->get('emailAddress'));
     }
     return $data;
 }
Beispiel #3
0
 protected function getDataFromEntity(Entity $entity)
 {
     $data = $entity->toArray();
     $fieldDefs = $entity->getFields();
     $fieldList = array_keys($fieldDefs);
     foreach ($fieldList as $field) {
         $type = null;
         if (!empty($fieldDefs[$field]['type'])) {
             $type = $fieldDefs[$field]['type'];
         }
         if ($type == Entity::DATETIME) {
             if (!empty($data[$field])) {
                 $data[$field] = $this->dateTime->convertSystemDateTime($data[$field]);
             }
         } else {
             if ($type == Entity::DATE) {
                 if (!empty($data[$field])) {
                     $data[$field] = $this->dateTime->convertSystemDate($data[$field]);
                 }
             } else {
                 if ($type == Entity::JSON_ARRAY) {
                     if (!empty($data[$field])) {
                         $list = $data[$field];
                         $newList = [];
                         foreach ($list as $item) {
                             $v = $item;
                             if ($item instanceof \StdClass) {
                                 $v = get_object_vars($v);
                             }
                             foreach ($v as $k => $w) {
                                 $v[$k] = $this->format($v[$k]);
                             }
                             $newList[] = $v;
                         }
                         $data[$field] = $newList;
                     }
                 } else {
                     if ($type == Entity::JSON_OBJECT) {
                         if (!empty($data[$field])) {
                             $value = $data[$field];
                             if ($value instanceof \StdClass) {
                                 $data[$field] = get_object_vars($value);
                             }
                             foreach ($data[$field] as $k => $w) {
                                 $data[$field][$k] = $this->format($data[$field][$k]);
                             }
                         }
                     }
                 }
             }
         }
         if (array_key_exists($field, $data)) {
             $data[$field] = $this->format($data[$field]);
         }
     }
     return $data;
 }
Beispiel #4
0
 public function beforeSave(Entity $entity)
 {
     if (!$entity->has('executeTime')) {
         $entity->set('executeTime', date('Y-m-d H:i:s'));
     }
     if (!$entity->has('attempts')) {
         $attempts = $this->getConfig()->get('cron.attempts', 0);
         $entity->set('attempts', $attempts);
     }
 }
Beispiel #5
0
 protected function handleAfterSaveAccounts(Entity $entity, array $options)
 {
     $accountIdChanged = $entity->has('accountId') && $entity->get('accountId') != $entity->getFetched('accountId');
     $titleChanged = $entity->has('title') && $entity->get('title') != $entity->getFetched('title');
     if ($accountIdChanged) {
         $accountId = $entity->get('accountId');
         if (empty($accountId)) {
             $this->unrelate($entity, 'accounts', $entity->getFetched('accountId'));
             return;
         }
     }
     if ($titleChanged) {
         if (empty($accountId)) {
             $accountId = $entity->getFetched('accountId');
             if (empty($accountId)) {
                 return;
             }
         }
     }
     if ($accountIdChanged || $titleChanged) {
         $pdo = $this->getEntityManager()->getPDO();
         $sql = "\n                SELECT id, role FROM account_contact\n                WHERE\n                    account_id = " . $pdo->quote($accountId) . " AND\n                    contact_id = " . $pdo->quote($entity->id) . " AND\n                    deleted = 0\n            ";
         $sth = $pdo->prepare($sql);
         $sth->execute();
         if ($row = $sth->fetch()) {
             if ($titleChanged && $entity->get('title') != $row['role']) {
                 $this->updateRelation($entity, 'accounts', $accountId, array('role' => $entity->get('title')));
             }
         } else {
             if ($accountIdChanged) {
                 $this->relate($entity, 'accounts', $accountId, array('role' => $entity->get('title')));
             }
         }
     }
 }
Beispiel #6
0
 public function save(Entity $entity, array $options = array())
 {
     $isNew = $entity->isNew();
     $result = parent::save($entity, $options);
     if ($isNew) {
         if (!empty($entity->id) && $entity->has('contents')) {
             $contents = $entity->get('contents');
             $this->getFileManager()->putContents('data/upload/' . $entity->id, $contents);
         }
     }
     return $result;
 }
Beispiel #7
0
 public function checkIsOwner(User $user, Entity $entity)
 {
     if ($entity->has('assignedUserId')) {
         if ($user->id === $entity->get('assignedUserId')) {
             return true;
         }
     }
     if ($user->id === $entity->get('createdById')) {
         return true;
     }
     return false;
 }
Beispiel #8
0
 public function checkInTeam(User $user, Entity $entity)
 {
     if ($entity->has('campaignId')) {
         $campaignId = $entity->get('campaignId');
         if (!$campaignId) {
             return;
         }
         $campaign = $this->getEntityManager()->getEntity('Campaign', $campaignId);
         if ($campaign && $this->getAclManager()->getImplementation('Campaign')->checkInTeam($user, $campaign)) {
             return true;
         }
     }
     return;
 }
Beispiel #9
0
 protected function afterRemove(Entity $entity, array $options = array())
 {
     if ($entity->get('fileId')) {
         $attachment = $this->getEntityManager()->getEntity('Attachment', $entity->get('fileId'));
         if ($attachment) {
             $this->getEntityManager()->removeEntity($attachment);
         }
     }
     $pdo = $this->getEntityManager()->getPDO();
     $sql = "DELETE FROM import_entity WHERE import_id = :importId";
     $sth = $pdo->prepare($sql);
     $sth->bindValue(':importId', $entity->id);
     $sth->execute();
     parent::afterRemove($entity, $options);
 }
Beispiel #10
0
 public function checkIsOwner(User $user, Entity $entity)
 {
     if ($entity->has('parentId') && $entity->has('parentType')) {
         $parentType = $entity->get('parentType');
         $parentId = $entity->get('parentId');
         if (!$parentType || !$parentId) {
             return;
         }
         $parent = $this->getEntityManager()->getEntity($parentType, $parentId);
         if ($parent && $parent->has('assignedUserId') && $parent->get('assignedUserId') === $user->id) {
             return true;
         }
     }
     return;
 }
Beispiel #11
0
 public function getEntityReminders(Entity $entity)
 {
     $pdo = $this->getEntityManager()->getPDO();
     $reminders = array();
     $sql = "\n            SELECT id, `seconds`, `type`\n            FROM `reminder`\n            WHERE\n                `entity_type` = " . $pdo->quote($entity->getEntityType()) . " AND\n                `entity_id` = " . $pdo->quote($entity->id) . " AND\n                `deleted` = 0\n                ORDER BY `seconds` ASC\n        ";
     $sth = $pdo->prepare($sql);
     $sth->execute();
     $rows = $sth->fetchAll(\PDO::FETCH_ASSOC);
     foreach ($rows as $row) {
         $o = new \StdClass();
         $o->seconds = intval($row['seconds']);
         $o->type = $row['type'];
         $reminders[] = $o;
     }
     return $reminders;
 }
Beispiel #12
0
 public function sendInvitations(Entity $entity)
 {
     $invitationManager = $this->getInvitationManager();
     $users = $entity->get('users');
     foreach ($users as $user) {
         $invitationManager->sendInvitation($entity, $user, 'users');
     }
     $contacts = $entity->get('contacts');
     foreach ($contacts as $contact) {
         $invitationManager->sendInvitation($entity, $contact, 'contacts');
     }
     $leads = $entity->get('leads');
     foreach ($leads as $lead) {
         $invitationManager->sendInvitation($entity, $lead, 'leads');
     }
     return true;
 }
Beispiel #13
0
 public function beforeRemove(Entity $entity, array $options = array())
 {
     if (!empty($options['silent']) && !empty($options['noNotifications'])) {
         return;
     }
     $entityType = $entity->getEntityType();
     if ($this->checkHasStream($entityType)) {
         $followersData = $this->getStreamService()->getEntityFollowers($entity);
         foreach ($followersData['idList'] as $userId) {
             if ($userId === $this->getUser()->id) {
                 continue;
             }
             $notification = $this->getEntityManager()->getEntity('Notification');
             $notification->set(array('userId' => $userId, 'type' => 'EntityRemoved', 'data' => array('entityType' => $entity->getEntityType(), 'entityId' => $entity->id, 'entityName' => $entity->get('name'), 'userId' => $this->getUser()->id, 'userName' => $this->getUser()->get('name'))));
             $this->getEntityManager()->saveEntity($notification);
         }
     }
 }
Beispiel #14
0
 public function process(Entity $entity)
 {
     if ($entity->has('assignedUserId') && $entity->get('assignedUserId')) {
         $assignedUserId = $entity->get('assignedUserId');
         if ($assignedUserId != $this->getUser()->id && $entity->isFieldChanged('assignedUserId')) {
             $notification = $this->getEntityManager()->getEntity('Notification');
             $notification->set(array('type' => 'Assign', 'userId' => $assignedUserId, 'data' => array('entityType' => $entity->getEntityType(), 'entityId' => $entity->id, 'entityName' => $entity->get('name'), 'isNew' => $entity->isNew(), 'userId' => $this->getUser()->id, 'userName' => $this->getUser()->get('name'))));
             $this->getEntityManager()->saveEntity($notification);
         }
     }
 }
Beispiel #15
0
 public function send(Entity $reminder)
 {
     $user = $this->getEntityManager()->getEntity('User', $reminder->get('userId'));
     $entity = $this->getEntityManager()->getEntity($reminder->get('entityType'), $reminder->get('entityId'));
     $emailAddress = $user->get('emailAddress');
     if (empty($user) || empty($emailAddress) || empty($entity)) {
         return;
     }
     $email = $this->getEntityManager()->getEntity('Email');
     $email->set('to', $emailAddress);
     $subjectTpl = $this->getTemplate('ReminderSubject');
     $bodyTpl = $this->getTemplate('ReminderBody');
     $subject = $this->parseInvitationTemplate($subjectTpl, $entity, $user);
     $subject = str_replace(array("\n", "\r"), '', $subject);
     $body = $this->parseInvitationTemplate($bodyTpl, $entity, $user);
     $email->set('subject', $subject);
     $email->set('body', $body);
     $email->set('isHtml', true);
     $this->getEntityManager()->saveEntity($email);
     $emailSender = $this->mailSender;
     $emailSender->send($email);
     $this->getEntityManager()->removeEntity($email);
 }
 public function afterSave(Entity $entity)
 {
     if ($this->getConfig()->get('assignmentEmailNotifications') && $entity->has('assignedUserId') && in_array($entity->getEntityName(), $this->getConfig()->get('assignmentEmailNotificationsEntityList', array()))) {
         $userId = $entity->get('assignedUserId');
         if (!empty($userId) && $userId != $this->getUser()->id && $entity->isFieldChanged('assignedUserId')) {
             $job = $this->getEntityManager()->getEntity('Job');
             $job->set(array('serviceName' => 'EmailNotification', 'method' => 'notifyAboutAssignmentJob', 'data' => json_encode(array('userId' => $userId, 'assignerUserId' => $this->getUser()->id, 'entityId' => $entity->id, 'entityType' => $entity->getEntityName())), 'executeTime' => date('Y-m-d H:i:s')));
             $this->getEntityManager()->saveEntity($job);
         }
     }
 }
Beispiel #17
0
 public function afterSave(Entity $entity)
 {
     if ($entity->isNew()) {
         $parentType = $entity->get('parentType');
         $parentId = $entity->get('parentId');
         $superParentType = $entity->get('superParentType');
         $superParentTypeId = $entity->get('superParentTypeId');
         $userIdList = [];
         if ($parentType && $parentId) {
             $userIdList = array_merge($userIdList, $this->getSubscriberIdList($parentType, $parentId));
         }
         if ($superParentType && $superParentTypeId) {
             $userIdList = array_merge($userIdList, $this->getSubscriberIdList($superParentType, $superParentTypeId));
         }
         //$userIdList = array_merge($userIdList, $this->getMentionedUserIdList($entity));
         $userIdList = array_unique($userIdList);
         if (!empty($userIdList)) {
             $this->getNotificationService()->notifyAboutNote($userIdList, $entity);
         }
     }
 }
Beispiel #18
0
 protected function handleAfterSaveContacts(Entity $entity, array $options)
 {
     $contactIdChanged = $entity->has('contactId') && $entity->get('contactId') != $entity->getFetched('contactId');
     if ($contactIdChanged) {
         $contactId = $entity->get('contactId');
         if (empty($contactId)) {
             $this->unrelate($entity, 'contacts', $entity->getFetched('contactId'));
             return;
         }
     }
     if ($contactIdChanged) {
         $pdo = $this->getEntityManager()->getPDO();
         $sql = "\n                SELECT id FROM case_contact\n                WHERE\n                    contact_id = " . $pdo->quote($contactId) . " AND\n                    case_id = " . $pdo->quote($entity->id) . " AND\n                    deleted = 0\n            ";
         $sth = $pdo->prepare($sql);
         $sth->execute();
         if (!$sth->fetch()) {
             $this->relate($entity, 'contacts', $contactId);
         }
     }
 }
Beispiel #19
0
 public function prepareEntityForOutput(Entity $entity)
 {
     foreach ($this->internalFields as $field) {
         $entity->clear($field);
     }
 }
Beispiel #20
0
 public function checkInTeam(User $user, Entity $entity)
 {
     $userTeamIds = $user->get('teamsIds');
     if (!$entity->hasRelation('teams') || !$entity->hasField('teamsIds')) {
         return false;
     }
     if (!$entity->has('teamsIds')) {
         $entity->loadLinkMultipleField('teams');
     }
     $teamIds = $entity->get('teamsIds');
     if (empty($teamIds)) {
         return false;
     }
     foreach ($userTeamIds as $id) {
         if (in_array($id, $teamIds)) {
             return true;
         }
     }
     return false;
 }
Beispiel #21
0
 public function afterSave(Entity $entity, array $options = array())
 {
     $entityName = $entity->getEntityType();
     if ($this->checkHasStream($entity)) {
         if ($entity->isNew()) {
             $userIdList = [];
             $assignedUserId = $entity->get('assignedUserId');
             $createdById = $entity->get('createdById');
             if ($this->getConfig()->get('followCreatedEntities') && !empty($createdById)) {
                 $userIdList[] = $createdById;
             }
             if (!empty($assignedUserId) && !in_array($assignedUserId, $userIdList)) {
                 $userIdList[] = $assignedUserId;
             }
             if (!empty($userIdList)) {
                 $this->getStreamService()->followEntityMass($entity, $userIdList);
             }
             if (empty($options['noStream'])) {
                 $this->getStreamService()->noteCreate($entity);
             }
             if (in_array($this->getUser()->id, $userIdList)) {
                 $entity->set('isFollowed', true);
             }
             $autofollowUserIdList = $this->getAutofollowUserIdList($entity, $userIdList);
             foreach ($autofollowUserIdList as $i => $userId) {
                 if (in_array($userId, $userIdList)) {
                     unset($autofollowUserIdList[$i]);
                 }
             }
             $autofollowUserIdList = array_values($autofollowUserIdList);
             if (!empty($autofollowUserIdList)) {
                 $job = $this->getEntityManager()->getEntity('Job');
                 $job->set(array('serviceName' => 'Stream', 'method' => 'afterRecordCreatedJob', 'data' => array('userIdList' => $autofollowUserIdList, 'entityType' => $entity->getEntityType(), 'entityId' => $entity->id)));
                 $this->getEntityManager()->saveEntity($job);
             }
         } else {
             if (empty($options['noStream'])) {
                 if ($entity->isFieldChanged('assignedUserId')) {
                     $assignedUserId = $entity->get('assignedUserId');
                     if (!empty($assignedUserId)) {
                         $this->getStreamService()->followEntity($entity, $assignedUserId);
                         $this->getStreamService()->noteAssign($entity);
                         if ($this->getUser()->id === $assignedUserId) {
                             $entity->set('isFollowed', true);
                         }
                     }
                 }
                 $this->getStreamService()->handleAudited($entity);
                 $statusFields = $this->getStatusFields();
                 if (array_key_exists($entityName, $this->statusFields)) {
                     $field = $this->statusFields[$entityName];
                     $value = $entity->get($field);
                     if (!empty($value) && $value != $entity->getFetched($field)) {
                         $this->getStreamService()->noteStatus($entity, $field);
                     }
                 }
             }
         }
     }
     if ($entity->isNew() && empty($options['noStream']) && $this->getMetadata()->get("scopes.{$entityName}.tab")) {
         $this->handleCreateRelated($entity);
     }
 }
Beispiel #22
0
 protected function handleSpecifiedRelations(Entity $entity)
 {
     $relationTypes = array($entity::HAS_MANY, $entity::MANY_MANY, $entity::HAS_CHILDREN);
     foreach ($entity->getRelations() as $name => $defs) {
         if (in_array($defs['type'], $relationTypes)) {
             $fieldName = $name . 'Ids';
             $columnsFieldsName = $name . 'Columns';
             if ($entity->has($fieldName) || $entity->has($columnsFieldsName)) {
                 if ($this->getMetadata()->get("entityDefs." . $entity->getEntityType() . ".fields.{$name}.noSave")) {
                     continue;
                 }
                 if ($entity->has($fieldName)) {
                     $specifiedIds = $entity->get($fieldName);
                 } else {
                     $specifiedIds = array();
                     foreach ($entity->get($columnsFieldsName) as $id => $d) {
                         $specifiedIds[] = $id;
                     }
                 }
                 if (is_array($specifiedIds)) {
                     $toRemoveIds = array();
                     $existingIds = array();
                     $toUpdateIds = array();
                     $existingColumnsData = new \stdClass();
                     $defs = array();
                     $columns = $this->getMetadata()->get("entityDefs." . $entity->getEntityType() . ".fields.{$name}.columns");
                     if (!empty($columns)) {
                         $columnData = $entity->get($columnsFieldsName);
                         $defs['additionalColumns'] = $columns;
                     }
                     $foreignCollection = $entity->get($name, $defs);
                     if ($foreignCollection) {
                         foreach ($foreignCollection as $foreignEntity) {
                             $existingIds[] = $foreignEntity->id;
                             if (!empty($columns)) {
                                 $data = new \stdClass();
                                 foreach ($columns as $columnName => $columnField) {
                                     $foreignId = $foreignEntity->id;
                                     $data->{$columnName} = $foreignEntity->get($columnField);
                                 }
                                 $existingColumnsData->{$foreignId} = $data;
                                 $entity->setFetched($columnsFieldsName, $existingColumnsData);
                             }
                         }
                     }
                     if ($entity->has($fieldName)) {
                         $entity->setFetched($fieldName, $existingIds);
                     }
                     if ($entity->has($columnsFieldsName) && !empty($columns)) {
                         $entity->setFetched($columnsFieldsName, $existingColumnsData);
                     }
                     foreach ($existingIds as $id) {
                         if (!in_array($id, $specifiedIds)) {
                             $toRemoveIds[] = $id;
                         } else {
                             if (!empty($columns)) {
                                 foreach ($columns as $columnName => $columnField) {
                                     if ($columnData->{$id}->{$columnName} != $existingColumnsData->{$id}->{$columnName}) {
                                         $toUpdateIds[] = $id;
                                     }
                                 }
                             }
                         }
                     }
                     foreach ($specifiedIds as $id) {
                         if (!in_array($id, $existingIds)) {
                             $data = null;
                             if (!empty($columns) && isset($columnData->{$id})) {
                                 $data = $columnData->{$id};
                             }
                             $this->relate($entity, $name, $id, $data);
                         }
                     }
                     foreach ($toRemoveIds as $id) {
                         $this->unrelate($entity, $name, $id);
                     }
                     if (!empty($columns)) {
                         foreach ($toUpdateIds as $id) {
                             $data = $columnData->{$id};
                             $this->updateRelation($entity, $name, $id, $data);
                         }
                     }
                 }
             }
         }
     }
 }
Beispiel #23
0
 protected function sendPassword(Entity $user, $password)
 {
     $emailAddress = $user->get('emailAddress');
     if (empty($emailAddress)) {
         return;
     }
     $email = $this->getEntityManager()->getEntity('Email');
     if (!$this->getConfig()->get('smtpServer')) {
         return;
     }
     $subject = $this->getLanguage()->translate('accountInfoEmailSubject', 'messages', 'User');
     $body = $this->getLanguage()->translate('accountInfoEmailBody', 'messages', 'User');
     $body = str_replace('{userName}', $user->get('userName'), $body);
     $body = str_replace('{password}', $password, $body);
     $body = str_replace('{siteUrl}', $this->getConfig()->get('siteUrl'), $body);
     $email->set(array('subject' => $subject, 'body' => $body, 'isHtml' => false, 'to' => $emailAddress));
     $this->getMailSender()->send($email);
 }
Beispiel #24
0
 protected function beforeSave(Entity $entity, array $options)
 {
     $eaRepositoty = $this->getEntityManager()->getRepository('EmailAddress');
     if ($entity->has('attachmentsIds')) {
         $attachmentsIds = $entity->get('attachmentsIds');
         if (!empty($attachmentsIds)) {
             $entity->set('hasAttachment', true);
         }
     }
     if ($entity->has('from') || $entity->has('to') || $entity->has('cc') || $entity->has('bcc') || $entity->has('replyTo')) {
         if (!$entity->has('usersIds')) {
             $entity->loadLinkMultipleField('users');
         }
         if ($entity->has('from')) {
             $from = trim($entity->get('from'));
             if (!empty($from)) {
                 $ids = $eaRepositoty->getIds(array($from));
                 if (!empty($ids)) {
                     $entity->set('fromEmailAddressId', $ids[0]);
                     $this->setUsersIdsByEmailAddressId($entity, $ids[0]);
                 }
             } else {
                 $entity->set('fromEmailAddressId', null);
             }
         }
         if ($entity->has('to')) {
             $this->prepareAddressess($entity, 'to');
         }
         if ($entity->has('cc')) {
             $this->prepareAddressess($entity, 'cc');
         }
         if ($entity->has('bcc')) {
             $this->prepareAddressess($entity, 'bcc');
         }
         if ($entity->has('replyTo')) {
             $this->prepareAddressess($entity, 'replyTo');
         }
         $usersIds = $entity->get('usersIds');
         $assignedUserId = $entity->get('assignedUserId');
         if (!empty($assignedUserId) && !in_array($assignedUserId, $usersIds)) {
             $usersIds[] = $assignedUserId;
         }
         $entity->set('usersIds', $usersIds);
     }
     parent::beforeSave($entity, $options);
     $parentId = $entity->get('parentId');
     $parentType = $entity->get('parentType');
     if (!empty($parentId) || !empty($parentType)) {
         $parent = $this->getEntityManager()->getEntity($parentType, $parentId);
         if (!empty($parent)) {
             if ($parent->getEntityType() == 'Account') {
                 $accountId = $parent->id;
             } else {
                 if ($parent->has('accountId')) {
                     $accountId = $parent->get('accountId');
                 }
             }
             if (!empty($accountId)) {
                 $account = $this->getEntityManager()->getEntity('Account', $accountId);
                 if ($account) {
                     $entity->set('accountId', $accountId);
                     $entity->set('accountName', $account->get('name'));
                 }
             }
         }
     }
 }
Beispiel #25
0
 public function storeEntityPhoneNumber(Entity $entity)
 {
     $phone = trim($entity->get('phoneNumber'));
     $phoneNumberData = null;
     if ($entity->has('phoneNumberData')) {
         $phoneNumberData = $entity->get('phoneNumberData');
     }
     $pdo = $this->getEntityManager()->getPDO();
     if ($phoneNumberData !== null && is_array($phoneNumberData)) {
         $previousPhoneNumberData = array();
         if (!$entity->isNew()) {
             $previousPhoneNumberData = $this->getPhoneNumberData($entity);
         }
         $hash = array();
         foreach ($phoneNumberData as $row) {
             $key = $row->phoneNumber;
             if (!empty($key)) {
                 $hash[$key] = array('primary' => $row->primary ? true : false, 'type' => $row->type);
             }
         }
         $hashPrev = array();
         foreach ($previousPhoneNumberData as $row) {
             $key = $row->phoneNumber;
             if (!empty($key)) {
                 $hashPrev[$key] = array('primary' => $row->primary ? true : false, 'type' => $row->type);
             }
         }
         $primary = false;
         $toCreate = array();
         $toUpdate = array();
         $toRemove = array();
         foreach ($hash as $key => $data) {
             $new = true;
             $changed = false;
             if ($hash[$key]['primary']) {
                 $primary = $key;
             }
             if (array_key_exists($key, $hashPrev)) {
                 $new = false;
                 $changed = $hash[$key]['type'] != $hashPrev[$key]['type'];
                 if ($hash[$key]['primary']) {
                     if ($hash[$key]['primary'] == $hashPrev[$key]['primary']) {
                         $primary = false;
                     }
                 }
             }
             if ($new) {
                 $toCreate[] = $key;
             }
             if ($changed) {
                 $toUpdate[] = $key;
             }
         }
         foreach ($hashPrev as $key => $data) {
             if (!array_key_exists($key, $hash)) {
                 $toRemove[] = $key;
             }
         }
         foreach ($toRemove as $number) {
             $phoneNumber = $this->getByNumber($number);
             if ($phoneNumber) {
                 $query = "\n                            DELETE FROM  entity_phone_number\n                            WHERE\n                                entity_id = " . $pdo->quote($entity->id) . " AND\n                                entity_type = " . $pdo->quote($entity->getEntityName()) . " AND\n                                phone_number_id = " . $pdo->quote($phoneNumber->id) . "\n                        ";
                 $sth = $pdo->prepare($query);
                 $sth->execute();
             }
         }
         foreach ($toUpdate as $number) {
             $phoneNumber = $this->getByNumber($number);
             if ($phoneNumber) {
                 $phoneNumber->set(array('type' => $hash[$number]['type']));
                 $this->save($phoneNumber);
             }
         }
         foreach ($toCreate as $number) {
             $phoneNumber = $this->getByNumber($number);
             if (!$phoneNumber) {
                 $phoneNumber = $this->get();
                 $phoneNumber->set(array('name' => $number, 'type' => $hash[$number]['type']));
                 $this->save($phoneNumber);
             } else {
                 if ($phoneNumber->get('type') != $hash[$number]['type']) {
                     $phoneNumber->set(array('type' => $hash[$number]['type']));
                     $this->save($phoneNumber);
                 }
             }
             $query = "\n                        INSERT entity_phone_number\n                            (entity_id, entity_type, phone_number_id, `primary`)\n                            VALUES\n                            (\n                                " . $pdo->quote($entity->id) . ",\n                                " . $pdo->quote($entity->getEntityName()) . ",\n                                " . $pdo->quote($phoneNumber->id) . ",\n                                " . $pdo->quote((int) ($number === $primary)) . "\n                            )\n                    ";
             $sth = $pdo->prepare($query);
             $sth->execute();
         }
         if ($primary) {
             $phoneNumber = $this->getByNumber($primary);
             if ($phoneNumber) {
                 $query = "\n                            UPDATE entity_phone_number\n                            SET `primary` = 0\n                            WHERE\n                                entity_id = " . $pdo->quote($entity->id) . " AND\n                                entity_type = " . $pdo->quote($entity->getEntityName()) . " AND\n                                `primary` = 1 AND\n                                deleted = 0\n                        ";
                 $sth = $pdo->prepare($query);
                 $sth->execute();
                 $query = "\n                            UPDATE entity_phone_number\n                            SET `primary` = 1\n                            WHERE\n                                entity_id = " . $pdo->quote($entity->id) . " AND\n                                entity_type = " . $pdo->quote($entity->getEntityName()) . " AND\n                                phone_number_id = " . $pdo->quote($phoneNumber->id) . " AND \n                                deleted = 0\n                        ";
                 $sth = $pdo->prepare($query);
                 $sth->execute();
             }
         }
     } else {
         $entityRepository = $this->getEntityManager()->getRepository($entity->getEntityName());
         if (!empty($phone)) {
             if ($phone != $entity->getFetched('phoneNumber')) {
                 $phoneNumberNew = $this->where(array('name' => $phone))->findOne();
                 $isNewPhoneNumber = false;
                 if (!$phoneNumberNew) {
                     $phoneNumberNew = $this->get();
                     $phoneNumberNew->set('name', $phone);
                     $defaultType = $this->getEntityManager()->getFoxMetadata()->get('entityDefs.' . $entity->getEntityName() . '.fields.phoneNumber.defaultType');
                     $phoneNumberNew->set('type', $defaultType);
                     $this->save($phoneNumberNew);
                     $isNewPhoneNumber = true;
                 }
                 $phoneOld = $entity->getFetched('phoneNumber');
                 if (!empty($phoneOld)) {
                     $phoneNumberOld = $this->getByNumber($phoneOld);
                     $entityRepository->unrelate($entity, 'phoneNumbers', $phoneNumberOld);
                 }
                 $entityRepository->relate($entity, 'phoneNumbers', $phoneNumberNew);
                 $query = "\n                            UPDATE entity_phone_number\n                            SET `primary` = 1\n                            WHERE\n                                entity_id = " . $pdo->quote($entity->id) . " AND\n                                entity_type = " . $pdo->quote($entity->getEntityName()) . " AND\n                                phone_number_id = " . $pdo->quote($phoneNumberNew->id) . "\n                        ";
                 $sth = $pdo->prepare($query);
                 $sth->execute();
             }
         } else {
             $phoneOld = $entity->getFetched('phoneNumber');
             if (!empty($phoneOld)) {
                 $phoneNumberOld = $this->getByNumber($phoneOld);
                 $entityRepository->unrelate($entity, 'phoneNumbers', $phoneNumberOld);
             }
         }
     }
 }
Beispiel #26
0
 public function fetchFromMailServer(Entity $emailAccount)
 {
     if ($emailAccount->get('status') != 'Active') {
         throw new Error();
     }
     $importer = new \Fox\Core\Mail\Importer($this->getEntityManager(), $this->getFileManager(), $this->getConfig());
     $maxSize = $this->getConfig()->get('emailMessageMaxSize');
     $teamId = $emailAccount->get('teamId');
     $userId = $this->getUser()->id;
     if ($emailAccount->get('assignToUserId')) {
         $userId = $emailAccount->get('assignToUserId');
     }
     $teamIds = array();
     if (!empty($teamId)) {
         $teamIds[] = $teamId;
     }
     $filterCollection = $this->getEntityManager()->getRepository('EmailFilter')->where(['OR' => [['parentType' => $emailAccount->getEntityType(), 'parentId' => $emailAccount->id], ['parentId' => null]]])->find();
     $fetchData = json_decode($emailAccount->get('fetchData'), true);
     if (empty($fetchData)) {
         $fetchData = array();
     }
     if (!array_key_exists('lastUID', $fetchData)) {
         $fetchData['lastUID'] = array();
     }
     if (!array_key_exists('lastUID', $fetchData)) {
         $fetchData['lastDate'] = array();
     }
     $imapParams = array('host' => $emailAccount->get('host'), 'port' => $emailAccount->get('port'), 'user' => $emailAccount->get('username'), 'password' => $this->getCrypt()->decrypt($emailAccount->get('password')));
     if ($emailAccount->get('ssl')) {
         $imapParams['ssl'] = 'SSL';
     }
     $storage = new \Fox\Core\Mail\Mail\Storage\Imap($imapParams);
     $monitoredFolders = $emailAccount->get('monitoredFolders');
     if (empty($monitoredFolders)) {
         $monitoredFolders = 'INBOX';
     }
     $portionLimit = $this->getConfig()->get('inboundEmailMaxPortionSize', self::PORTION_LIMIT);
     $monitoredFoldersArr = explode(',', $monitoredFolders);
     foreach ($monitoredFoldersArr as $folder) {
         $folder = mb_convert_encoding(trim($folder), 'UTF7-IMAP', 'UTF-8');
         try {
             $storage->selectFolder($folder);
         } catch (\Exception $e) {
             $GLOBALS['log']->error('InboundEmail ' . $emailAccount->id . ' (Select Folder) [' . $e->getCode() . '] ' . $e->getMessage());
             continue;
         }
         $lastUID = 0;
         $lastDate = 0;
         if (!empty($fetchData['lastUID'][$folder])) {
             $lastUID = $fetchData['lastUID'][$folder];
         }
         if (!empty($fetchData['lastDate'][$folder])) {
             $lastDate = $fetchData['lastDate'][$folder];
         }
         $ids = $storage->getIdsFromUID($lastUID);
         if (count($ids) == 1 && !empty($lastUID)) {
             if ($storage->getUniqueId($ids[0]) == $lastUID) {
                 continue;
             }
         }
         $k = 0;
         foreach ($ids as $i => $id) {
             $toSkip = false;
             if ($k == count($ids) - 1) {
                 $lastUID = $storage->getUniqueId($id);
             }
             if ($maxSize) {
                 if ($storage->getSize($id) > $maxSize * 1024 * 1024) {
                     $k++;
                     continue;
                 }
             }
             $message = null;
             $email = null;
             try {
                 $message = $storage->getMessage($id);
                 if ($message && isset($message->from)) {
                     $fromString = $message->from;
                     if (preg_match('/MAILER-DAEMON|POSTMASTER/i', $fromString)) {
                         $toSkip = true;
                         try {
                             $this->processBouncedMessage($message);
                         } catch (\Exception $e) {
                             $GLOBALS['log']->error('InboundEmail ' . $emailAccount->id . ' (Process Bounced Message: [' . $e->getCode() . '] ' . $e->getMessage());
                         }
                     }
                 }
                 if (!$toSkip) {
                     try {
                         $email = $importer->importMessage($message, $userId, $teamIds, $filterCollection);
                     } catch (\Exception $e) {
                         $GLOBALS['log']->error('InboundEmail ' . $emailAccount->id . ' (Import Message): [' . $e->getCode() . '] ' . $e->getMessage());
                     }
                 }
             } catch (\Exception $e) {
                 $GLOBALS['log']->error('InboundEmail ' . $emailAccount->id . ' (Get Message): [' . $e->getCode() . '] ' . $e->getMessage());
             }
             if (!empty($email)) {
                 if (!$emailAccount->get('createCase')) {
                     $this->noteAboutEmail($email);
                 }
                 if ($emailAccount->get('createCase')) {
                     $this->createCase($emailAccount, $email);
                 } else {
                     if ($emailAccount->get('reply')) {
                         $user = $this->getEntityManager()->getEntity('User', $userId);
                         $this->autoReply($emailAccount, $email, $user);
                     }
                 }
             }
             if ($k == count($ids) - 1) {
                 if ($message && isset($message->date)) {
                     $dt = new \DateTime($message->date);
                     if ($dt) {
                         $dateSent = $dt->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i:s');
                         $lastDate = $dateSent;
                     }
                 }
             }
             if ($k == $portionLimit - 1) {
                 $lastUID = $storage->getUniqueId($id);
                 break;
             }
             $k++;
         }
         $fetchData['lastUID'][$folder] = $lastUID;
         $fetchData['lastDate'][$folder] = $lastDate;
         $emailAccount->set('fetchData', json_encode($fetchData));
         $this->getEntityManager()->saveEntity($emailAccount, array('silent' => true));
     }
     return true;
 }
Beispiel #27
0
 public function getEntityFollowers(Entity $entity, $offset = 0, $limit = false)
 {
     $query = $this->getEntityManager()->getQuery();
     $pdo = $this->getEntityManager()->getPDO();
     if (!$limit) {
         $limit = 200;
     }
     $sql = $query->createSelectQuery('User', array('select' => ['id', 'name'], 'customJoin' => "\n                JOIN subscription AS `subscription` ON\n                    subscription.user_id = user.id AND\n                    subscription.entity_id = " . $query->quote($entity->id) . " AND\n                    subscription.entity_type = " . $query->quote($entity->getEntityType()) . "\n            ", 'offset' => $offset, 'limit' => $limit, 'whereClause' => array('isActive' => true), 'orderBy' => [['LIST:id:' . $this->getUser()->id, 'DESC'], ['name']]));
     $sth = $pdo->prepare($sql);
     $sth->execute();
     $data = array('idList' => [], 'nameMap' => new \StdClass());
     while ($row = $sth->fetch(\PDO::FETCH_ASSOC)) {
         $id = $row['id'];
         $data['idList'][] = $id;
         $data['nameMap']->{$id} = $row['name'];
     }
     return $data;
 }
Beispiel #28
0
 public function storeEntityEmailAddress(Entity $entity)
 {
     $email = trim($entity->get('emailAddress'));
     $emailAddressData = null;
     if ($entity->has('emailAddressData')) {
         $emailAddressData = $entity->get('emailAddressData');
     }
     $pdo = $this->getEntityManager()->getPDO();
     if ($emailAddressData !== null && is_array($emailAddressData)) {
         $previousEmailAddressData = array();
         if (!$entity->isNew()) {
             $previousEmailAddressData = $this->getEmailAddressData($entity);
         }
         $hash = array();
         foreach ($emailAddressData as $row) {
             $key = $row->emailAddress;
             if (!empty($key)) {
                 $hash[$key] = array('primary' => $row->primary ? true : false, 'optOut' => $row->optOut ? true : false, 'invalid' => $row->invalid ? true : false);
             }
         }
         $hashPrev = array();
         foreach ($previousEmailAddressData as $row) {
             $key = $row->emailAddress;
             if (!empty($key)) {
                 $hashPrev[$key] = array('primary' => $row->primary ? true : false, 'optOut' => $row->optOut ? true : false, 'invalid' => $row->invalid ? true : false);
             }
         }
         $primary = false;
         $toCreate = array();
         $toUpdate = array();
         $toRemove = array();
         foreach ($hash as $key => $data) {
             $new = true;
             $changed = false;
             if ($hash[$key]['primary']) {
                 $primary = $key;
             }
             if (array_key_exists($key, $hashPrev)) {
                 $new = false;
                 $changed = $hash[$key]['optOut'] != $hashPrev[$key]['optOut'] || $hash[$key]['invalid'] != $hashPrev[$key]['invalid'];
                 if ($hash[$key]['primary']) {
                     if ($hash[$key]['primary'] == $hashPrev[$key]['primary']) {
                         $primary = false;
                     }
                 }
             }
             if ($new) {
                 $toCreate[] = $key;
             }
             if ($changed) {
                 $toUpdate[] = $key;
             }
         }
         foreach ($hashPrev as $key => $data) {
             if (!array_key_exists($key, $hash)) {
                 $toRemove[] = $key;
             }
         }
         foreach ($toRemove as $address) {
             $emailAddress = $this->getByAddress($address);
             if ($emailAddress) {
                 $query = "\n                            DELETE FROM entity_email_address\n                            WHERE\n                                entity_id = " . $pdo->quote($entity->id) . " AND\n                                entity_type = " . $pdo->quote($entity->getEntityName()) . " AND\n                                email_address_id = " . $pdo->quote($emailAddress->id) . "\n                        ";
                 $sth = $pdo->prepare($query);
                 $sth->execute();
             }
         }
         foreach ($toUpdate as $address) {
             $emailAddress = $this->getByAddress($address);
             if ($emailAddress) {
                 $emailAddress->set(array('optOut' => $hash[$address]['optOut'], 'invalid' => $hash[$address]['invalid']));
                 $this->save($emailAddress);
             }
         }
         foreach ($toCreate as $address) {
             $emailAddress = $this->getByAddress($address);
             if (!$emailAddress) {
                 $emailAddress = $this->get();
                 $emailAddress->set(array('name' => $address, 'optOut' => $hash[$address]['optOut'], 'invalid' => $hash[$address]['invalid']));
                 $this->save($emailAddress);
             } else {
                 if ($emailAddress->get('optOut') != $hash[$address]['optOut'] || $emailAddress->get('invalid') != $hash[$address]['invalid']) {
                     $emailAddress->set(array('optOut' => $hash[$address]['optOut'], 'invalid' => $hash[$address]['invalid']));
                     $this->save($emailAddress);
                 }
             }
             $query = "\n                        INSERT entity_email_address\n                            (entity_id, entity_type, email_address_id, `primary`)\n                            VALUES\n                            (\n                                " . $pdo->quote($entity->id) . ",\n                                " . $pdo->quote($entity->getEntityName()) . ",\n                                " . $pdo->quote($emailAddress->id) . ",\n                                " . $pdo->quote((int) ($address === $primary)) . "\n                            )\n                    ";
             $sth = $pdo->prepare($query);
             $sth->execute();
         }
         if ($primary) {
             $emailAddress = $this->getByAddress($primary);
             if ($emailAddress) {
                 $query = "\n                            UPDATE entity_email_address\n                            SET `primary` = 0\n                            WHERE\n                                entity_id = " . $pdo->quote($entity->id) . " AND\n                                entity_type = " . $pdo->quote($entity->getEntityName()) . " AND\n                                `primary` = 1 AND\n                                deleted = 0\n                        ";
                 $sth = $pdo->prepare($query);
                 $sth->execute();
                 $query = "\n                            UPDATE entity_email_address\n                            SET `primary` = 1\n                            WHERE\n                                entity_id = " . $pdo->quote($entity->id) . " AND\n                                entity_type = " . $pdo->quote($entity->getEntityName()) . " AND\n                                email_address_id = " . $pdo->quote($emailAddress->id) . " AND\n                                deleted = 0\n                        ";
                 $sth = $pdo->prepare($query);
                 $sth->execute();
             }
         }
     } else {
         $entityRepository = $this->getEntityManager()->getRepository($entity->getEntityName());
         if (!empty($email)) {
             if ($email != $entity->getFetched('emailAddress')) {
                 $emailAddressNew = $this->where(array('lower' => strtolower($email)))->findOne();
                 $isNewEmailAddress = false;
                 if (!$emailAddressNew) {
                     $emailAddressNew = $this->get();
                     $emailAddressNew->set('name', $email);
                     $this->save($emailAddressNew);
                     $isNewEmailAddress = true;
                 }
                 $emailOld = $entity->getFetched('emailAddress');
                 if (!empty($emailOld)) {
                     $emailAddressOld = $this->getByAddress($emailOld);
                     $entityRepository->unrelate($entity, 'emailAddresses', $emailAddressOld);
                 }
                 $entityRepository->relate($entity, 'emailAddresses', $emailAddressNew);
                 $query = "\n                            UPDATE entity_email_address\n                            SET `primary` = 1\n                            WHERE\n                                entity_id = " . $pdo->quote($entity->id) . " AND\n                                entity_type = " . $pdo->quote($entity->getEntityName()) . " AND\n                                email_address_id = " . $pdo->quote($emailAddressNew->id) . "\n                        ";
                 $sth = $pdo->prepare($query);
                 $sth->execute();
             }
         } else {
             $emailOld = $entity->getFetched('emailAddress');
             if (!empty($emailOld)) {
                 $emailAddressOld = $this->getByAddress($emailOld);
                 $entityRepository->unrelate($entity, 'emailAddresses', $emailAddressOld);
             }
         }
     }
 }
Beispiel #29
0
 protected function sendQueueItem(Entity $queueItem, Entity $massEmail, Entity $emailTemplate, $attachmetList = [], $campaign = null, $isTest = false)
 {
     $target = $this->getEntityManager()->getEntity($queueItem->get('targetType'), $queueItem->get('targetId'));
     if (!$target || !$target->id || !$target->get('emailAddress')) {
         $queueItem->set('status', 'Failed');
         $this->getEntityManager()->saveEntity($queueItem);
         return;
     }
     $emailAddress = $target->get('emailAddress');
     if (!$emailAddress) {
         $queueItem->set('status', 'Failed');
         $this->getEntityManager()->saveEntity($queueItem);
         return false;
     }
     $emailAddressRecord = $this->getEntityManager()->getRepository('EmailAddress')->getByAddress($emailAddress);
     if ($emailAddressRecord) {
         if ($emailAddressRecord->get('invalid') || $emailAddressRecord->get('optOut')) {
             $queueItem->set('status', 'Failed');
             $this->getEntityManager()->saveEntity($queueItem);
             return false;
         }
     }
     $trackingUrlList = [];
     if ($campaign) {
         $trackingUrlList = $campaign->get('trackingUrls');
     }
     $email = $this->getPreparedEmail($queueItem, $massEmail, $emailTemplate, $target, $trackingUrlList);
     $params = array();
     if ($massEmail->get('fromName')) {
         $params['fromName'] = $massEmail->get('fromName');
     }
     if ($massEmail->get('replyToName')) {
         $params['replyToName'] = $massEmail->get('replyToName');
     }
     try {
         $attemptCount = $queueItem->get('attemptCount');
         $attemptCount++;
         $queueItem->set('attemptCount', $attemptCount);
         $message = new \Zend\Mail\Message();
         $header = new \Fox\Core\Mail\Mail\Header\XQueueItemId();
         $header->setId($queueItem->id);
         $message->getHeaders()->addHeader($header);
         $this->getMailSender()->useGlobal()->send($email, $params, $message, $attachmetList);
         $emailObject = $emailTemplate;
         if ($massEmail->get('storeSentEmails')) {
             $this->getEntityManager()->saveEntity($email);
             $emailObject = $email;
         }
         $queueItem->set('emailAddress', $target->get('emailAddress'));
         $queueItem->set('status', 'Sent');
         $queueItem->set('sentAt', date('Y-m-d H:i:s'));
         $this->getEntityManager()->saveEntity($queueItem);
         if ($campaign) {
             $this->getCampaignService()->logSent($campaign->id, $queueItem->id, $target, $emailObject, $target->get('emailAddress'));
         }
     } catch (\Exception $e) {
         if ($queueItem->get('attemptCount') >= self::MAX_ATTEMPT_COUNT) {
             $this->setQueueItemFailed($queueItem);
             $queueItem->set('status', 'Failed');
         }
         $this->getEntityManager()->saveEntity($queueItem);
         $GLOBALS['log']->error('MassEmail#sendQueueItem: [' . $e->getCode() . '] ' . $e->getMessage());
         return false;
     }
     return true;
 }
Beispiel #30
0
 protected function parseValue(Entity $entity, $field, $value, $params = array())
 {
     $decimalMark = '.';
     if (!empty($params['decimalMark'])) {
         $decimalMark = $params['decimalMark'];
     }
     $defaultCurrency = 'USD';
     if (!empty($params['defaultCurrency'])) {
         $defaultCurrency = $params['defaultCurrency'];
     }
     $dateFormat = 'Y-m-d';
     if (!empty($params['dateFormat'])) {
         if (!empty($this->dateFormatsMap[$params['dateFormat']])) {
             $dateFormat = $this->dateFormatsMap[$params['dateFormat']];
         }
     }
     $timeFormat = 'H:i';
     if (!empty($params['timeFormat'])) {
         if (!empty($this->timeFormatsMap[$params['timeFormat']])) {
             $timeFormat = $this->timeFormatsMap[$params['timeFormat']];
         }
     }
     $fieldDefs = $entity->getFields();
     if (!empty($fieldDefs[$field])) {
         $type = $fieldDefs[$field]['type'];
         switch ($type) {
             case Entity::DATE:
                 $dt = \DateTime::createFromFormat($dateFormat, $value);
                 if ($dt) {
                     return $dt->format('Y-m-d');
                 }
                 break;
             case Entity::DATETIME:
                 $dt = \DateTime::createFromFormat($dateFormat . ' ' . $timeFormat, $value);
                 if ($dt) {
                     return $dt->format('Y-m-d H:i');
                 }
                 break;
             case Entity::FLOAT:
                 $currencyField = $field . 'Currency';
                 if ($entity->hasField($currencyField)) {
                     if (!$entity->has($currencyField)) {
                         $entity->set($currencyField, $defaultCurrency);
                     }
                 }
                 $a = explode($decimalMark, $value);
                 $a[0] = preg_replace('/[^A-Za-z0-9\\-]/', '', $a[0]);
                 if (count($a) > 1) {
                     return $a[0] . '.' . $a[1];
                 } else {
                     return $a[0];
                 }
                 break;
         }
     }
     return $value;
 }