Example #1
0
 public function __construct()
 {
     $this->aUserIds = array();
     $this->oEngine = Engine::GetInstance();
     $sId = strtolower(get_class($this));
     $this->aConfig = Config::Get('plugin.botchecker.rules.' . $sId);
     $this->iHumanScore = 0;
     $this->iBotScore = 0;
 }
Example #2
0
 public static function deleteUser($iUserId)
 {
     $aFilter = array('user_id' => $iUserId);
     $iTopicCount = Engine::GetInstance()->Topic_GetCountTopicsByFilter($aFilter);
     $iCommentCount = Engine::GetInstance()->Comment_GetCountCommentsByUserId($iUserId, 'topic');
     if ($iTopicCount == 0 && $iCommentCount == 0) {
         Engine::GetInstance()->PluginBotchecker_Botchecker_deleteUser($iUserId);
         return '[delete] Simple delete user with id=' . $iUserId;
     } else {
         return '[skip] User with id=' . $iUserId . ' has ' . $iTopicCount . ' topics and ' . $iCommentCount . ' commants';
     }
 }
 /**
  * Выполняет удаление всех связей many_to_many сущности
  *
  * @param $oEntity
  * @param $sRelationKey
  */
 protected function _deleteManyToManyRelation($oEntity, $sRelationKey)
 {
     $aRelations = $oEntity->_getRelations();
     if (!isset($aRelations[$sRelationKey]['type']) or $aRelations[$sRelationKey]['type'] != EntityORM::RELATION_TYPE_MANY_TO_MANY) {
         return;
     }
     $aFilterAdd = $aRelations[$sRelationKey]['filter'];
     $oEntityRelation = Engine::GetEntity($aRelations[$sRelationKey]['join_entity']);
     /**
      * По сущности связи формируем запрос за получение списка сохраненых связей в БД
      */
     $sCmd = Engine::GetPluginPrefix($aRelations[$sRelationKey]['join_entity']) . 'Module' . Engine::GetModuleName($aRelations[$sRelationKey]['join_entity']) . '_Get' . Engine::GetEntityName($aRelations[$sRelationKey]['join_entity']) . 'ItemsByFilter';
     list($aFilter) = $this->oMapperORM->BuildFilter($aFilterAdd, $oEntityRelation);
     $aFilter[$aRelations[$sRelationKey]['join_key']] = $oEntity->_getPrimaryKeyValue();
     $aRelationItemsSaved = Engine::GetInstance()->_CallModule($sCmd, array($aFilter));
     foreach ($aRelationItemsSaved as $oRelation) {
         $oRelation->Delete();
     }
 }
 /**
  * Возвращает ядро
  * @see Engine::GetInstance
  *
  * @return Engine
  */
 public static function E()
 {
     return Engine::GetInstance();
 }
