This commit is contained in:
Yuri Kuznetsov
2014-11-11 16:07:13 +02:00
parent e45b98d684
commit e87a69e6a3
28 changed files with 717 additions and 717 deletions
+8 -8
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Controllers;
@@ -27,33 +27,33 @@ use \Espo\Core\Exceptions\Error;
class Stream extends \Espo\Core\Controllers\Base
{
const MAX_SIZE_LIMIT = 400;
public static $defaultAction = 'list';
public function actionList($params, $data, $request)
{
$scope = $params['scope'];
$id = isset($params['id']) ? $params['id'] : null;
$offset = intval($request->get('offset'));
$maxSize = intval($request->get('maxSize'));
$after = $request->get('after');
$service = $this->getService('Stream');
if (empty($maxSize)) {
$maxSize = self::MAX_SIZE_LIMIT;
}
if (!empty($maxSize) && $maxSize > self::MAX_SIZE_LIMIT) {
throw new Forbidden();
}
}
$result = $service->find($scope, $id, array(
'offset' => $offset,
'maxSize' => $maxSize,
'after' => $after,
));
return array(
'total' => $result['total'],
'list' => $result['collection']->toArray()
+51 -51
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Core\Controllers;
@@ -30,27 +30,27 @@ use \Espo\Core\Utils\Util;
class Record extends Base
{
const MAX_SIZE_LIMIT = 200;
public static $defaultAction = 'list';
public static $defaultAction = 'list';
protected function getEntityManager()
{
return $this->getContainer()->get('entityManager');
}
protected function getRecordService($name = null)
{
if (empty($name)) {
$name = $this->name;
}
if ($this->getServiceFactory()->checkExists($name)) {
$service = $this->getServiceFactory()->create($name);
} else {
$service = $this->getServiceFactory()->create('Record');
$service->setEntityName($name);
}
}
return $service;
}
@@ -58,19 +58,19 @@ class Record extends Base
{
$id = $params['id'];
$entity = $this->getRecordService()->getEntity($id);
if (empty($entity)) {
throw new NotFound();
}
return $entity->toArray();
}
public function actionPatch($params, $data)
{
return $this->actionUpdate($params, $data);
}
public function actionCreate($params, $data)
{
if (!$this->getAcl()->check($this->name, 'edit')) {
@@ -78,7 +78,7 @@ class Record extends Base
}
$service = $this->getRecordService();
if ($entity = $service->createEntity($data)) {
return $entity->toArray();
}
@@ -91,9 +91,9 @@ class Record extends Base
if (!$this->getAcl()->check($this->name, 'edit')) {
throw new Forbidden();
}
$id = $params['id'];
$id = $params['id'];
if ($entity = $this->getRecordService()->updateEntity($id, $data)) {
return $entity->toArray();
}
@@ -113,7 +113,7 @@ class Record extends Base
$asc = $request->get('asc') === 'true';
$sortBy = $request->get('sortBy');
$q = $request->get('q');
if (empty($maxSize)) {
$maxSize = self::MAX_SIZE_LIMIT;
}
@@ -129,17 +129,17 @@ class Record extends Base
'sortBy' => $sortBy,
'q' => $q,
));
return array(
'total' => $result['total'],
'list' => $result['collection']->toArray()
);
}
public function actionListLinked($params, $data, $request)
{
$id = $params['id'];
$link = $params['link'];
$link = $params['link'];
$where = $request->get('where');
$offset = $request->get('offset');
@@ -147,13 +147,13 @@ class Record extends Base
$asc = $request->get('asc') === 'true';
$sortBy = $request->get('sortBy');
$q = $request->get('q');
if (empty($maxSize)) {
$maxSize = self::MAX_SIZE_LIMIT;
}
if (!empty($maxSize) && $maxSize > self::MAX_SIZE_LIMIT) {
throw new Forbidden();
}
}
$result = $this->getRecordService()->findLinkedEntities($id, $link, array(
'where' => $where,
@@ -163,8 +163,8 @@ class Record extends Base
'sortBy' => $sortBy,
'q' => $q,
));
return array(
'total' => $result['total'],
'list' => $result['collection']->toArray()
@@ -180,30 +180,30 @@ class Record extends Base
}
throw new Error();
}
public function actionExport($params, $data, $request)
{
{
if ($this->getConfig()->get('disableExport') && !$this->getUser()->isAdmin()) {
throw new Forbidden();
}
if (!$this->getAcl()->check($this->name, 'read')) {
throw new Forbidden();
}
}
$ids = $request->get('ids');
$where = $request->get('where');
return array(
'id' => $this->getRecordService()->export($ids, $where)
);
);
}
public function actionMassUpdate($params, $data, $request)
{
if (!$this->getAcl()->check($this->name, 'edit')) {
throw new Forbidden();
}
}
$ids = $data['ids'];
$where = $data['where'];
@@ -232,17 +232,17 @@ class Record extends Base
{
$id = $params['id'];
$link = $params['link'];
$foreignIds = array();
$foreignIds = array();
if (isset($data['id'])) {
$foreignIds[] = $data['id'];
}
}
if (isset($data['ids']) && is_array($data['ids'])) {
foreach ($data['ids'] as $foreignId) {
$foreignIds[] = $foreignId;
}
}
}
$result = false;
foreach ($foreignIds as $foreignId) {
if ($this->getRecordService()->linkEntity($id, $link, $foreignId)) {
@@ -251,26 +251,26 @@ class Record extends Base
}
if ($result) {
return true;
}
throw new Error();
}
throw new Error();
}
public function actionRemoveLink($params, $data)
{
$id = $params['id'];
$link = $params['link'];
$foreignIds = array();
$foreignIds = array();
if (isset($data['id'])) {
$foreignIds[] = $data['id'];
}
}
if (isset($data['ids']) && is_array($data['ids'])) {
foreach ($data['ids'] as $foreignId) {
$foreignIds[] = $foreignId;
}
}
$result = false;
foreach ($foreignIds as $foreignId) {
if ($this->getRecordService()->unlinkEntity($id, $link, $foreignId)) {
@@ -279,27 +279,27 @@ class Record extends Base
}
if ($result) {
return true;
}
throw new Error();
}
throw new Error();
}
public function actionFollow($params)
{
if (!$this->getAcl()->check($this->name, 'read')) {
throw new Forbidden();
}
$id = $params['id'];
return $this->getRecordService()->follow($id);
return $this->getRecordService()->follow($id);
}
public function actionUnfollow($params)
{
if (!$this->getAcl()->check($this->name, 'read')) {
throw new Forbidden();
}
$id = $params['id'];
return $this->getRecordService()->unfollow($id);
return $this->getRecordService()->unfollow($id);
}
}
+1 -1
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Core\ORM\DB;
+19 -19
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Core\ORM;
@@ -27,59 +27,59 @@ use \Espo\Core\Utils\Util;
class EntityManager extends \Espo\ORM\EntityManager
{
protected $espoMetadata;
private $hookManager;
protected $user;
protected $container;
private $repositoryClassNameHash = array();
private $entityClassNameHash = array();
public function setContainer(\Espo\Core\Container $container)
{
$this->container = $container;
$this->container = $container;
}
public function getContainer()
{
return $this->container;
return $this->container;
}
public function setUser($user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
public function getEspoMetadata()
{
return $this->espoMetadata;
}
}
public function setEspoMetadata($espoMetadata)
{
$this->espoMetadata = $espoMetadata;
}
public function setHookManager(\Espo\Core\HookManager $hookManager)
{
$this->hookManager = $hookManager;
}
public function getHookManager()
{
return $this->hookManager;
}
public function normalizeRepositoryName($name)
{
{
if (empty($this->repositoryClassNameHash[$name])) {
$className = '\\Espo\\Custom\\Repositories\\' . Util::normilizeClassName($name);
if (!class_exists($className)) {
@@ -89,9 +89,9 @@ class EntityManager extends \Espo\ORM\EntityManager
}
return $this->repositoryClassNameHash[$name];
}
public function normalizeEntityName($name)
{
{
if (empty($this->entityClassNameHash[$name])) {
$className = '\\Espo\\Custom\\Entities\\' . Util::normilizeClassName($name);
if (!class_exists($className)) {
+25 -25
View File
@@ -66,26 +66,26 @@ class RDB extends \Espo\ORM\Repositories\RDB implements Injectable
$this->handlePhoneNumberParams($params);
$this->handleCurrencyParams($params);
}
protected function handleCurrencyParams(&$params)
{
$entityName = $this->entityName;
$metadata = $this->getMetadata();
if (!$metadata) {
return;
}
$defs = $metadata->get('entityDefs.' . $entityName);
foreach ($defs['fields'] as $field => $d) {
if (isset($d['type']) && $d['type'] == 'currency') {
if (empty($params['customJoin'])) {
$params['customJoin'] = '';
$params['customJoin'] = '';
}
$alias = Util::toUnderScore($field) . "_currency_alias";
$params['customJoin'] .= "
$params['customJoin'] .= "
LEFT JOIN currency AS `{$alias}` ON {$alias}.id = ".Util::toUnderScore($entityName).".".Util::toUnderScore($field)."_currency
";
}
@@ -114,10 +114,10 @@ class RDB extends \Espo\ORM\Repositories\RDB implements Injectable
);
}
}
protected function handlePhoneNumberParams(&$params)
{
$entityName = $this->entityName;
$entityName = $this->entityName;
$defs = $this->getEntityManager()->getMetadata()->get($entityName);
if (!empty($defs['relations']) && array_key_exists('phoneNumbers', $defs['relations'])) {
@@ -198,7 +198,7 @@ class RDB extends \Espo\ORM\Repositories\RDB implements Injectable
if ($entity->has('modifiedAt')) {
$restoreData['modifiedAt'] = $entity->get('modifiedAt');
}
$entity->clear('modifiedById');
$entity->clear('modifiedById');
} else {
if ($entity->hasField('modifiedAt')) {
$entity->set('modifiedAt', $nowString);
@@ -228,15 +228,15 @@ class RDB extends \Espo\ORM\Repositories\RDB implements Injectable
}
protected function handleEmailAddressSave(Entity $entity)
{
if ($entity->hasRelation('emailAddresses') && $entity->hasField('emailAddress')) {
{
if ($entity->hasRelation('emailAddresses') && $entity->hasField('emailAddress')) {
$emailAddressRepository = $this->getEntityManager()->getRepository('EmailAddress')->storeEntityEmailAddress($entity);
}
}
protected function handlePhoneNumberSave(Entity $entity)
{
if ($entity->hasRelation('phoneNumbers') && $entity->hasField('phoneNumber')) {
{
if ($entity->hasRelation('phoneNumbers') && $entity->hasField('phoneNumber')) {
$emailAddressRepository = $this->getEntityManager()->getRepository('PhoneNumber')->storeEntityPhoneNumber($entity);
}
}
@@ -254,32 +254,32 @@ class RDB extends \Espo\ORM\Repositories\RDB implements Injectable
$existingIds = array();
$toUpdateIds = array();
$existingColumnsData = new \stdClass();
$defs = array();
$columns = $this->getMetadata()->get("entityDefs." . $entity->getEntityName() . ".fields.{$name}.columns");
if (!empty($columns)) {
if (!empty($columns)) {
$columnData = $entity->get($name . 'Columns');
$defs['additionalColumns'] = $columns;
}
}
foreach ($entity->get($name, $defs) as $foreignEntity) {
$existingIds[] = $foreignEntity->id;
if (!empty($columns)) {
if (!empty($columns)) {
$data = new \stdClass();
foreach ($columns as $columnName => $columnField) {
$foreignId = $foreignEntity->id;
$data->$columnName = $foreignEntity->get($columnField);
}
}
$existingColumnsData->$foreignId = $data;
}
}
}
foreach ($existingIds as $id) {
if (!in_array($id, $specifiedIds)) {
$toRemoveIds[] = $id;
} else {
if (!empty($columns)) {
if (!empty($columns)) {
foreach ($columns as $columnName => $columnField) {
if ($columnData->$id->$columnName != $existingColumnsData->$id->$columnName) {
$toUpdateIds[] = $id;
@@ -291,7 +291,7 @@ class RDB extends \Espo\ORM\Repositories\RDB implements Injectable
foreach ($specifiedIds as $id) {
if (!in_array($id, $existingIds)) {
$data = null;
if (!empty($columns)) {
if (!empty($columns)) {
$data = $columnData->$id;
}
$this->relate($entity, $name, $id, $data);
@@ -300,7 +300,7 @@ class RDB extends \Espo\ORM\Repositories\RDB implements Injectable
foreach ($toRemoveIds as $id) {
$this->unrelate($entity, $name, $id);
}
if (!empty($columns)) {
if (!empty($columns)) {
foreach ($toUpdateIds as $id) {
$data = $columnData->$id;
$this->updateRelation($entity, $name, $id, $data);
+7 -7
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Core\ORM;
@@ -27,22 +27,22 @@ use \Espo\Core\Interfaces\Injectable;
abstract class Repository extends \Espo\ORM\Repository implements Injectable
{
protected $dependencies = array();
protected $injections = array();
public function inject($name, $object)
{
$this->injections[$name] = $object;
}
}
protected function getInjection($name)
{
return $this->injections[$name];
}
public function getDependencyList()
{
return $this->dependencies;
}
}
}
@@ -18,18 +18,18 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Core\ORM;
class RepositoryFactory extends \Espo\ORM\RepositoryFactory
{
{
protected $defaultRepositoryClassName = '\\Espo\\Core\\ORM\\Repositories\\RDB';
public function create($name)
{
$repository = parent::create($name);
$dependencies = $repository->getDependencyList();
foreach ($dependencies as $name) {
$repository->inject($name, $this->entityManager->getContainer()->get($name));
@@ -174,7 +174,7 @@ class Base
if (empty($result['whereClause'])) {
$result['whereClause'] = array();
}
$fieldDefs = $this->entityManager->getEntity($this->entityName)->getFields();
$value = $params['q'];
@@ -332,8 +332,8 @@ class Base
break;
case 'currentQuarter':
$dt = new \DateTime();
$quarter = ceil($dt->format('m') / 3);
$dt->modify('first day of January this year');
$quarter = ceil($dt->format('m') / 3);
$dt->modify('first day of January this year');
$part['AND'] = array(
$item['field'] . '>=' => $dt->add(new \DateInterval('P'.(($quarter - 1) * 3).'M'))->format('Y-m-d'),
$item['field'] . '<' => $dt->add(new \DateInterval('P3M'))->format('Y-m-d'),
@@ -341,13 +341,13 @@ class Base
break;
case 'lastQuarter':
$dt = new \DateTime();
$quarter = ceil($dt->format('m') / 3);
$dt->modify('first day of January this year');
$quarter = ceil($dt->format('m') / 3);
$dt->modify('first day of January this year');
$quarter--;
if ($quarter == 0) {
$quarter = 4;
$dt->sub('P1Y');
}
}
$part['AND'] = array(
$item['field'] . '>=' => $dt->add(new \DateInterval('P'.(($quarter - 1) * 3).'M'))->format('Y-m-d'),
$item['field'] . '<' => $dt->add(new \DateInterval('P3M'))->format('Y-m-d'),
+10 -10
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Core\Services;
@@ -31,38 +31,38 @@ abstract class Base implements Injectable
'entityManager',
'user',
);
protected $injections = array();
public function inject($name, $object)
{
$this->injections[$name] = $object;
}
public function __construct()
{
$this->init();
}
protected function init()
{
{
}
protected function getInjection($name)
{
return $this->injections[$name];
}
public function getDependencyList()
{
return $this->dependencies;
}
protected function getEntityManager()
{
return $this->getInjection('entityManager');
}
protected function getConfig()
{
return $this->getInjection('config');
+17 -17
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\ORM\DB;
@@ -35,7 +35,7 @@ interface IMapper
* @return IEntity $entity
*/
function selectById(IEntity $entity, $id);
/**
* Selects list of beans according to given parameters.
*
@@ -56,7 +56,7 @@ interface IMapper
* @return mixed Result of the aggregation
*/
function aggregate(IEntity $entity, $params, $aggregation, $aggregationBy, $deleted);
/**
* Returns count of records according to given parameters.
*
@@ -65,7 +65,7 @@ interface IMapper
* @return int Count of record
*/
function count(IEntity $entity, $params);
/**
* Returns max value of the field in the select according to given parameters.
*
@@ -76,7 +76,7 @@ interface IMapper
* @return mixed Max value
*/
function max(IEntity $entity, $params, $field, $deleted);
/**
* Returns min value of the field in the select according to given parameters.
*
@@ -87,7 +87,7 @@ interface IMapper
* @return mixed Min value
*/
function min(IEntity $entity, $params, $field, $deleted);
/**
* Returns sum value of the field in the select according to given parameters.
*
@@ -98,7 +98,7 @@ interface IMapper
* @return mixed Sum value
*/
function sum(IEntity $entity, $params);
/**
* Selects related bean or list of beans.
*
@@ -109,7 +109,7 @@ interface IMapper
* @return array List of beans or total count if $totalCount was passed as true
*/
function selectRelated(IEntity $entity, $relName, $params, $totalCount);
/**
* Returns count of related records according to given parameters.
*
@@ -119,7 +119,7 @@ interface IMapper
* @return int Count of records
*/
function countRelated(IEntity $entity, $relName, $params);
/**
* Links the bean with another one.
*
@@ -128,8 +128,8 @@ interface IMapper
* @param string $id Id of the foreign record.
* @return bool True if success
*/
function addRelation(IEntity $entity, $relName, $id);
function addRelation(IEntity $entity, $relName, $id);
/**
* Removes relation of bean with certain record.
*
@@ -139,7 +139,7 @@ interface IMapper
* @return bool True if success
*/
function removeRelation(IEntity $entity, $relName, $id);
/**
* Removes all relations of bean of specified relation name.
*
@@ -148,7 +148,7 @@ interface IMapper
* @return bool True if success
*/
function removeAllRelations(IEntity $entity, $relName);
/**
* Insert the bean into db.
*
@@ -156,7 +156,7 @@ interface IMapper
* @return bool True if success
*/
function insert(IEntity $entity);
/**
* Updates the bean in db.
*
@@ -164,8 +164,8 @@ interface IMapper
* @return bool True if success
*/
function update(IEntity $entity);
/**
* Deletes the bean.
* (Marks as deleted)
@@ -174,7 +174,7 @@ interface IMapper
* @return bool True if success
*/
function delete(IEntity $entity);
/**
* Sets class name of a model collection that will be returned by operations such as select.
*
+19 -19
View File
@@ -37,7 +37,7 @@ abstract class Mapper implements IMapper
public $pdo;
protected $entityFactroy;
protected $query;
protected $fieldsMapCache = array();
@@ -148,7 +148,7 @@ abstract class Mapper implements IMapper
if (empty($aggregation) || !isset($entity->fields[$aggregationBy])) {
return false;
}
$params['aggregation'] = $aggregation;
$params['aggregationBy'] = $aggregationBy;
@@ -178,13 +178,13 @@ abstract class Mapper implements IMapper
if (!$relEntity) {
return null;
}
if ($totalCount) {
$params['aggregation'] = 'COUNT';
$params['aggregationBy'] = 'id';
}
if (empty($params['whereClause'])) {
$params['whereClause'] = array();
}
@@ -198,13 +198,13 @@ abstract class Mapper implements IMapper
switch ($relType) {
case IEntity::BELONGS_TO:
case IEntity::BELONGS_TO:
$params['whereClause'][$foreignKey] = $entity->get($key);
$params['offset'] = 0;
$params['limit'] = 1;
$params['limit'] = 1;
$sql = $this->query->createSelectQuery($relEntity->getEntityName(), $params);
$ps = $this->pdo->query($sql);
if ($ps) {
@@ -221,7 +221,7 @@ abstract class Mapper implements IMapper
case IEntity::HAS_MANY:
case IEntity::HAS_CHILDREN:
$params['whereClause'][$foreignKey] = $entity->get($key);
if ($relType == IEntity::HAS_CHILDREN) {
@@ -259,23 +259,23 @@ abstract class Mapper implements IMapper
$additionalColumnsConditions = $params['additionalColumnsConditions'];
}
$MMJoinPart = $this->getMMJoin($entity, $relationName, $keySet, $additionalColumnsConditions);
$MMJoinPart = $this->getMMJoin($entity, $relationName, $keySet, $additionalColumnsConditions);
if (empty($params['customJoin'])) {
$params['customJoin'] = '';
} else {
$params['customJoin'] .= ' ';
}
$params['customJoin'] .= $MMJoinPart;
$params['relationName'] = $relOpt['relationName'];
// TODO total
$sql = $this->query->createSelectQuery($relEntity->getEntityName(), $params);
$dataArr = array();
@@ -659,12 +659,12 @@ abstract class Mapper implements IMapper
if ($type == IEntity::FOREIGN) {
continue;
}
}
if ($entity->getFetched($field) === $value && $type != IEntity::JSON_ARRAY && $type != IEntity::JSON_OBJECT) {
continue;
}
$value = $this->prepareValueForInsert($type, $value);
$setArr[] = "`" . $this->toDb($field) . "` = " . $this->quote($value);
@@ -684,7 +684,7 @@ abstract class Mapper implements IMapper
return false;
}
protected function prepareValueForInsert($type, $value) {
if ($type == IEntity::JSON_ARRAY && is_array($value)) {
$value = json_encode($value);
+37 -37
View File
@@ -18,27 +18,27 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\ORM;
class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \SeekableIterator
{
private $entityFactory = null;
private $entityFactory = null;
private $entityName;
private $position = 0;
protected $container = array();
public function __construct($data = array(), $entityName, EntityFactory $entityFactory = null)
{
$this->container = $data;
$this->container = $data;
$this->entityName = $entityName;
$this->entityFactory = $entityFactory;
}
public function rewind()
{
$this->position = 0;
@@ -47,17 +47,17 @@ class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \Seekable
$this->position ++;
}
}
public function current()
{
{
return $this->getEntityByOffset($this->position);
}
public function key()
{
{
return $this->position;
}
public function next()
{
do {
@@ -68,17 +68,17 @@ class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \Seekable
}
} while ($next);
}
public function valid()
{
{
return isset($this->container[$this->position]);
}
public function offsetExists($offset)
{
return isset($this->container[$offset]);
}
public function offsetGet($offset)
{
if (!isset($this->container[$offset])) {
@@ -86,13 +86,13 @@ class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \Seekable
}
return $this->getEntityByOffset($offset);
}
public function offsetSet($offset, $value)
{
if (!($value instanceof Entity)) {
throw new \InvalidArgumentException('Only Entity is allowed to be added to EntityCollection.');
}
if (is_null($offset)) {
$this->container[] = $value;
} else {
@@ -101,7 +101,7 @@ class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \Seekable
}
public function offsetUnset($offset)
{
{
unset($this->container[$offset]);
}
@@ -109,41 +109,41 @@ class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \Seekable
{
return count($this->container);
}
public function seek($offset)
{
$this->position = $offset;
if (!$this->valid()) {
throw new \OutOfBoundsException("Invalid seek offset ($offset).");
}
}
}
public function append(Entity $entity)
{
$this->container[] = $entity;
}
private function getEntityByOffset($offset)
{
$value = $this->container[$offset];
if ($value instanceof Entity) {
return $value;
} else if (is_array($value)) {
$this->container[$offset] = $this->buildEntityFromArray($value);
} else if (is_array($value)) {
$this->container[$offset] = $this->buildEntityFromArray($value);
} else {
return null;
}
return $this->container[$offset];
}
protected function buildEntityFromArray(array $dataArray)
{
$entity = $this->entityFactory->create($this->entityName);
if ($entity) {
$entity->set($dataArray);
$entity->setAsFetched();
$entity->setAsFetched();
return $entity;
}
}
@@ -151,25 +151,25 @@ class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \Seekable
public function getEntityName()
{
return $this->entityName;
}
}
public function getInnerContainer()
{
return $this->container;
}
public function merge(EntityCollection $collection)
{
$newData = $this->container;
$newData = $this->container;
$incomingData = $collection->getInnerContainer();
foreach ($incomingData as $v) {
if (!$this->contains($v)) {
$this->container[] = $v;
}
}
}
public function contains($value)
{
if ($this->indexOf($value) !== false) {
@@ -177,12 +177,12 @@ class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \Seekable
}
return false;
}
public function indexOf($value)
{
$index = 0;
if (is_array($value)) {
foreach ($this->container as $v) {
foreach ($this->container as $v) {
if (is_array($v)) {
if ($value['id'] == $v['id']) {
return $index;
@@ -194,7 +194,7 @@ class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \Seekable
}
$index ++;
}
} else if ($value instanceof Entity) {
} else if ($value instanceof Entity) {
foreach ($this->container as $v) {
if (is_array($v)) {
if ($value->id == $v['id']) {
@@ -210,7 +210,7 @@ class EntityCollection implements \Iterator, \Countable, \ArrayAccess, \Seekable
}
return false;
}
public function toArray()
{
$arr = array();
+6 -6
View File
@@ -18,16 +18,16 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\ORM;
class EntityFactory
{
{
protected $metadata;
protected $entityManager;
public function __construct(EntityManager $entityManager, Metadata $metadata)
{
$this->entityManager = $entityManager;
@@ -35,12 +35,12 @@ class EntityFactory
}
public function create($name)
{
$className = $this->entityManager->normalizeEntityName($name);
$className = $this->entityManager->normalizeEntityName($name);
$defs = $this->metadata->get($name);
if (!class_exists($className)) {
return null;
}
$entity = new $className($defs, $this->entityManager);
$entity = new $className($defs, $this->entityManager);
return $entity;
}
+3 -3
View File
@@ -38,7 +38,7 @@ class EntityManager
protected $repositoryHash = array();
protected $params = array();
protected $query;
public function __construct($params)
@@ -65,7 +65,7 @@ class EntityManager
$this->init();
}
public function getQuery()
{
if (empty($this->query)) {
@@ -78,7 +78,7 @@ class EntityManager
{
if (empty($this->mappers[$className])) {
// TODO use factory
$this->mappers[$className] = new $className($this->getPDO(), $this->entityFactory, $this->getQuery());
}
return $this->mappers[$className];
+9 -9
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\ORM;
@@ -40,46 +40,46 @@ interface IEntity
const DATETIME = 'datetime';
const JSON_ARRAY = 'jsonArray';
const JSON_OBJECT = 'jsonObject';
const MANY_MANY = 'manyMany';
const HAS_MANY = 'hasMany';
const BELONGS_TO = 'belongsTo';
const HAS_ONE = 'hasOne';
const BELONGS_TO_PARENT = 'belongsToParent';
const HAS_CHILDREN = 'hasChildren';
/**
* Push values from the array.
* E.g. insert values into the bean from a request data.
* @param array $arr Array of field - value pairs
*/
function populateFromArray(array $arr);
/**
* Resets all fields in the current model.
*/
function reset();
/**
* Set field.
*/
function set($name, $value);
/**
* Get field.
*/
function get($name);
/**
* Check field is set.
*/
function has($name);
/**
* Clear field.
*/
function clear($name);
}
+3 -3
View File
@@ -18,19 +18,19 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\ORM;
class Metadata
{
protected $data = array();
public function setData($data)
{
$this->data = $data;
}
public function get($entityName)
{
return $this->data[$entityName];
+25 -25
View File
@@ -18,69 +18,69 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\ORM;
abstract class Repository
{
{
/**
* @var EntityFactory EntityFactory object.
*/
protected $entityFactory;
/**
* @var EntityManager EntityManager object.
*/
protected $entityManager;
/**
* @var iModel Seed entity.
*/
*/
protected $seed;
/**
* @var string Class Name of aggregate root.
*/
*/
protected $entityClassName;
/**
* @var string Model Name of aggregate root.
*/
*/
protected $entityName;
public function __construct($entityName, EntityManager $entityManager, EntityFactory $entityFactory)
{
$this->entityName = $entityName;
$this->entityFactory = $entityFactory;
$this->seed = $this->entityFactory->create($entityName);
$this->entityName = $entityName;
$this->entityFactory = $entityFactory;
$this->seed = $this->entityFactory->create($entityName);
$this->entityClassName = get_class($this->seed);
$this->entityManager = $entityManager;
$this->entityManager = $entityManager;
}
protected function getEntityFactory()
{
return $this->entityFactory;
}
protected function getEntityManager()
{
return $this->entityManager;
}
abstract public function get($id = null);
abstract public function save(Entity $entity);
abstract public function get($id = null);
abstract public function save(Entity $entity);
abstract public function remove(Entity $entity);
abstract public function find(array $params);
abstract public function findOne(array $params);
abstract public function findOne(array $params);
abstract public function getAll();
abstract public function count(array $params);
}
+10 -10
View File
@@ -18,41 +18,41 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\ORM;
class RepositoryFactory
{
protected $entityFactroy;
protected $entityManager;
protected $defaultRepositoryClassName = '\\Espo\\ORM\\Repository';
protected $defaultRepositoryClassName = '\\Espo\\ORM\\Repository';
public function __construct(EntityManager $entityManager, EntityFactory $entityFactroy)
{
$this->entityManager = $entityManager;
$this->entityFactroy = $entityFactroy;
}
public function create($name)
{
$className = $this->entityManager->normalizeRepositoryName($name);
if (!class_exists($className)) {
$className = $this->defaultRepositoryClassName;
}
$repository = new $className($name, $this->entityManager, $this->entityFactroy);
$repository = new $className($name, $this->entityManager, $this->entityFactroy);
return $repository;
}
protected function normalizeName($name)
{
return $name;
}
public function setDefaultRepositoryClassName($defaultRepositoryClassName)
{
$this->defaultRepositoryClassName = $defaultRepositoryClassName;
+8 -8
View File
@@ -18,25 +18,25 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Services;
class Attachment extends Record
{
protected $notFilteringFields = array('contents');
protected $notFilteringFields = array('contents');
public function createEntity($data)
{
{
if (!empty($data['file'])) {
list($prefix, $contents) = explode(',', $data['file']);
list($prefix, $contents) = explode(',', $data['file']);
$contents = base64_decode($contents);
$data['contents'] = $contents;
}
$entity = parent::createEntity($data);
return $entity;
}
}
+2 -2
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Services;
@@ -27,7 +27,7 @@ use \Espo\Core\Exceptions\Error;
use \Espo\Core\Exceptions\NotFound;
class AuthToken extends Record
{
{
protected $internalFields = array('hash', 'token');
}
+17 -17
View File
@@ -31,24 +31,24 @@ class EmailAddress extends Record
private function findInAddressBookByEntityType($where, $limit, $entityType, &$result)
{
$service = $this->getServiceFactory()->create($entityType);
$r = $service->findEntities(array(
'where' => $where,
'maxSize' => $limit,
'sortBy' => 'name'
));
));
foreach ($r['collection'] as $entity) {
$entity->loadLinkMultipleField('emailAddress');
$emailAddress = $entity->get('emailAddress');
$result[] = array(
'emailAddress' => $emailAddress,
'name' => $entity->get('name'),
'entityType' => $entityType
);
$c = $service->getEntity($entity->id);
$emailAddressData = $c->get('emailAddressData');
@@ -63,14 +63,14 @@ class EmailAddress extends Record
break;
}
}
}
}
}
public function searchInAddressBook($query, $limit)
{
$result = array();
$result = array();
$where = array(
array(
'type' => 'or',
@@ -93,13 +93,13 @@ class EmailAddress extends Record
'value' => null
)
);
$this->findInAddressBookByEntityType($where, $limit, 'Contact', $result);
$this->findInAddressBookByEntityType($where, $limit, 'Lead', $result);
$this->findInAddressBookByEntityType($where, $limit, 'User', $result);
$this->findInAddressBookByEntityType($where, $limit, 'User', $result);
$final = array();
foreach ($result as $r) {
foreach ($final as $f) {
if ($f['emailAddress'] == $r['emailAddress'] && $f['name'] == $r['name']) {
@@ -108,9 +108,9 @@ class EmailAddress extends Record
}
$final[] = $r;
}
return $final;
}
}
+30 -30
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Services;
@@ -28,90 +28,90 @@ use \Espo\Core\Exceptions\NotFound;
use Espo\ORM\Entity;
class EmailNotification extends \Espo\Core\Services\Base
{
{
protected function init()
{
$this->dependencies[] = 'metadata';
$this->dependencies[] = 'mailSender';
$this->dependencies[] = 'language';
}
protected function getMailSender()
{
return $this->getInjection('mailSender');
}
}
protected function getMetadata()
{
return $this->getInjection('metadata');
}
protected function getLanguage()
{
return $this->getInjection('language');
}
protected function replaceMessageVariables($text, $entity, $user, $assignerUser)
{
{
$recordUrl = $this->getConfig()->get('siteUrl') . '#' . $entity->getEntityName() . '/view/' . $entity->id;
$text = str_replace('{userName}', $user->get('name'), $text);
$text = str_replace('{assignerUserName}', $assignerUser->get('name'), $text);
$text = str_replace('{recordUrl}', $recordUrl, $text);
$text = str_replace('{recordUrl}', $recordUrl, $text);
$text = str_replace('{entityType}', $this->getLanguage()->translate($entity->getEntityName(), 'scopeNames'), $text);
$fields = $entity->getFields();
foreach ($fields as $field => $d) {
$text = str_replace('{Entity.' . $field . '}', $entity->get($field), $text);
$text = str_replace('{Entity.' . $field . '}', $entity->get($field), $text);
}
return $text;
}
public function notifyAboutAssignmentJob($data)
{
$userId = $data['userId'];
$assignerUserId = $data['assignerUserId'];
$entityId = $data['entityId'];
$entityType = $data['entityType'];
$entityType = $data['entityType'];
$user = $this->getEntityManager()->getEntity('User', $userId);
$prefs = $this->getEntityManager()->getEntity('Preferences', $userId);
if (!$prefs) {
return true;
}
if (!$prefs->get('receiveAssignmentEmailNotifications')) {
return true;
}
$assignerUser = $this->getEntityManager()->getEntity('User', $assignerUserId);
$entity = $this->getEntityManager()->getEntity($entityType, $entityId);
}
$assignerUser = $this->getEntityManager()->getEntity('User', $assignerUserId);
$entity = $this->getEntityManager()->getEntity($entityType, $entityId);
if ($user && $entity && $assignerUser && $entity->get('assignedUserId') == $userId) {
$emailAddress = $user->get('emailAddress');
if (!empty($emailAddress)) {
$email = $this->getEntityManager()->getEntity('Email');
$email = $this->getEntityManager()->getEntity('Email');
$subject = $this->getLanguage()->translate('assignmentEmailNotificationSubject', 'messages', $entity->getEntityName());
$body = $this->getLanguage()->translate('assignmentEmailNotificationBody', 'messages', $entity->getEntityName());
$subject = $this->replaceMessageVariables($subject, $entity, $user, $assignerUser);
$body = $this->replaceMessageVariables($body, $entity, $user, $assignerUser);
$email->set(array(
'subject' => $subject,
'body' => $body,
'isHtml' => false,
'to' => $emailAddress
));
$this->getMailSender()->send($email);
}
}
return true;
}
}
+13 -13
View File
@@ -29,29 +29,29 @@ use \Espo\Core\Exceptions\Forbidden;
use \Espo\Core\Exceptions\NotFound;
class ExternalAccount extends Record
{
{
protected function getClient($integration, $id)
{
{
$integrationEntity = $this->getEntityManager()->getEntity('Integration', $integration);
if (!$integrationEntity) {
throw new NotFound();
}
$d = $integrationEntity->toArray();
if (!$integrationEntity->get('enabled')) {
throw new Error("{$integration} is disabled.");
}
$factory = new \Espo\Core\ExternalAccount\ClientManager($this->getEntityManager(), $this->getMetadata(), $this->getConfig());
$factory = new \Espo\Core\ExternalAccount\ClientManager($this->getEntityManager(), $this->getMetadata(), $this->getConfig());
return $factory->create($integration, $id);
}
public function getExternalAccountEntity($integration, $userId)
{
return $this->getEntityManager()->getEntity('ExternalAccount', $integration . '__' . $userId);
}
public function ping($integration, $userId)
{
$entity = $this->getExternalAccountEntity($integration, $userId);
@@ -62,7 +62,7 @@ class ExternalAccount extends Record
}
} catch (\Exception $e) {}
}
public function authorizationCode($integration, $userId, $code)
{
$entity = $this->getExternalAccountEntity($integration, $userId);
@@ -71,14 +71,14 @@ class ExternalAccount extends Record
}
$entity->set('enabled', true);
$this->getEntityManager()->saveEntity($entity);
$client = $this->getClient($integration, $userId);
if ($client instanceof \Espo\Core\ExternalAccount\Clients\OAuth2Abstract) {
if ($client instanceof \Espo\Core\ExternalAccount\Clients\OAuth2Abstract) {
$result = $client->getAccessTokenFromAuthorizationCode($code);
if (!empty($result) && !empty($result['accessToken'])) {
if (!empty($result) && !empty($result['accessToken'])) {
$entity->clear('accessToken');
$entity->clear('refreshToken');
$entity->clear('tokenType');
$entity->clear('tokenType');
foreach ($result as $name => $value) {
$entity->set($name, $value);
}
+15 -15
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Services;
@@ -28,7 +28,7 @@ use \Espo\Core\Exceptions\NotFound;
use Espo\ORM\Entity;
class GlobalSearch extends \Espo\Core\Services\Base
{
{
protected $dependencies = array(
'entityManager',
'user',
@@ -37,7 +37,7 @@ class GlobalSearch extends \Espo\Core\Services\Base
'selectManagerFactory',
'config',
);
protected function getSelectManagerFactory()
{
return $this->injections['selectManagerFactory'];
@@ -47,33 +47,33 @@ class GlobalSearch extends \Espo\Core\Services\Base
{
return $this->injections['entityManager'];
}
protected function getAcl()
{
return $this->injections['acl'];
}
protected function getMetadata()
{
return $this->injections['metadata'];
}
}
public function find($query, $offset, $maxSize)
{
$entityNameList = $this->getConfig()->get('globalSearchEntityList');
$entityTypeCount = count($entityNameList);
$list = array();
$count = 0;
$total = 0;
foreach ($entityNameList as $entityName) {
foreach ($entityNameList as $entityName) {
if (!$this->getAcl()->check($entityName, 'read')) {
continue;
}
$selectManager = $this->getSelectManagerFactory()->create($entityName);
$selectManager = $this->getSelectManagerFactory()->create($entityName);
$searchParams = array(
'whereClause' => array(
'OR' => array(
@@ -86,7 +86,7 @@ class GlobalSearch extends \Espo\Core\Services\Base
'order' => 'DESC',
);
$selectParams = array_merge_recursive($searchParams, $selectManager->getAclParams());
$collection = $this->getEntityManager()->getRepository($entityName)->find($selectParams);
$count += count($collection);
$total += $this->getEntityManager()->getRepository($entityName)->count($selectParams);
@@ -96,7 +96,7 @@ class GlobalSearch extends \Espo\Core\Services\Base
$list[] = $data;
}
}
return array(
'total' => $total,
'list' => $list,
+83 -83
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Services;
@@ -29,7 +29,7 @@ use \Espo\Core\Exceptions\Error;
use Espo\ORM\Entity;
class Import extends \Espo\Core\Services\Base
{
{
protected $dependencies = array(
'entityManager',
'user',
@@ -40,7 +40,7 @@ class Import extends \Espo\Core\Services\Base
'serviceFactory',
'fileManager',
);
protected $dateFormatsMap = array(
'YYYY-MM-DD' => 'Y-m-d',
'DD-MM-YYYY' => 'd-m-Y',
@@ -49,43 +49,43 @@ class Import extends \Espo\Core\Services\Base
'DD/MM/YYYY' => 'd/m/Y',
'DD.MM.YYYY' => 'd.m.Y',
'MM.DD.YYYY' => 'm.d.Y',
'YYYY.MM.DD' => 'Y.m.d',
'YYYY.MM.DD' => 'Y.m.d',
);
protected $timeFormatsMap = array(
'HH:mm' => 'H:i',
'hh:mm a' => 'h:i a',
'hh:mma' => 'h:ia',
'hh:mm A' => 'h:iA',
'hh:mmA' => 'h:iA',
'hh:mmA' => 'h:iA',
);
protected function getSelectManagerFactory()
{
return $this->injections['selectManagerFactory'];
}
protected function getFileManager()
{
return $this->injections['fileManager'];
}
protected function getAcl()
{
return $this->injections['acl'];
}
protected function getMetadata()
{
return $this->injections['metadata'];
}
protected function getServiceFactory()
{
return $this->injections['serviceFactory'];
}
protected function readCsvString(&$string, $CSV_SEPARATOR = ';', $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\n")
{
$o = array();
@@ -144,24 +144,24 @@ class Import extends \Espo\Core\Services\Base
$string = substr($string, $i);
return $o;
}
public function revert($scope, array $idsToRemove)
{
$ids = array();
if (!empty($scope) && !empty($idsToRemove)) {
foreach ($idsToRemove as $id) {
foreach ($idsToRemove as $id) {
$entity = $this->getEntityManager()->getEntity($scope, $id);
if ($entity) {
if ($entity) {
if ($this->getEntityManager()->removeEntity($entity)) {
$ids[] = $id;
$ids[] = $id;
}
}
$this->getEntityManager()->getRepository($scope)->deleteFromDb($id);
}
}
return $ids;
return $ids;
}
public function import($scope, array $fields, $attachmentId, array $params = array())
{
$delimiter = ',';
@@ -171,22 +171,22 @@ class Import extends \Espo\Core\Services\Base
$enclosure = '"';
if (!empty($params['textQualifier'])) {
$enclosure = $params['textQualifier'];
}
}
$contents = $this->getFileManager()->getContents('data/upload/' . $attachmentId);
if (empty($contents)) {
throw new Error('Import error');
}
}
$result = array(
'importedIds' => array(),
'updatedIds' => array(),
'duplicateIds' => array(),
);
'duplicateIds' => array(),
);
$i = -1;
while ($arr = $this->readCsvString($contents, $delimiter, $enclosure)) {
$i++;
$i++;
if ($i == 0 && !empty($params['headerRow'])) {
continue;
}
@@ -203,21 +203,21 @@ class Import extends \Espo\Core\Services\Base
if (!empty($r['duplicate'])) {
$result['duplicateIds'][] = $r['id'];
}
}
return array(
'countCreated' => count($result['importedIds']),
'countUpdated' => count($result['updatedIds']),
'importedIds' => $result['importedIds'],
'duplicateIds' => $result['duplicateIds'],
);
);
}
public function importRow($scope, array $fields, array $row, array $params = array())
{
// TODO create related records or related if exists, e.g. Account from accountName (skip users)
// Duplicate check
$id = null;
if (!empty($params['action'])) {
if ($params['action'] == 'createAndUpdate' && in_array('id', $fields)) {
@@ -225,19 +225,19 @@ class Import extends \Espo\Core\Services\Base
$id = $row[$i];
if (empty($id)) {
$id = null;
}
}
}
}
$entity = $this->getEntityManager()->getEntity($scope, $id);
$entity->set('assignedUserId', $this->getUser()->id);
if (!empty($params['defaultValues'])) {
$entity->set(get_object_vars($params['defaultValues']));
}
$fieldsDefs = $entity->getFields();
$relDefs = $entity->getRelations();
@@ -249,14 +249,14 @@ class Import extends \Espo\Core\Services\Base
$entity->id = $value;
}
continue;
}
}
if (array_key_exists($field, $fieldsDefs)) {
if ($value !== '') {
$type = $this->getMetadata()->get("entityDefs.{$scope}.fields.{$field}.type");
if ($type == 'personName') {
$lastNameField = 'last' . ucfirst($field);
$firstNameField = 'first' . ucfirst($field);
$firstName = '';
$lastName = $value;
switch ($params['personNameFormat']) {
@@ -283,7 +283,7 @@ class Import extends \Espo\Core\Services\Base
}
break;
}
if (!$entity->get($firstNameField)) {
$entity->set($firstNameField, $firstName);
}
@@ -291,44 +291,44 @@ class Import extends \Espo\Core\Services\Base
$entity->set($lastNameField, $lastName);
}
continue;
}
}
$entity->set($field, $this->parseValue($entity, $field, $value, $params));
}
}
}
}
foreach ($fields as $i => $field) {
if (array_key_exists($field, $fieldsDefs) && $fieldsDefs[$field]['type'] == Entity::FOREIGN) {
if ($entity->has($field)) {
$relation = $fieldsDefs[$field]['relation'];
if ($field == $relation . 'Name' && !$entity->has($relation . 'Id') && array_key_exists($relation, $relDefs)) {
if ($relDefs[$relation]['type'] == Entity::BELONGS_TO) {
$name = $entity->get($field);
$scope = $relDefs[$relation]['entity'];
$found = $this->getEntityManager()->getRepository($scope)->where(array('name' => $name))->findOne();
if ($found) {
$entity->set($relation . 'Id', $found->id);
} else {
if (!in_array($scope, 'User', 'Team')) {
// TODO create related record with name $name and relate
}
}
}
}
}
}
}
foreach ($fields as $i => $field) {
if (array_key_exists($field, $fieldsDefs) && $fieldsDefs[$field]['type'] == Entity::FOREIGN) {
if ($entity->has($field)) {
$relation = $fieldsDefs[$field]['relation'];
if ($field == $relation . 'Name' && !$entity->has($relation . 'Id') && array_key_exists($relation, $relDefs)) {
if ($relDefs[$relation]['type'] == Entity::BELONGS_TO) {
$name = $entity->get($field);
$scope = $relDefs[$relation]['entity'];
$found = $this->getEntityManager()->getRepository($scope)->where(array('name' => $name))->findOne();
if ($found) {
$entity->set($relation . 'Id', $found->id);
} else {
if (!in_array($scope, 'User', 'Team')) {
// TODO create related record with name $name and relate
}
}
}
}
}
}
}
$result = array();
$a = $entity->toArray();
try {
if ($this->getEntityManager()->saveEntity($entity)) {
$result['id'] = $entity->id;
@@ -339,37 +339,37 @@ class Import extends \Espo\Core\Services\Base
}
}
} catch (\Exception $e) {}
return $result;
}
protected function parseValue(Entity $entity, $field, $value, $params = array())
{
$decimalMark = '.';
if (!empty($params['decimalMark'])) {
$decimalMark = $params['decimalMark'];
}
$defaultCurrency = 'USD';
if (!empty($params['defaultCurrency'])) {
$dateFormat = $params['defaultCurrency'];
}
$dateFormat = 'Y-m-d';
if (!empty($params['dateFormat'])) {
$dateFormat = $params['dateFormat'];
}
$timeFormat = 'H:i';
if (!empty($params['timeFormat'])) {
$timeFormat = $params['timeFormat'];
}
$fieldDefs = $entity->getFields();
if (!empty($fieldDefs[$field])) {
$type = $fieldDefs[$field]['type'];
switch ($type) {
case Entity::DATE:
$dt = \DateTime::createFromFormat($dateFormat, $value);
@@ -383,17 +383,17 @@ class Import extends \Espo\Core\Services\Base
return $dt->format('Y-m-d H:i');
}
break;
case Entity::FLOAT:
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 {
@@ -401,9 +401,9 @@ class Import extends \Espo\Core\Services\Base
}
break;
}
}
return $value;
return $value;
}
}
+25 -25
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Services;
@@ -28,7 +28,7 @@ use \Espo\Core\Exceptions\NotFound;
use Espo\ORM\Entity;
class Notification extends \Espo\Core\Services\Base
{
{
protected $dependencies = array(
'entityManager',
'user',
@@ -43,68 +43,68 @@ class Notification extends \Espo\Core\Services\Base
protected function getUser()
{
return $this->injections['user'];
}
}
protected function getMetadata()
{
return $this->injections['metadata'];
}
public function notifyAboutMentionInPost($userId, $noteId)
{
$notification = $this->getEntityManager()->getEntity('Notification');
$notification = $this->getEntityManager()->getEntity('Notification');
$notification->set(array(
'type' => 'MentionInPost',
'data' => array('noteId' => $noteId),
'userId' => $userId
));
$this->getEntityManager()->saveEntity($notification);
$this->getEntityManager()->saveEntity($notification);
}
public function notifyAboutNote($userId, $noteId)
{
$notification = $this->getEntityManager()->getEntity('Notification');
$notification = $this->getEntityManager()->getEntity('Notification');
$notification->set(array(
'type' => 'Note',
'data' => array('noteId' => $noteId),
'userId' => $userId
));
$this->getEntityManager()->saveEntity($notification);
$this->getEntityManager()->saveEntity($notification);
}
public function notifyAboutNoteFromJob($data)
{
$userIdList = $data['userIdList'];
$noteId = $data['noteId'];
foreach ($userIdList as $userId) {
$this->notifyAboutNote($userId, $noteId);
}
return true;
}
public function getNotReadCount($userId)
{
$searchParams = array();
$searchParams['whereClause'] = array(
'userId' => $userId
);
);
return $this->getEntityManager()->getRepository('Notification')->where(array(
'userId' => $userId,
'read' => 0,
))->count();
}
public function markAllRead($userId)
{
{
$pdo = $this->getEntityManager()->getPDO();
$sql = "UPDATE notification SET `read` = 1 WHERE user_id = ".$pdo->quote($userId)." AND `read` = 0";
$pdo->prepare($sql)->execute();
return true;
}
public function getList($userId, array $params = array())
{
{
$searchParams = array();
$searchParams['whereClause'] = array(
'userId' => $userId
@@ -117,10 +117,10 @@ class Notification extends \Espo\Core\Services\Base
}
$searchParams['orderBy'] = 'createdAt';
$searchParams['order'] = 'DESC';
$collection = $this->getEntityManager()->getRepository('Notification')->find($searchParams);
$count = $this->getEntityManager()->getRepository('Notification')->count($searchParams);
$ids = array();
foreach ($collection as $k => $entity) {
$ids[] = $entity->id;
@@ -130,7 +130,7 @@ class Notification extends \Espo\Core\Services\Base
}
switch ($entity->get('type')) {
case 'Note':
case 'MentionInPost':
case 'MentionInPost':
$note = $this->getEntityManager()->getEntity('Note', $data->noteId);
if ($note) {
if ($note->get('parentId') && $note->get('parentType')) {
@@ -147,8 +147,8 @@ class Notification extends \Espo\Core\Services\Base
}
break;
}
}
}
if (!empty($ids)) {
$pdo = $this->getEntityManager()->getPDO();
$sql = "UPDATE notification SET `read` = 1 WHERE id IN ('" . implode("', '", $ids) ."')";
@@ -156,8 +156,8 @@ class Notification extends \Espo\Core\Services\Base
$s = $pdo->prepare($sql);
$s->execute();
}
return array(
'total' => $count,
'collection' => $collection
+157 -157
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Services;
@@ -44,19 +44,19 @@ class Record extends \Espo\Core\Services\Base
'selectManagerFactory',
'preferences'
);
protected $entityName;
private $streamService;
protected $notFilteringFields = array(); // TODO maybe remove it
protected $internalFields = array();
protected $readOnlyFields = array();
protected $linkSelectParams = array();
public function __construct()
{
parent::__construct();
@@ -75,69 +75,69 @@ class Record extends \Espo\Core\Services\Base
{
$this->entityName = $entityName;
}
protected function getServiceFactory()
{
return $this->injections['serviceFactory'];
}
protected function getSelectManagerFactory()
{
return $this->injections['selectManagerFactory'];
}
protected function getAcl()
{
return $this->injections['acl'];
}
protected function getFileManager()
{
return $this->injections['fileManager'];
}
}
protected function getPreferences()
{
return $this->injections['preferences'];
}
protected function getMetadata()
{
return $this->injections['metadata'];
}
protected function getRepository()
{
{
return $this->getEntityManager()->getRepository($this->entityName);
}
protected function getRecordService($name)
{
{
if ($this->getServiceFactory()->checkExists($name)) {
$service = $this->getServiceFactory()->create($name);
} else {
$service = $this->getServiceFactory()->create('Record');
$service->setEntityName($name);
}
}
return $service;
}
protected function prepareEntity($entity)
{
}
public function getEntity($id = null)
{
$entity = $this->getRepository()->get($id);
$entity = $this->getRepository()->get($id);
if (!empty($entity) && !empty($id)) {
$this->loadAdditionalFields($entity);
$this->loadAdditionalFields($entity);
if ($entity->getEntityName() == 'Opportunity') {
$contactsColumns = $entity->get('contactsColumns');
}
if (!$this->getAcl()->check($entity, 'read')) {
throw new Forbidden();
}
@@ -147,7 +147,7 @@ class Record extends \Espo\Core\Services\Base
}
return $entity;
}
protected function getStreamService()
{
if (empty($this->streamService)) {
@@ -155,16 +155,16 @@ class Record extends \Espo\Core\Services\Base
}
return $this->streamService;
}
protected function loadIsFollowed(Entity $entity)
{
{
if ($this->getStreamService()->checkIsFollowed($entity)) {
$entity->set('isFollowed', true);
} else {
$entity->set('isFollowed', false);
}
}
protected function loadLinkMultipleFields(Entity $entity)
{
$fieldDefs = $this->getMetadata()->get('entityDefs.' . $entity->getEntityName() . '.fields', array());
@@ -173,12 +173,12 @@ class Record extends \Espo\Core\Services\Base
$columns = null;
if (!empty($defs['columns'])) {
$columns = $defs['columns'];
}
$entity->loadLinkMultipleField($field, $columns);
}
$entity->loadLinkMultipleField($field, $columns);
}
}
}
protected function loadParentNameFields(Entity $entity)
{
$fieldDefs = $this->getMetadata()->get('entityDefs.' . $entity->getEntityName() . '.fields', array());
@@ -186,8 +186,8 @@ class Record extends \Espo\Core\Services\Base
if (isset($defs['type']) && $defs['type'] == 'linkParent') {
$id = $entity->get($field . 'Id');
$scope = $entity->get($field . 'Type');
if ($scope) {
if ($scope) {
if ($foreignEntity = $this->getEntityManager()->getEntity($scope, $id)) {
$entity->set($field . 'Name', $foreignEntity->get('name'));
}
@@ -195,44 +195,44 @@ class Record extends \Espo\Core\Services\Base
}
}
}
protected function loadAdditionalFields($entity)
{
$this->loadLinkMultipleFields($entity);
$this->loadLinkMultipleFields($entity);
$this->loadParentNameFields($entity);
$this->loadIsFollowed($entity);
$this->loadEmailAddressField($entity);
$this->loadPhoneNumberField($entity);
}
protected function loadEmailAddressField(Entity $entity)
{
$fieldDefs = $this->getMetadata()->get('entityDefs.' . $entity->getEntityName() . '.fields', array());
$fieldDefs = $this->getMetadata()->get('entityDefs.' . $entity->getEntityName() . '.fields', array());
if (!empty($fieldDefs['emailAddress']) && $fieldDefs['emailAddress']['type'] == 'email') {
$dataFieldName = 'emailAddressData';
$entity->set($dataFieldName, $this->getEntityManager()->getRepository('EmailAddress')->getEmailAddressData($entity));
}
}
protected function loadPhoneNumberField(Entity $entity)
{
$fieldDefs = $this->getMetadata()->get('entityDefs.' . $entity->getEntityName() . '.fields', array());
$fieldDefs = $this->getMetadata()->get('entityDefs.' . $entity->getEntityName() . '.fields', array());
if (!empty($fieldDefs['phoneNumber']) && $fieldDefs['phoneNumber']['type'] == 'phone') {
$dataFieldName = 'phoneNumberData';
$entity->set($dataFieldName, $this->getEntityManager()->getRepository('PhoneNumber')->getPhoneNumberData($entity));
}
}
protected function getSelectManager($entityName)
{
return $this->getSelectManagerFactory()->create($entityName);
}
protected function storeEntity(Entity $entity)
{
return $this->getRepository()->save($entity);
}
protected function isValid($entity)
{
$fieldDefs = $entity->getFields();
@@ -243,14 +243,14 @@ class Record extends \Espo\Core\Services\Base
}
return true;
}
protected function stripTags($string)
{
return strip_tags($string, '<a><img><p><br><span><ol><ul><li><blockquote><pre><h1><h2><h3><h4><h5><table><tr><td><th><thead><tbody><i><b>');
}
protected function filterInputField($field, $value)
{
{
if (in_array($field, $this->notFilteringFields)) {
return $value;
}
@@ -259,14 +259,14 @@ class Record extends \Espo\Core\Services\Base
$value = $this->$methodName($value);
}
return $value;
}
}
protected function filterInput(&$data)
{
{
foreach ($this->readOnlyFields as $field) {
unset($data[$field]);
}
foreach ($data as $key => $value) {
if (is_array($data[$key])) {
foreach ($data[$key] as $i => $v) {
@@ -275,32 +275,32 @@ class Record extends \Espo\Core\Services\Base
} else if ($data[$key] instanceof \stdClass) {
$propertyList = get_object_vars($data[$key]);
foreach ($propertyList as $property => $value) {
$data[$key]->$property = $this->filterInputField($property, $data[$key]->$property);
$data[$key]->$property = $this->filterInputField($property, $data[$key]->$property);
}
} else {
$data[$key] = $this->filterInputField($key, $data[$key]);
}
}
}
protected function handleInput(&$data)
{
}
public function createEntity($data)
{
$entity = $this->getEntity();
$this->filterInput($data);
$this->handleInput($data);
$entity->set($data);
if (!$this->isValid($entity)) {
throw new BadRequest();
}
if (empty($data['forceDuplicate'])) {
$duplicates = $this->checkEntityForDuplicate($entity);
if (!empty($duplicates)) {
@@ -310,36 +310,36 @@ class Record extends \Espo\Core\Services\Base
);
throw new Conflict(json_encode($reason));
}
}
}
if ($this->storeEntity($entity)) {
$this->prepareEntityForOutput($entity);
return $entity;
}
}
throw new Error();
}
public function updateEntity($id, $data)
{
unset($data['deleted']);
{
unset($data['deleted']);
$this->filterInput($data);
$this->handleInput($data);
$entity = $this->getEntity($id);
if (!$this->getAcl()->check($entity, 'edit')) {
throw new Forbidden();
}
$entity->set($data);
if (!$this->isValid($entity)) {
throw new BadRequest();
}
}
if ($this->storeEntity($entity)) {
$this->prepareEntityForOutput($entity);
return $entity;
@@ -355,20 +355,20 @@ class Record extends \Espo\Core\Services\Base
if (!$this->getAcl()->check($entity, 'delete')) {
throw new Forbidden();
}
return $this->getRepository()->remove($entity);
}
public function findEntities($params)
{
{
$selectParams = $this->getSelectManager($this->entityName)->getSelectParams($params, true);
$collection = $this->getRepository()->find($selectParams);
$collection = $this->getRepository()->find($selectParams);
foreach ($collection as $e) {
$this->loadParentNameFields($e);
$this->prepareEntityForOutput($e);
}
return array(
'total' => $this->getRepository()->count($selectParams),
'collection' => $collection,
@@ -376,97 +376,97 @@ class Record extends \Espo\Core\Services\Base
}
public function findLinkedEntities($id, $link, $params)
{
$entity = $this->getEntity($id);
{
$entity = $this->getEntity($id);
$foreignEntityName = $entity->relations[$link]['entity'];
if (!$this->getAcl()->check($entity, 'read')) {
throw new Forbidden();
}
if (!$this->getAcl()->check($foreignEntityName, 'read')) {
throw new Forbidden();
}
$selectParams = $this->getSelectManager($foreignEntityName)->getSelectParams($params, true);
if (array_key_exists($link, $this->linkSelectParams)) {
$selectParams = array_merge($selectParams, $this->linkSelectParams[$link]);
}
$collection = $this->getRepository()->findRelated($entity, $link, $selectParams);
$collection = $this->getRepository()->findRelated($entity, $link, $selectParams);
$recordService = $this->getRecordService($foreignEntityName);
foreach ($collection as $e) {
$this->loadParentNameFields($e);
$recordService->prepareEntityForOutput($e);
}
return array(
'total' => $this->getRepository()->countRelated($entity, $link, $selectParams),
'collection' => $collection,
);
}
public function linkEntity($id, $link, $foreignId)
{
$entity = $this->getEntity($id);
{
$entity = $this->getEntity($id);
$entityName = $entity->getEntityName($entity);
$foreignEntityName = $entity->relations[$link]['entity'];
$foreignEntityName = $entity->relations[$link]['entity'];
if (!$this->getAcl()->check($entity, 'edit')) {
throw new Forbidden();
}
if (empty($foreignEntityName)) {
throw new Error();
}
$foreignEntity = $this->getEntityManager()->getEntity($foreignEntityName, $foreignId);
if (!$this->getAcl()->check($foreignEntity, 'edit')) {
throw new Forbidden();
}
}
if (!empty($foreignEntity)) {
$this->getRepository()->relate($entity, $link, $foreignEntity);
return true;
return true;
}
}
public function unlinkEntity($id, $link, $foreignId)
{
$entity = $this->getEntity($id);
$entity = $this->getEntity($id);
$entityName = $entity->getEntityName($entity);
$foreignEntityName = $entity->relations[$link]['entity'];
$foreignEntityName = $entity->relations[$link]['entity'];
if (!$this->getAcl()->check($entity, 'edit')) {
throw new Forbidden();
}
if (empty($foreignEntityName)) {
throw new Error();
}
$foreignEntity = $this->getEntityManager()->getEntity($foreignEntityName, $foreignId);
if (!$this->getAcl()->check($foreignEntity, 'edit')) {
throw new Forbidden();
}
if (!empty($foreignEntity)) {
$this->getRepository()->unrelate($entity, $link, $foreignEntity);
return true;
return true;
}
}
public function massUpdate($attributes = array(), $ids = array(), $where = array())
{
$idsUpdated = array();
$idsUpdated = array();
$repository = $this->getRepository();
if (!empty($ids)) {
foreach ($ids as $id) {
$entity = $this->getEntity($id);
@@ -478,17 +478,17 @@ class Record extends \Espo\Core\Services\Base
}
}
}
return $idsUpdated;
// TODO update $where
}
public function massRemove($ids = array(), $where = array())
{
$idsRemoved = array();
$idsRemoved = array();
$repository = $this->getRepository();
if (!empty($ids)) {
foreach ($ids as $id) {
$entity = $this->getEntity($id);
@@ -499,49 +499,49 @@ class Record extends \Espo\Core\Services\Base
}
}
}
return $idsRemoved;
// TODO update $where
}
public function follow($id, $userId = null)
{
$entity = $this->getEntity($id);
if (!$this->getAcl()->check($entity, 'read')) {
throw new Forbidden();
}
if (empty($userId)) {
$userId = $this->getUser()->id;
}
return $this->getStreamService()->followEntity($entity, $userId);
}
public function unfollow($id, $userId = null)
{
$entity = $this->getEntity($id);
if (!$this->getAcl()->check($entity, 'read')) {
throw new Forbidden();
}
}
if (empty($userId)) {
$userId = $this->getUser()->id;
}
return $this->getStreamService()->unfollowEntity($entity, $userId);
}
protected function getDuplicateWhereClause(Entity $entity)
{
return false;
}
public function checkEntityForDuplicate(Entity $entity)
{
{
$where = $this->getDuplicateWhereClause($entity);
if ($where) {
$duplicates = $this->getRepository()->where($where)->find();
if (count($duplicates)) {
@@ -551,12 +551,12 @@ class Record extends \Espo\Core\Services\Base
}
return $result;
}
}
}
return false;
}
public function export($ids, $where)
{
{
if (!empty($ids)) {
$where = array(
array(
@@ -565,15 +565,15 @@ class Record extends \Espo\Core\Services\Base
'value' => $ids
)
);
}
}
$selectParams = $this->getSelectManager($this->entityName)->getSelectParams(array('where' => $where), true);
$collection = $this->getRepository()->find($selectParams);
$arr = array();
$collection->toArray();
$fieldsToSkip = array(
'modifiedByName',
'createdByName',
@@ -583,7 +583,7 @@ class Record extends \Espo\Core\Services\Base
'createdAt',
'deleted',
);
$fields = null;
foreach ($collection as $entity) {
if (empty($fields)) {
@@ -592,9 +592,9 @@ class Record extends \Espo\Core\Services\Base
if (in_array($field, $fieldsToSkip)) {
continue;
}
if (empty($defs['notStorable'])) {
$fields[] = $field;
$fields[] = $field;
} else {
if (in_array($defs['type'], array('email', 'phone'))) {
$fields[] = $field;
@@ -604,20 +604,20 @@ class Record extends \Espo\Core\Services\Base
}
}
}
$row = array();
foreach ($fields as $field) {
$row[$field] = $entity->get($field);
}
$arr[] = $row;
}
}
$delimiter = $this->getPreferences()->get('exportDelimiter');
if (empty($delimiter)) {
$delimiter = ',';
}
$fp = fopen('php://temp', 'w');
$fp = fopen('php://temp', 'w');
fputcsv($fp, array_keys($arr[0]), $delimiter);
foreach ($arr as $row) {
fputcsv($fp, $row, $delimiter);
@@ -625,26 +625,26 @@ class Record extends \Espo\Core\Services\Base
rewind($fp);
$csv = stream_get_contents($fp);
fclose($fp);
$fileName = "Export_{$this->entityName}.csv";
$attachment = $this->getEntityManager()->getEntity('Attachment');
$attachment->set('name', $fileName);
$attachment->set('role', 'Export File');
$attachment->set('type', 'text/csv');
$this->getEntityManager()->saveEntity($attachment);
if (!empty($attachment->id)) {
$this->getInjection('fileManager')->putContents('data/upload/' . $attachment->id, $csv);
// TODO cron job to remove file
if (!empty($attachment->id)) {
$this->getInjection('fileManager')->putContents('data/upload/' . $attachment->id, $csv);
// TODO cron job to remove file
return $attachment->id;
}
}
throw new Error();
}
public function prepareEntityForOutput(Entity $entity)
{
{
foreach ($this->internalFields as $field) {
$entity->clear($field);
}
+108 -108
View File
@@ -18,7 +18,7 @@
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
************************************************************************/
namespace Espo\Services;
@@ -33,13 +33,13 @@ class Stream extends \Espo\Core\Services\Base
'Lead' => array(
'field' => 'status',
'style' => array(
'New' => 'primary',
'New' => 'primary',
'Assigned' => 'primary',
'In Process' => 'primary',
'Converted' => 'success',
'Recycled' => 'danger',
'Dead' => 'danger',
),
),
),
'Case' => array(
'field' => 'status',
@@ -50,17 +50,17 @@ class Stream extends \Espo\Core\Services\Base
'Closed' => 'success',
'Rejected' => 'danger',
'Duplicate' => 'danger',
),
),
),
'Opportunity' => array(
'field' => 'stage',
'style' => array(
'style' => array(
'Closed Won' => 'success',
'Closed Lost' => 'danger',
),
),
),
),
);
protected $dependencies = array(
'entityManager',
'config',
@@ -74,31 +74,31 @@ class Stream extends \Espo\Core\Services\Base
{
return $this->injections['container']->get('serviceFactory');
}
protected function getAcl()
{
return $this->injections['acl'];
}
protected function getMetadata()
{
return $this->injections['metadata'];
}
public function checkIsFollowed(Entity $entity, $userId = null)
{
if (empty($userId)) {
$userId = $this->getUser()->id;
}
$pdo = $this->getEntityManager()->getPDO();
$sql = "
SELECT id FROM subscription
WHERE
SELECT id FROM subscription
WHERE
entity_id = " . $pdo->quote($entity->id) . " AND entity_type = " . $pdo->quote($entity->getEntityName()) . " AND
user_id = " . $pdo->quote($userId) . "
";
$sth = $pdo->prepare($sql);
$sth->execute();
if ($sth->fetchAll()) {
@@ -106,7 +106,7 @@ class Stream extends \Espo\Core\Services\Base
}
return false;
}
public function followEntity(Entity $entity, $userId)
{
if ($userId == 'system') {
@@ -115,9 +115,9 @@ class Stream extends \Espo\Core\Services\Base
if (!$this->getMetadata()->get('scopes.' . $entity->getEntityName() . '.stream')) {
throw new Error();
}
$pdo = $this->getEntityManager()->getPDO();
if (!$this->checkIsFollowed($entity, $userId)) {
$sql = "
INSERT INTO subscription
@@ -129,42 +129,42 @@ class Stream extends \Espo\Core\Services\Base
}
return true;
}
public function unfollowEntity(Entity $entity, $userId)
{
if (!$this->getMetadata()->get('scopes.' . $entity->getEntityName() . '.stream')) {
throw new Error();
}
}
$pdo = $this->getEntityManager()->getPDO();
$sql = "
DELETE FROM subscription
WHERE
WHERE
entity_id = " . $pdo->quote($entity->id) . " AND entity_type = " . $pdo->quote($entity->getEntityName()) . " AND
user_id = " . $pdo->quote($userId) . "
";
$sth = $pdo->prepare($sql)->execute();
return true;
}
public function unfollowAllUsersFromEntity(Entity $entity)
{
if (empty($entity->id)) {
return;
}
$pdo = $this->getEntityManager()->getPDO();
$sql = "
DELETE FROM subscription
WHERE
WHERE
entity_id = " . $pdo->quote($entity->id) . " AND entity_type = " . $pdo->quote($entity->getEntityName()) . "
";
$sth = $pdo->prepare($sql)->execute();
$sth = $pdo->prepare($sql)->execute();
}
public function findUserStream($params = array())
{
$selectParams = array(
@@ -173,69 +173,69 @@ class Stream extends \Espo\Core\Services\Base
'orderBy' => 'createdAt',
'order' => 'DESC',
'customJoin' => "
JOIN subscription ON
note.parent_type = subscription.entity_type AND
JOIN subscription ON
note.parent_type = subscription.entity_type AND
note.parent_id = subscription.entity_id AND
subscription.user_id = '" . $this->getUser()->id . "'
"
);
if (!empty($params['after'])) {
$where = array();
$where['createdAt>'] = $params['after'];
$selectParams['whereClause'] = $where;
}
$collection = $this->getEntityManager()->getRepository('Note')->find($selectParams);
foreach ($collection as $e) {
if ($e->get('type') == 'Post' || $e->get('type') == 'EmailReceived') {
$e->loadAttachments();
}
}
foreach ($collection as $e) {
if ($e->get('parentId') && $e->get('parentType')) {
$entity = $this->getEntityManager()->getEntity($e->get('parentType'), $e->get('parentId'));
if ($entity) {
$e->set('parentName', $entity->get('name'));
}
}
}
}
unset($selectParams['whereClause']['createdAt>']);
unset($selectParams['whereClause']['createdAt>']);
$count = $this->getEntityManager()->getRepository('Note')->count($selectParams);
return array(
'total' => $count,
'collection' => $collection,
);
);
}
public function find($scope, $id, $params = array())
{
if ($scope == 'User') {
return $this->findUserStream($params);
}
$entity = $this->getEntityManager()->getEntity($scope, $id);
if (empty($entity)) {
throw new NotFound();
}
if (!$this->getAcl($entity, 'read')) {
throw new Forbidden();
}
$where = array(
'parentType' => $scope,
'parentId' => $id
);
if (!empty($params['after'])) {
$where['createdAt>'] = $params['after'];
}
$collection = $this->getEntityManager()->getRepository('Note')->find(array(
'whereClause' => $where,
'offset' => $params['offset'],
@@ -243,24 +243,24 @@ class Stream extends \Espo\Core\Services\Base
'orderBy' => 'createdAt',
'order' => 'DESC'
));
foreach ($collection as $e) {
if ($e->get('type') == 'Post' || $e->get('type') == 'EmailReceived') {
$e->loadAttachments();
}
}
unset($where['createdAt>']);
$count = $this->getEntityManager()->getRepository('Note')->count(array(
'whereClause' => $where,
));
return array(
'total' => $count,
'collection' => $collection,
);
}
);
}
protected function loadAssignedUserName(Entity $entity)
{
$user = $this->getEntityManager()->getEntity('User', $entity->get('assignedUserId'));
@@ -268,41 +268,41 @@ class Stream extends \Espo\Core\Services\Base
$entity->set('assignedUserName', $user->get('name'));
}
}
public function noteEmailReceived(Entity $entity, Entity $email, $isInitial = false)
{
$entityName = $entity->getEntityName();
$note = $this->getEntityManager()->getEntity('Note');
$note->set('type', 'EmailReceived');
$note->set('parentId', $entity->id);
$note->set('parentType', $entityName);
$note->set('post', $email->getBodyPlain());
$data = array();
$data['emailId'] = $email->id;
$data['emailName'] = $email->get('name');
$data['isInitial'] = $isInitial;
$note->set('data', $data);
$this->getEntityManager()->saveEntity($note);
$attachmentsIds = $email->get('attachmentsIds');
if (!empty($attachmentsIds)) {
$attachmentsData = $this->getServiceFactory()->create('Email')->copyAttachments($email->id, 'Note', $note->id);
$attachmentsData = $this->getServiceFactory()->create('Email')->copyAttachments($email->id, 'Note', $note->id);
}
}
public function noteCreate(Entity $entity)
{
$entityName = $entity->getEntityName();
$note = $this->getEntityManager()->getEntity('Note');
$note->set('type', 'Create');
$note->set('parentId', $entity->id);
$note->set('parentType', $entityName);
@@ -312,35 +312,35 @@ class Stream extends \Espo\Core\Services\Base
if ($entity->get('assignedUserId') != $entity->get('createdById')) {
if (!$entity->has('assignedUserName')) {
$this->loadAssignedUserName($entity);
}
}
$data['assignedUserId'] = $entity->get('assignedUserId');
$data['assignedUserName'] = $entity->get('assignedUserName');
$data['assignedUserName'] = $entity->get('assignedUserName');
}
if (array_key_exists($entityName, $this->statusDefs)) {
$field = $this->statusDefs[$entityName]['field'];
$value = $entity->get($field);
if (!empty($value)) {
$style = 'default';
if (!empty($value)) {
$style = 'default';
if (!empty($this->statusDefs[$entityName]['style'][$value])) {
$style = $this->statusDefs[$entityName]['style'][$value];
}
}
$data['statusValue'] = $value;
$data['statusField'] = $field;
$data['statusStyle'] = $style;
$data['statusStyle'] = $style;
}
}
$note->set('data', $data);
$this->getEntityManager()->saveEntity($note);
}
public function noteCreateRelated(Entity $entity, $entityType, $id, $action = 'created')
{
$note = $this->getEntityManager()->getEntity('Note');
$note->set('type', 'CreateRelated');
$note->set('type', 'CreateRelated');
$note->set('parentId', $id);
$note->set('parentType', $entityType);
@@ -349,16 +349,16 @@ class Stream extends \Espo\Core\Services\Base
'entityType' => $entity->getEntityName(),
'entityId' => $entity->id,
'entityName' => $entity->get('name')
));
));
$this->getEntityManager()->saveEntity($note);
$this->getEntityManager()->saveEntity($note);
}
public function noteAssign(Entity $entity)
{
$note = $this->getEntityManager()->getEntity('Note');
$note->set('type', 'Assign');
$note->set('type', 'Assign');
$note->set('parentId', $entity->id);
$note->set('parentType', $entity->getEntityName());
@@ -368,48 +368,48 @@ class Stream extends \Espo\Core\Services\Base
$note->set('data', array(
'assignedUserId' => $entity->get('assignedUserId'),
'assignedUserName' => $entity->get('assignedUserName'),
));
));
$this->getEntityManager()->saveEntity($note);
}
public function noteStatus(Entity $entity, $field)
{
$note = $this->getEntityManager()->getEntity('Note');
$note->set('type', 'Status');
$note->set('type', 'Status');
$note->set('parentId', $entity->id);
$note->set('parentType', $entity->getEntityName());
$style = 'default';
$entityName = $entity->getEntityName();
$style = 'default';
$entityName = $entity->getEntityName();
$value = $entity->get($field);
if (!empty($this->statusDefs[$entityName]) && !empty($this->statusDefs[$entityName]['style'][$value])) {
$style = $this->statusDefs[$entityName]['style'][$value];
}
$note->set('data', array(
'field' => $field,
'value' => $value,
'style' => $style,
));
$this->getEntityManager()->saveEntity($note);
$this->getEntityManager()->saveEntity($note);
}
protected function getAuditedFields(Entity $entity)
{
$entityName = $entity->getEntityName();
if (!array_key_exists($entityName, $this->auditedFieldsCache)) {
$entityName = $entity->getEntityName();
if (!array_key_exists($entityName, $this->auditedFieldsCache)) {
$fields = $this->getMetadata()->get('entityDefs.' . $entityName . '.fields');
$auditedFields = array();
$auditedFields = array();
foreach ($fields as $field => $d) {
if (!empty($d['audited'])) {
$attributes = array();
$fieldsDefs = $this->getMetadata()->get('fields.' . $d['type']);
if (empty($fieldsDefs['actualFields'])) {
$attributes[] = $field;
} else {
@@ -421,30 +421,30 @@ class Stream extends \Espo\Core\Services\Base
}
}
}
$auditedFields[$field] = $attributes;
}
}
$this->auditedFieldsCache[$entityName] = $auditedFields;
}
return $this->auditedFieldsCache[$entityName];
}
public function handleAudited($entity)
{
$auditedFields = $this->getAuditedFields($entity);
$updatedFields = array();
$was = array();
$became = array();
foreach ($auditedFields as $field => $attrs) {
$updated = false;
foreach ($attrs as $attr) {
foreach ($attrs as $attr) {
if ($entity->get($attr) != $entity->getFetched($attr)) {
$updated = true;
$updated = true;
}
}
if ($updated) {
@@ -455,11 +455,11 @@ class Stream extends \Espo\Core\Services\Base
}
}
}
if (!empty($updatedFields)) {
$note = $this->getEntityManager()->getEntity('Note');
$note->set('type', 'Update');
$note->set('type', 'Update');
$note->set('parentId', $entity->id);
$note->set('parentType', $entity->getEntityName());
@@ -469,7 +469,7 @@ class Stream extends \Espo\Core\Services\Base
'was' => $was,
'became' => $became,
)
));
));
$this->getEntityManager()->saveEntity($note);
}