function findByKeyword(array $keyword, $orderBy = null, $limit = null, $offset = null) { $keyword = "%{$keyword}%"; $from = $this->_getKeywordDQLFrom(); $where = $this->_getKeywordDQLWhere(); $ob = ''; if (is_array($orderBy)) { $ob = 'ORDER BY '; $first = true; foreach ($orderBy as $prop => $order) { if (!$first) { $ob .= ', '; } $ob .= "{$prop} {$order}"; } } $dql = "SELECT e FROM {$from} WHERE {$where} {$ob}"; $query = App::i()->em->createQuery($dql); if ($limit) { $query->setMaxResults($limit); } if ($offset) { $query->setFirstResult($offset); } $query->setParameter('keyword', $keyword); return $query->getResult(); }
/** * Sets the value of the location property. * * You can set the value of this property using a GeoPoint object or using an array, * * <code> * // example with GeoPoint * $entity->location = new GeoPoint(-45.123, -23.345); * * // example with arrays * $entity->location = [-45.123, -23.345]; * $entity->location = ['x' => -45.123, 'y' => -23.345]; * $entity->location = ['longitude' => -45.123, 'latitude' => -23.345]; * * </code> * * This method sets the value of the property _geoLocation with a PostGIS ST_Geography type. * * @param \MapasCulturais\Types\GeoPoint|array $location */ function setLocation($location) { $x = $y = null; if (!$location instanceof GeoPoint) { if (is_array($location) && key_exists('x', $location) && key_exists('y', $location)) { $x = $location['x']; $y = $location['y']; } elseif (is_array($location) && key_exists('longitude', $location) && key_exists('latitude', $location)) { $x = $location['longitude']; $y = $location['latitude']; } elseif (is_array($location) && count($location) === 2 && is_numeric($location[0]) && is_numeric($location[1])) { $x = $location[0]; $y = $location[1]; } else { throw new \Exception(App::txt('The location must be an instance of \\MapasCulturais\\Types\\GeoPoint or an array with two numeric values')); } $location = new GeoPoint($x, $y); } if (is_numeric($x) && is_numeric($y)) { $rsm = new \Doctrine\ORM\Query\ResultSetMapping(); $sql = "SELECT ST_GeographyFromText('POINT({$location->longitude} {$location->latitude})') AS geo"; $rsm->addScalarResult('geo', 'geo'); $query = App::i()->em->createNativeQuery($sql, $rsm); $this->_geoLocation = $query->getSingleScalarResult(); } $this->location = $location; }
/** * Returns the owner of this TermRelation * @return \MapasCulturais\Entity */ public function getOwner() { if (!$this->_owner && ($this->objectType && $this->objectId)) { $this->_owner = \MapasCulturais\App::i()->repo($this->objectType)->find($this->objectId); } return $this->_owner; }
function testValidations() { $app = App::i(); $type = new MapasCulturais\Definitions\EntityType('MapasCulturais\\Entities\\Agent', 9999, 'test type'); $app->registerEntityType($type); $metas = array('metaRequired' => array('label' => 'Meta Required', 'validations' => array('required' => 'required error message'), 'validValues' => array('Value', 'Loren'), 'invalidValues' => array(null, '')), 'metaEmail' => array('label' => 'Meta Email', 'validations' => array('v::email()' => 'error message'), 'validValues' => array(null, '', '*****@*****.**', '*****@*****.**', '*****@*****.**'), 'invalidValues' => array('test', 'test', 'teste#teste.com', 'alow as@teste.com')), 'metaRequiredEmail' => array('label' => 'Meta Email', 'validations' => array('required' => 'required error message', 'v::email()' => 'error message'), 'validValues' => array('*****@*****.**', '*****@*****.**', '*****@*****.**'), 'invalidValues' => array(null, '', 'test', 'test', 'teste#teste.com', 'alow as@teste.com')), 'metaUrl' => array('label' => 'Meta Url', 'validations' => array('v::url()' => 'error message'), 'validValues' => array(null, '', 'http://www.test.com', 'http://www.testing-tests.com', 'http://www.test.com/', 'https://www.test.com/', 'http://www.test.com/ok', 'https://testing.com/ok.test', 'http://test.com/ok.php', 'http://a.very.long.domain.name.com/ok.jpg?with=get%20params', 'https://www.test.com/ok'), 'invalidValues' => array('htts:///222 asd.com', 'asdasd', 'www.test.com')), 'metaRequiredUrl' => array('label' => 'Meta Url', 'validations' => array('required' => 'required error message', 'v::url()' => 'error message'), 'validValues' => array('http://www.test.com', 'http://www.testing-tests.com', 'http://www.test.com/', 'https://www.test.com/', 'http://www.test.com/ok', 'https://testing.com/ok.test', 'http://test.com/ok.php', 'http://a.very.long.domain.name.com/ok.jpg?with=get%20params', 'https://www.test.com/ok'), 'invalidValues' => array(null, '', 'htts:///222 asd.com', 'asdasd', 'www.test.com')), 'metaContact' => array('label' => 'Meta Contact', 'validations' => array('required' => 'required error message', 'v::oneOf(v::email(), v::brPhone())' => 'error message'), 'validValues' => array('*****@*****.**', '*****@*****.**', '*****@*****.**', '(11) 9876-5432', '(11) 3456-1234', '(11)34561234', '(11) 93456-1234'), 'invalidValues' => array(null, '', 'test@', 'test', 'teste#teste.com', 'alow as@teste.com', '(11)123', '(1) 123123123123-123'))); foreach ($metas as $meta_key => $config) { $definition = new MapasCulturais\Definitions\Metadata($meta_key, $config); $app->unregisterEntityMetadata('MapasCulturais\\Entities\\Agent'); $app->registerMetadata($definition, 'MapasCulturais\\Entities\\Agent', $type->id); $agent = new Agent(); $agent->name = 'Teste'; $agent->type = $type; $agent->terms['area'][] = 'Cinema'; for ($i = 1; $i <= 2; $i++) { foreach ($config['validValues'] as $val) { $agent->{$meta_key} = $val; $errors = $agent->getValidationErrors(); $this->assertArrayNotHasKey($meta_key, $errors, print_r(array('type' => "assertArrayNotHasKey", 'KEY' => $meta_key, 'VALID VALUE' => $val, 'errors' => $errors), true)); } foreach ($config['invalidValues'] as $val) { $agent->{$meta_key} = $val; $errors = $agent->getValidationErrors(); $this->assertArrayHasKey($meta_key, $errors, print_r(array('type' => "assertArrayNotHasKey", 'KEY' => $meta_key, 'INVALID VALUE' => $val, 'errors' => $errors), true)); } } } }
protected function _init() { $app = App::i(); $token = $this->_config['token']; try { $jwt_data = \JWT::decode($token); if (isset($jwt_data->pk)) { $pk = $jwt_data->pk; $userapp = $app->repo('UserApp')->find($pk); // pegar da tabela de apps if (!$userapp) { http_response_code(401); die; } \JWT::decode($token, $userapp->privateKey, ['HS512', 'HS256', 'HS1']); $user = $userapp->user; $this->__user = $user; return true; } } catch (\Exception $e) { http_response_code(401); } http_response_code(401); die; }
/** * Sets the Longitude of the point. * * @param float $val Longitude * * @throws \Exception if the value is greater than 180 or less then -180 */ public function setLongitude($val) { if ($val > 180 || $val < -180) { throw new \Exception(App::txt('Longitude must be a float between 180 and -180')); } $this->longitude = $val; }
function API_findByEvents() { $eventController = App::i()->controller('event'); $query_data = $this->getData; $date_from = key_exists('@from', $query_data) ? $query_data['@from'] : date("Y-m-d"); $date_to = key_exists('@to', $query_data) ? $query_data['@to'] : $date_from; unset($query_data['@from'], $query_data['@to']); $event_data = array('@select' => 'id') + $query_data; unset($event_data['@count']); $events = $eventController->apiQuery($event_data); $event_ids = array_map(function ($e) { return $e['id']; }, $events); $spaces = $this->repository->findByEventsAndDateInterval($event_ids, $date_from, $date_to); $space_ids = array_map(function ($e) { return $e->id; }, $spaces); if ($space_ids) { $space_data = array('id' => 'IN(' . implode(',', $space_ids) . ')'); foreach ($query_data as $key => $val) { if ($key[0] === '@' || $key == '_geoLocation') { $space_data[$key] = $val; } } unset($space_data['@keyword']); $this->apiResponse($this->apiQuery($space_data)); } else { $this->apiResponse(key_exists('@count', $query_data) ? 0 : array()); } }
function API_list() { $app = App::i(); $result = []; if (isset($this->data['includeData'])) { $rsm = new \Doctrine\ORM\Query\ResultSetMapping(); $rsm->addScalarResult('type', 'type'); $rsm->addScalarResult('name', 'name'); $strNativeQuery = "SELECT type, name FROM geo_division"; $query = $app->getEm()->createNativeQuery($strNativeQuery, $rsm); $divisions = $query->getScalarResult(); } foreach ($app->getRegisteredGeoDivisions() as $geoDivision) { $r = clone $geoDivision; if (isset($this->data['includeData'])) { foreach ($divisions as $index => $division) { if (!isset($r->data)) { $r->data = []; } if ($r->key === $division['type']) { $r->data[] = $division['name']; } } } $result[] = $r; } $this->json($result); }
public function register() { parent::register(); $app = App::i(); $metadata = ['MapasCulturais\\Entities\\Event' => ['num_sniic' => ['label' => 'Nº SNIIC:', 'private' => false]], 'MapasCulturais\\Entities\\Project' => ['num_sniic' => ['label' => 'Nº SNIIC:', 'private' => false]], 'MapasCulturais\\Entities\\Space' => ['num_sniic' => ['label' => 'Nº SNIIC:', 'private' => false], 'cnpj' => ['label' => 'CNPJ', 'private' => false, 'validations' => ['v::cnpj()' => 'O CNPJ informado é inválido']], 'esfera' => ['label' => 'Esfera', 'type' => 'select', 'options' => ['Pública', 'Privada']], 'esfera_tipo' => ['label' => 'Tipo de esfera', 'type' => 'select', 'options' => ['Federal', 'Estadual', 'Distrital', 'Municipal', 'Associação', 'Empresa', 'Fundação', 'Particular', 'Religiosa', 'Mista', 'Entidade Sindical', 'Outra']], 'certificado' => ['label' => 'Títulos e Certificados', 'type' => 'select', 'options' => ['ONG' => 'Organização não Governamental (ONG)', 'OSCIP' => 'Organização da Sociedade Civil de Interesse Público (OSCIP)', 'OS' => 'Organização Social (OS)', 'CEBAS' => 'Certificado de Entidade Beneficente de Assistência Social (CEBAS)', 'UPF' => 'Certificado de Utilidade Pública Federal (UPF)', 'UPE' => 'Certificado de Utilidade Pública Estadual (UPE)', 'UPM' => 'Certificado de Utilidade Pública Municipal (UPM)']]], 'MapasCulturais\\Entities\\Agent' => ['num_sniic' => ['label' => 'Nº SNIIC:', 'private' => false], 'tipologia_nivel1' => ['label' => 'Tipologia Nível 1', 'private' => false], 'tipologia_nivel2' => ['label' => 'Tipologia Nível 2', 'private' => false], 'tipologia_nivel3' => ['label' => 'Tipologia Nível 3', 'private' => false, 'validations' => ['required' => 'A tipologia deve ser informada.']]]]; $prefix = $this->getMetadataPrefix(); foreach ($this->_getAgentMetadata() as $key => $cfg) { $key = $prefix . $key; $metadata['MapasCulturais\\Entities\\Agent'][$key] = $cfg; } foreach ($this->_getSpaceMetadata() as $key => $cfg) { $key = $prefix . $key; $metadata['MapasCulturais\\Entities\\Space'][$key] = $cfg; } foreach ($this->_getEventMetadata() as $key => $cfg) { $key = $prefix . $key; $metadata['MapasCulturais\\Entities\\Event'][$key] = $cfg; } foreach ($this->_getProjectMetadata() as $key => $cfg) { $key = $prefix . $key; $metadata['MapasCulturais\\Entities\\Project'][$key] = $cfg; } foreach ($metadata as $entity_class => $metas) { foreach ($metas as $key => $cfg) { $def = new \MapasCulturais\Definitions\Metadata($key, $cfg); $app->registerMetadata($def, $entity_class); } } }
public function __construct() { $this->_publicKey = self::getToken(32); $this->_privateKey = self::getToken(64); $this->user = App::i()->user; parent::__construct(); }
/** * * @param \MapasCulturais\Entities\User $user * @param mixed $status = all all|sent|Entities\Registration::STATUS_*|[Entities\Registration::STATUS_*, Entities\Registration::STATUS_*] * @return \MapasCulturais\Entities\Registration[] */ function findByUser($user, $status = 'all') { if ($user->is('guest')) { return []; } $status_where = ""; if ($status === 'all') { $status = false; } else { if ($status === 'sent') { $status = false; $status_where = "r.status > 0 AND"; } else { if (is_int($status)) { $status_where = "r.status = :status AND"; } else { if (is_array($status)) { $status_where = "r.status IN (:status) AND"; } } } } $dql = "\n SELECT\n r\n FROM\n MapasCulturais\\Entities\\Registration r\n LEFT JOIN MapasCulturais\\Entities\\RegistrationAgentRelation rar WITH rar.owner = r\n WHERE\n {$status_where}\n (\n r.owner IN (:agents) OR\n rar.agent IN (:agents)\n )"; $q = $this->_em->createQuery($dql); $q->setParameter('agents', $user->agents ? $user->agents->toArray() : [-1]); if ($status !== false) { $q->setParameter('status', $status); } \MapasCulturais\App::i()->log->debug($dql); return $q->getResult(); }
public function createByAuthResponse($response) { $this->_isCreating = true; $app = \MapasCulturais\App::i(); // cria o usuário $user = new Entities\User(); $user->authProvider = $response['auth']['provider']; $user->authUid = $response['auth']['uid']; $user->email = $response['auth']['info']['email']; $this->_em->persist($user); // cria um agente do tipo user profile para o usuário criado acima $agent = new Entities\Agent($user); $agent->isUserProfile = true; if (isset($response['auth']['info']['name'])) { $agent->name = $response['auth']['info']['name']; } elseif (isset($response['auth']['info']['first_name']) && isset($response['auth']['info']['last_name'])) { $agent->name = $response['auth']['info']['first_name'] . ' ' . $response['auth']['info']['last_name']; } else { $agent->name = 'Sem nome'; } $app->em->persist($agent); $app->em->flush(); $this->_isCreating = false; return $user; }
function setParent($parent) { //Added this case to remove parent from the entity if ($parent === null) { $this->parent = null; return; } elseif (!is_object($parent)) { return; } $parent->checkPermission('createChild'); $error1 = App::txt('O pai não pode ser o filho.'); $error2 = App::txt('O pai deve ser do mesmo tipo que o filho.'); if (!key_exists('parent', $this->_validationErrors)) { $this->_validationErrors['parent'] = array(); } if ($parent && $parent->id === $this->id) { $this->_validationErrors['parent'][] = $error1; } elseif (key_exists('parent', $this->_validationErrors) && in_array($error1, $this->_validationErrors['parent'])) { $key = array_search($error, $this->_validationErrors['parent']); unset($this->_validationErrors['parent'][$key]); } if ($parent && $parent->className !== $this->className) { $this->_validationErrors['parent'][] = $error2; } elseif (key_exists('parent', $this->_validationErrors) && in_array($error2, $this->_validationErrors['parent'])) { $key = array_search($error, $this->_validationErrors['parent']); unset($this->_validationErrors['parent'][$key]); } if (!$this->_validationErrors['parent']) { unset($this->_validationErrors['parent']); } $this->parent = $parent; }
function GET_unpublish() { $this->requireAuthentication(); $app = App::i(); if (!key_exists('id', $this->urlData)) { $app->pass(); } $entity = $this->requestedEntity; $urls = [$entity->singleUrl, $entity->editUrl]; if (!$entity) { $app->pass(); } $entity_class = $entity->getClassName(); $entity->status = $entity_class::STATUS_DRAFT; $entity->save(true); if ($this->isAjax()) { $this->json($entity); } else { //e redireciona de volta para o referer if (in_array($app->request()->getReferer(), $urls)) { $app->redirect($app->createUrl('panel')); } else { $app->redirect($app->request()->getReferer()); } } }
function _init() { parent::_init(); $app = App::i(); $app->hook('view.render(<<*>>):before', function () use($app) { $this->jsObject['assets']['logo-prefeitura'] = $this->asset('img/logo-prefeitura.png', false); }); }
function getGroup() { if ($this->group == 'registration') { return App::txt("project registration"); } else { return $this->group; } }
public function _getAuthenticatedUser() { if (file_exists($this->filename)) { $id = file_get_contents($this->filename); $this->_user = \MapasCulturais\App::i()->repo('User')->find($id); } return $this->_user; }
function _init() { parent::_init(); $app = App::i(); $app->hook('view.render(<<*>>):before', function () use($app) { $this->_publishAssets(); }); }
/** * * @return EventOccurrence */ function getEventOccurrence() { if (isset($this->metadata['event_occurrence_id'])) { return App::i()->repo('EventOccurrence')->find($this->metadata['event_occurrence_id']); } else { return null; } }
/** * {@inheritdoc} */ public function stopQuery() { $app = App::i(); $time_end = microtime(true); $execution_time = number_format($time_end - $this->time_start, 4); $this->total_queries_time += $execution_time; $app->log->debug("\nQUERY Nº {$this->counter} EXECUTED IN {$execution_time} seconds (TOTAL QUERIES TIME: {$this->total_queries_time} seconds)"); $app->log->debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<< SQL Nº {$this->counter}\n"); }
function getOptionLabel($key) { $cfg = \MapasCulturais\App::i()->config['registration.agentRelationsOptions']; if (!$key || !isset($cfg[$key])) { return ''; } else { return $cfg[$key]; } }
protected function _init() { parent::_init(); $app = App::i(); $app->hook("controller(site).render(page)", function () use($app) { $page = $this->data[0]; $app->view->bodyClasses[] = "page-" . $page; }); }
function unpublish($flush = false) { $this->checkPermission('publish'); $app = App::i(); $app->disableAccessControl(); $this->status = self::STATUS_DRAFT; $this->save($flush); $app->enableAccessControl(); }
function GET_user() { $_user = App::i()->repo('User')->find($this->getUrlData()['id']); if ($_user) { $this->json($_user); } else { $this->json(['erro' => "usuario nao encontrado"], 400); } }
function GET_login() { $app = App::i(); if (isset($this->getData['redirectTo'])) { $app->auth->requireAuthentication($this->getData['redirectTo']); } else { $app->auth->requireAuthentication(); } }
public function addDocumentMetas() { parent::addDocumentMetas(); $app = App::i(); foreach ($this->documentMeta as $key => $meta) { if (isset($meta['property']) && ($meta['property'] === 'og:image' || $meta['property'] === 'og:image:url')) { $this->documentMeta[$key] = array('property' => $meta['property'], 'content' => $app->view->asset('img/share-rs.png', false)); } } }
protected function getContentType() { $response = \MapasCulturais\App::i()->response(); //$response['Content-Encoding'] = 'UTF-8'; $response['Content-Type'] = 'application/force-download'; $response['Content-Disposition'] = 'attachment; filename=mapas-culturais-dados-exportados.xls'; $response['Pragma'] = 'no-cache'; return 'application/vnd.ms-excel; charset=UTF-8'; //return 'text/html'; }
function updateAddressData($sourceSpace, $destinySpace) { \MapasCulturais\App::i()->log->debug('--- UPDATING SPACE: ' . $destinySpace); $destinySpace->endereco = $sourceSpace->endereco; $destinySpace->location = $sourceSpace->location; $destinySpace->sp_regiao = $sourceSpace->sp_regiao; $destinySpace->sp_subprefeitura = $sourceSpace->sp_subprefeitura; $destinySpace->sp_distrito = $sourceSpace->sp_distrito; \MapasCulturais\App::i()->log->debug('--- SPACE LOCATION ' . $destinySpace->location); }
/** * Returns the metalists of this entity. * * If a group name is informed returns only the metalists of the given group, otherwise returns all metalists * of this entity grouped by the group name. * * <code> * // Example of return when no group is informed * array( * 'links' => array($link1, $link2), * 'videos' => array($video1, $video2, $video3) * ) * </code> * */ function getMetaLists($group = null) { $app = App::i(); if ($group) { $result = $app->repo('MetaList')->findByGroup($this, $group); } else { $result = $app->repo('MetaList')->findByOwnerGroupedByGroup($this); } return $result; }
function GET_entrada() { $this->requireAuthentication(); $app = App::i(); if ($app->user->redeCulturaViva) { $app->redirect($app->createUrl('cadastro', 'index')); } else { $this->render('entrada'); } }