Example #5
0
 /**
  * Вызов методов сущности
  *
  * @param unknown_type $sName
  * @param unknown_type $aArgs
  * @return unknown
  */
 public function __call($sName, $aArgs)
 {
     $sType = substr($sName, 0, strpos(func_underscore($sName), '_'));
     if (!strpos($sName, '_') and in_array($sType, array('get', 'set', 'reload'))) {
         $sKey = func_underscore(preg_replace('/' . $sType . '/', '', $sName, 1));
         if ($sType == 'get') {
             if (isset($this->_aData[$sKey])) {
                 return $this->_aData[$sKey];
             } else {
                 $sField = $this->_getField($sKey);
                 if ($sField != $sKey && isset($this->_aData[$sField])) {
                     return $this->_aData[$sField];
                 }
             }
             /**
              * Проверяем на связи
              */
             if (array_key_exists($sKey, $this->aRelations)) {
                 $sEntityRel = $this->aRelations[$sKey][1];
                 $sRelationType = $this->aRelations[$sKey][0];
                 $sRelationKey = $this->aRelations[$sKey][2];
                 $sRelationJoinTable = null;
                 $sRelationJoinTableKey = 0;
                 // foreign key в join-таблице для текущей сущности
                 if ($sRelationType == self::RELATION_TYPE_MANY_TO_MANY && array_key_exists(3, $this->aRelations[$sKey])) {
                     $sRelationJoinTable = $this->aRelations[$sKey][3];
                     $sRelationJoinTableKey = isset($this->aRelations[$sKey][4]) ? $this->aRelations[$sKey][4] : $this->_getPrimaryKey();
                 }
                 /**
                  * Если связь уже загруженна, то возвращаем сразу результат
                  */
                 if (array_key_exists($sKey, $this->aRelationsData)) {
                     return $this->aRelationsData[$sKey];
                 }
                 $sRelModuleName = Engine::GetModuleName($sEntityRel);
                 $sRelEntityName = Engine::GetEntityName($sEntityRel);
                 $sRelPluginPrefix = Engine::GetPluginPrefix($sEntityRel);
                 $sRelPrimaryKey = 'id';
                 if ($oRelEntity = Engine::GetEntity($sEntityRel)) {
                     $sRelPrimaryKey = $oRelEntity->_getPrimaryKey();
                 }
                 $iPrimaryKeyValue = $this->_getDataOne($this->_getPrimaryKey());
                 $sCmd = '';
                 $mCmdArgs = array();
                 switch ($sRelationType) {
                     case self::RELATION_TYPE_BELONGS_TO:
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}By" . func_camelize($sRelPrimaryKey);
                         $mCmdArgs = $this->_getDataOne($sRelationKey);
                         break;
                     case self::RELATION_TYPE_HAS_ONE:
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}By" . func_camelize($sRelationKey);
                         $mCmdArgs = $iPrimaryKeyValue;
                         break;
                     case self::RELATION_TYPE_HAS_MANY:
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}ItemsByFilter";
                         $mCmdArgs = array($sRelationKey => $iPrimaryKeyValue);
                         break;
                     case self::RELATION_TYPE_MANY_TO_MANY:
                         $sCmd = "{$sRelPluginPrefix}Module{$sRelModuleName}_get{$sRelEntityName}ItemsByJoinTable";
                         $mCmdArgs = array('#join_table' => Config::Get($sRelationJoinTable), '#relation_key' => $sRelationKey, '#by_key' => $sRelationJoinTableKey, '#by_value' => $iPrimaryKeyValue, '#index-from-primary' => true);
                         break;
                     default:
                         break;
                 }
                 // Нужно ли учитывать дополнительный фильтр
                 $bUseFilter = is_array($mCmdArgs) && array_key_exists(0, $aArgs) && is_array($aArgs[0]);
                 if ($bUseFilter) {
                     $mCmdArgs = array_merge($mCmdArgs, $aArgs[0]);
                 }
                 $res = Engine::GetInstance()->_CallModule($sCmd, array($mCmdArgs));
                 // Сохраняем данные только в случае "чистой" выборки
                 if (!$bUseFilter) {
                     $this->aRelationsData[$sKey] = $res;
                 }
                 // Создаём объекты-обёртки для связей MANY_TO_MANY
                 if ($sRelationType == self::RELATION_TYPE_MANY_TO_MANY) {
                     $this->_aManyToManyRelations[$sKey] = new LS_ManyToManyRelation($res);
                 }
                 return $res;
             }
             return null;
         } elseif ($sType == 'set' and array_key_exists(0, $aArgs)) {
             if (array_key_exists($sKey, $this->aRelations)) {
                 $this->aRelationsData[$sKey] = $aArgs[0];
             } else {
                 $this->_aData[$this->_getField($sKey)] = $aArgs[0];
             }
         } elseif ($sType == 'reload') {
             if (array_key_exists($sKey, $this->aRelationsData)) {
                 unset($this->aRelationsData[$sKey]);
                 return $this->__call('get' . func_camelize($sKey), $aArgs);
             }
         }
     } else {
         return Engine::getInstance()->_CallModule($sName, $aArgs);
     }
 }
Example #6
0
 /**
  * Получить список сущностей по фильтру
  *
  * @param unknown_type $aFilter
  * @param unknown_type $sEntityFull
  * @return unknown
  */
 public function GetItemsByFilter($aFilter = array(), $sEntityFull = null)
 {
     if (is_null($aFilter)) {
         $aFilter = array();
     }
     if (is_null($sEntityFull)) {
         $sEntityFull = Engine::GetPluginPrefix($this) . 'Module' . Engine::GetModuleName($this) . '_Entity' . Engine::GetModuleName(get_class($this));
     } elseif (!substr_count($sEntityFull, '_')) {
         $sEntityFull = Engine::GetPluginPrefix($this) . 'Module' . Engine::GetModuleName($this) . '_Entity' . $sEntityFull;
     }
     // Если параметр #cache указан и пуст, значит игнорируем кэширование для запроса
     if (array_key_exists('#cache', $aFilter) && !$aFilter['#cache']) {
         $aEntities = $this->oMapperORM->GetItemsByFilter($aFilter, $sEntityFull);
     } else {
         $sEntityFullRoot = $this->Plugin_GetRootDelegater('entity', $sEntityFull);
         $sCacheKey = $sEntityFullRoot . '_items_by_filter_' . serialize($aFilter);
         $aCacheTags = array($sEntityFullRoot . '_save', $sEntityFullRoot . '_delete');
         $iCacheTime = 60 * 60 * 24;
         // скорее лучше хранить в свойстве сущности, для возможности выборочного переопределения
         // переопределяем из параметров
         if (isset($aFilter['#cache'][0])) {
             $sCacheKey = $aFilter['#cache'][0];
         }
         if (isset($aFilter['#cache'][1])) {
             $aCacheTags = $aFilter['#cache'][1];
         }
         if (isset($aFilter['#cache'][2])) {
             $iCacheTime = $aFilter['#cache'][2];
         }
         if (false === ($aEntities = $this->Cache_Get($sCacheKey))) {
             $aEntities = $this->oMapperORM->GetItemsByFilter($aFilter, $sEntityFull);
             $this->Cache_Set($aEntities, $sCacheKey, $aCacheTags, $iCacheTime);
         }
     }
     /**
      * Если необходимо подцепить связанные данные
      */
     if (count($aEntities) and isset($aFilter['#with'])) {
         if (!is_array($aFilter['#with'])) {
             $aFilter['#with'] = array($aFilter['#with']);
         }
         $oEntityEmpty = Engine::GetEntity($sEntityFull);
         $aRelations = $oEntityEmpty->_getRelations();
         $aEntityKeys = array();
         foreach ($aFilter['#with'] as $sRelationName) {
             $sRelType = $aRelations[$sRelationName][0];
             $sRelEntity = $this->Plugin_GetRootDelegater('entity', $aRelations[$sRelationName][1]);
             // получаем корневую сущность, без учета наследников
             $sRelKey = $aRelations[$sRelationName][2];
             if (!array_key_exists($sRelationName, $aRelations) or !in_array($sRelType, array(EntityORM::RELATION_TYPE_BELONGS_TO, EntityORM::RELATION_TYPE_HAS_ONE))) {
                 throw new Exception("The entity <{$sEntityFull}> not have relation <{$sRelationName}>");
             }
             /**
              * Формируем список ключей
              */
             foreach ($aEntities as $oEntity) {
                 $aEntityKeys[$sRelKey][] = $oEntity->_getDataOne($sRelKey);
             }
             $aEntityKeys[$sRelKey] = array_unique($aEntityKeys[$sRelKey]);
             /**
              * Делаем общий запрос по всем ключам
              */
             $oRelEntityEmpty = Engine::GetEntity($sRelEntity);
             $sRelModuleName = Engine::GetModuleName($sRelEntity);
             $sRelEntityName = Engine::GetEntityName($sRelEntity);
             $sRelPluginPrefix = Engine::GetPluginPrefix($sRelEntity);
             $sRelPrimaryKey = method_exists($oRelEntityEmpty, '_getPrimaryKey') ? func_camelize($oRelEntityEmpty->_getPrimaryKey()) : 'Id';
             $aRelData = Engine::GetInstance()->_CallModule("{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}ItemsByArray{$sRelPrimaryKey}", array($aEntityKeys[$sRelKey]));
             /**
              * Собираем набор
              */
             foreach ($aEntities as $oEntity) {
                 if (isset($aRelData[$oEntity->_getDataOne($sRelKey)])) {
                     $oEntity->_setData(array($sRelationName => $aRelData[$oEntity->_getDataOne($sRelKey)]));
                 }
             }
         }
     }
     /**
      * Returns assotiative array, indexed by PRIMARY KEY or another field.
      */
     if (in_array('#index-from-primary', $aFilter) || !empty($aFilter['#index-from'])) {
         $aEntities = $this->_setIndexesFromField($aEntities, $aFilter);
     }
     /**
      * Если запрашиваем постраничный список, то возвращаем сам список и общее количество записей
      */
     if (isset($aFilter['#page'])) {
         return array('collection' => $aEntities, 'count' => $this->GetCountItemsByFilter($aFilter, $sEntityFull));
     }
     return $aEntities;
 }
 /**
  * Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля
  * Также производит обработку методов set* и get*
  * Учитывает связи и может возвращать связанные данные
  * @see Engine::_CallModule
  *
  * @param string $sName Имя метода
  * @param array $aArgs Аргументы
  * @return mixed
  */
 public function __call($sName, $aArgs)
 {
     $sType = substr($sName, 0, strpos(func_underscore($sName), '_'));
     if (!strpos($sName, '_') and in_array($sType, array('get', 'set', 'reload'))) {
         $sKey = func_underscore(preg_replace('/' . $sType . '/', '', $sName, 1));
         if ($sType == 'get') {
             if (isset($this->_aData[$sKey])) {
                 return $this->_aData[$sKey];
             } else {
                 $sField = $this->_getField($sKey);
                 if ($sField != $sKey && isset($this->_aData[$sField])) {
                     return $this->_aData[$sField];
                 }
             }
             /**
              * Проверяем на связи
              */
             $aRelations = $this->_getRelations();
             if (array_key_exists($sKey, $aRelations)) {
                 $sEntityRel = $aRelations[$sKey]['rel_entity'];
                 $sRelationType = $aRelations[$sKey]['type'];
                 $sRelationKey = $aRelations[$sKey]['rel_key'];
                 $sRelModuleName = Engine::GetModuleName($sEntityRel);
                 $sRelEntityName = Engine::GetEntityName($sEntityRel);
                 $sRelPluginPrefix = Engine::GetPluginPrefix($sEntityRel);
                 $sRelPrimaryKey = 'id';
                 if ($oRelEntity = Engine::GetEntity($sEntityRel)) {
                     $sRelPrimaryKey = $oRelEntity->_getPrimaryKey();
                 }
                 $iPrimaryKeyValue = $this->_getDataOne($this->_getPrimaryKey());
                 $bUseFilter = array_key_exists(0, $aArgs) && is_array($aArgs[0]);
                 $sCmd = '';
                 $mCmdArgs = array();
                 switch ($sRelationType) {
                     case self::RELATION_TYPE_BELONGS_TO:
                         $sKeyTo = $aRelations[$sKey]['rel_key_to'] ?: $sRelPrimaryKey;
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}By" . func_camelize($sKeyTo);
                         $mCmdArgs = array($this->_getDataOne($sRelationKey));
                         break;
                     case self::RELATION_TYPE_HAS_ONE:
                         $aFilterAdd = $aRelations[$sKey]['filter'];
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}ByFilter";
                         $aFilterAdd = array_merge(array($sRelationKey => $iPrimaryKeyValue), $aFilterAdd);
                         $mCmdArgs = array($aFilterAdd);
                         break;
                     case self::RELATION_TYPE_HAS_MANY:
                         if ($aRelations[$sKey]['key_from']) {
                             $sRelationKeyValue = $this->_getDataOne($aRelations[$sKey]['key_from']);
                         } else {
                             $sRelationKeyValue = $iPrimaryKeyValue;
                         }
                         $aFilterAdd = $aRelations[$sKey]['filter'];
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}ItemsByFilter";
                         $aFilterAdd = array_merge(array($sRelationKey => $sRelationKeyValue), $aFilterAdd);
                         if ($bUseFilter) {
                             $aFilterAdd = array_merge($aFilterAdd, $aArgs[0]);
                         }
                         $mCmdArgs = array($aFilterAdd);
                         break;
                     case self::RELATION_TYPE_MANY_TO_MANY:
                         $sEntityJoin = $aRelations[$sKey]['join_entity'];
                         $sKeyJoin = $aRelations[$sKey]['join_key'];
                         $aFilterAdd = $aRelations[$sKey]['filter'];
                         $sCmd = "{$sRelPluginPrefix}Module{$sRelModuleName}_get{$sRelEntityName}ItemsByJoinEntity";
                         if ($bUseFilter) {
                             $aFilterAdd = array_merge($aFilterAdd, $aArgs[0]);
                         }
                         $mCmdArgs = array($sEntityJoin, $sKeyJoin, $sRelationKey, $iPrimaryKeyValue, $aFilterAdd);
                         break;
                     default:
                         break;
                 }
                 /**
                  * Если связь уже загруженна, то возвращаем результат
                  */
                 if (!$bUseFilter and array_key_exists($sKey, $this->aRelationsData)) {
                     return $this->aRelationsData[$sKey];
                 }
                 // Нужно ли учитывать дополнительный фильтр
                 $res = Engine::GetInstance()->_CallModule($sCmd, $mCmdArgs);
                 // Сохраняем данные только в случае "чистой" выборки
                 if (!$bUseFilter) {
                     $this->aRelationsData[$sKey] = $res;
                 }
                 // Создаём объекты-обёртки для связей MANY_TO_MANY
                 if ($sRelationType == self::RELATION_TYPE_MANY_TO_MANY) {
                     $this->_aManyToManyRelations[$sKey] = new ORMRelationManyToMany($res);
                 }
                 return $res;
             }
             return null;
         } elseif ($sType == 'set' and array_key_exists(0, $aArgs)) {
             if (array_key_exists($sKey, $this->aRelations)) {
                 $this->aRelationsData[$sKey] = $aArgs[0];
             } else {
                 $this->_aData[$this->_getField($sKey)] = $aArgs[0];
             }
             return $this;
         } elseif ($sType == 'reload') {
             if (array_key_exists($sKey, $this->aRelationsData)) {
                 unset($this->aRelationsData[$sKey]);
                 return $this->__call('get' . func_camelize($sKey), $aArgs);
             }
         }
     } else {
         return parent::__call($sName, $aArgs);
     }
 }