/** * Executes a commit after each action. This prevents having too many * manuall commit * * @param string $name The command name * @param KCommandContext $context The command context * * @return boolean Can return both true or false. */ public function execute($name, KCommandContext $context) { $parts = explode('.', $name); $result = $context->result; //after an action save if ($parts[0] == 'after' && $parts[1] != 'cancel') { //if there are not any commitable //skip if (count($this->getRepository()->getSpace()->getCommitables()) == 0) { return; } //do a commit $result = $this->commit(); $type = $result === false ? 'error' : 'success'; $message = $this->_makeStatusMessage($context->action, $type); if ($message) { $this->setMessage($message, $type, true); } if ($result === false) { if ($this->isIdentifiable() && $this->getItem()) { if ($this->getItem()->getErrors()->count()) { throw new AnErrorException($this->getItem()->getErrors(), KHttpResponse::BAD_REQUEST); } } else { $errors = AnHelperArray::getValues($this->getCommitErrors()); throw new AnErrorException($errors, KHttpResponse::BAD_REQUEST); } } } }
/** * Initializes the default configuration for the object * * Called from {@link __construct()} as a first step of object instantiation. * * @param KConfig $config An optional KConfig object with configuration options. * * @return void */ protected function _initialize(KConfig $config) { $config->append(array('attributes' => array('administratingIds' => array('type' => 'set', 'default' => 'set'), 'userId' => array('column' => 'person_userid', 'key' => true, 'type' => 'integer'), 'username' => array('column' => 'person_username', 'key' => true, 'format' => 'username'), 'userType' => array('column' => 'person_usertype', 'write' => 'protected'), 'email' => array('column' => 'person_useremail', 'key' => true, 'format' => 'email'), 'givenName' => array('column' => 'person_given_name', 'format' => 'string'), 'familyName' => array('column' => 'person_family_name', 'format' => 'string'), 'lastVisitDate' => array('type' => 'date', 'column' => 'person_lastvisitdate'), 'language' => array('column' => 'person_language'), 'timezone' => array('column' => 'person_time_zone'), 'gender' => array('column' => 'actor_gender')), 'aliases' => array('registrationDate' => 'creationTime', 'aboutMe' => 'description'), 'behaviors' => to_hash(array('describable' => array('searchable_properties' => array('username')), 'administrator', 'notifiable', 'leadable')))); $config->behaviors->append(array('followable' => array('subscribe_after_follow' => false))); parent::_initialize($config); AnHelperArray::unsetValues($config->behaviors, array('administrable')); }
/** * Removes a photo or list of photos from the set * * @return null * @param $photo a ComPhotosDomainEntityPhoto object */ public function removePhoto($photo) { $photos = AnHelperArray::getIterator($photo); foreach ($photos as $photo) { if ($edge = $this->photos->find($photo)) { $edge->delete(); } } }
/** * Initializes the default configuration for the object * * Called from {@link __construct()} as a first step of object instantiation. * * @param KConfig $config An optional KConfig object with configuration options. * * @return void */ protected function _initialize(KConfig $config) { $config->append(array('behaviors' => array('validatable', 'com://site/mailer.controller.behavior.mailer'))); parent::_initialize($config); AnHelperArray::unsetValues($config->behaviors, 'ownable'); //if it's a person view , set the default id to person if ($config->request->view == 'person') { $config->append(array('request' => array('id' => get_viewer()->id))); } }
/** * add locations to a locatable node * * @param entity set of location entities */ public function addLocation($locations) { $newItems = AnHelperArray::getIterator($locations); foreach ($newItems as $item) { if (!$this->locations->find($item)) { $this->locations->insert($item); } } return $item; }
/** * Initializes the default configuration for the object. * * Called from {@link __construct()} as a first step of object instantiation. * * @param KConfig $config An optional KConfig object with configuration options. */ protected function _initialize(KConfig $config) { $config->append(array('behaviors' => array('validatable', 'com://site/mailer.controller.behavior.mailer'), 'request' => array('reset_password' => 0))); parent::_initialize($config); AnHelperArray::unsetValues($config->behaviors, 'ownable'); $this->_allowed_user_types = array(ComPeopleDomainEntityPerson::USERTYPE_ADMINISTRATOR, ComPeopleDomainEntityPerson::USERTYPE_REGISTERED); $viewer = get_viewer(); if ($viewer->superadmin()) { $this->_allowed_user_types[] = ComPeopleDomainEntityPerson::USERTYPE_SUPER_ADMINISTRATOR; } }
/** * Browse Service * @todo move all queries to the query class * * @param KCommandContext $context */ protected function _actionBrowse(KCommandContext $context) { if ($this->locatable) { if (in_array($this->getView()->getLayout(), array('selector', 'list_selector'))) { $keyword = $this->q ? $this->getService('anahita:filter.term')->sanitize($this->q) : ''; $query = $this->getService('com://site/locations.domain.query.selector')->keyword($keyword)->excludeIds(AnHelperArray::collect($this->locatable->locations, 'id'))->locatable($this->locatable)->nearbyLatitude($this->nearby_latitude)->nearbyLongitude($this->nearby_longitude); } else { $query = $this->locatable->locations->order('name'); } $query->limit($this->limit, $this->start); return $this->getState()->setList($query->toEntityset())->getList(); } return parent::_actionBrowse($context); }
/** * Set the owner of the object. If multiple owners are passed then the first owner is the * primary owner and the rest just share the object with the owner * * @param ComActorsDomainEntityActor $owner The owner object * * @return ComBaseDomainEntityNode Return the ownable object */ public function setOwner($owner) { //multiple owners are passed $owner = KConfig::unbox($owner); if (is_array($owner)) { deprecated('array as owner'); } if (is_array($owner) && $this->isSharable()) { $owners = AnHelperArray::unique($owner); //remove the first owner as the primary owner $owner = array_shift($owners); //create an edge with the story for each secondary owner //$this->addOwner($owners); } $this->_mixer->set('owner', $owner); return $this; }
/** * Parse the segments of a URL. * * @param array The segments of the URL to parse. * @return array The URL attributes to be used by the application. */ public function parse(&$segments) { $path = implode('/', $segments); $vars = array(); $matches = array(); if (preg_match('/(\\d+)-([^\\/]+)/', $path, $matches)) { $vars['alias'] = $matches[2]; $path = str_replace($matches[0], $matches[1], $path); $segments = array_filter(explode('/', $path)); } $last = AnHelperArray::getValueAtIndex($segments, AnHelperArray::LAST_INDEX); if (preg_match('/@\\w+/', $last)) { $vars['oid'] = str_replace('@', '', array_pop($segments)); } $vars = array_merge($vars, parent::parse($segments)); if (isset($vars['get']) && $vars['get'] == 'graph') { $vars['type'] = count($segments) ? array_shift($segments) : 'followers'; } return $vars; }
/** * Browse Service * @todo move all queries to the query class * * @param KCommandContext $context */ protected function _actionBrowse(KCommandContext $context) { // @todo move these queries to query classes $keyword = $this->q ? $this->getService('anahita:filter.term')->sanitize($this->q) : ''; if ($this->locatable) { if (in_array($this->getView()->getLayout(), array('selector', 'list_selector'))) { $query = $this->getService('repos:locations.location')->getQuery(); $excludeIds = AnHelperArray::collect($this->locatable->locations, 'id'); if (count($excludeIds)) { $query->where('location.id', 'NOT IN', $excludeIds); } if ($keyword != '') { $query->keyword = $keyword; } if ($this->nearby_latitude && $this->nearby_longitude) { $earth_radius = 6371000; $lat = (double) $this->nearby_latitude; $lng = (double) $this->nearby_longitude; $calc_distance = 'CEIL((ACOS(SIN(' . $lat . '*PI()/180) * SIN(location.geo_latitude*PI()/180) + COS(' . $lat . '*PI()/180) * COS(location.geo_latitude*PI()/180) * COS((' . $lng . '*PI()/180) - (location.geo_longitude*PI()/180) )) *' . $earth_radius . '))'; $query->select(array($calc_distance . ' AS `distance`')); $query->having('distance < 5000'); $query->order('distance'); } } else { $query = $this->locatable->locations; $query->order('name'); } } elseif ($keyword != '') { $query = $this->getService('repos:locations.location')->getQuery(); $query->keyword = $keyword; } else { $entities = parent::_actionBrowse($context); $query = $entities->getQuery(); $edgeType = 'ComTagsDomainEntityTag,ComLocationsDomainEntityTag,com:locations.domain.entity.tag'; $query->where('edge.type', '=', $edgeType)->group('location.id'); } $query->limit($this->limit, $this->offset); //print str_replace('#_', 'jos', $query); return $this->getState()->setList($query->toEntityset())->getList(); }
/** * Initializes the options for the object. * * Called from {@link __construct()} as a first step of object instantiation. * * @param object An optional KConfig object with configuration options. */ protected function _initialize(KConfig $config) { $config->append(array('behaviors' => array('parentable', 'votable', 'com://site/hashtags.controller.behavior.hashtagable', 'com://site/people.controller.behavior.mentionable'))); AnHelperArray::unsetValues($config->behaviors, 'verifiable'); parent::_initialize($config); }
/** * Initializes the default configuration for the object * * Called from {@link __construct()} as a first step of object instantiation. * * @param KConfig $config An optional KConfig object with configuration options. * * @return void */ protected function _initialize(KConfig $config) { $config->append(array('behaviors' => array('parentable' => array('parent' => 'page')), 'attributes' => array('excerpt' => 'excerpt', 'revisionNum' => 'ordering'), 'aliases' => array('title' => 'name'))); parent::_initialize($config); AnHelperArray::unsetValues($config->behaviors, array('commentable', 'subscribable', 'hashtagable')); }
/** * Return a day selection from 1 to 31. * * @param array $options * * @return LibBaseTemplateTag; */ public function day($options = array()) { $options = new KConfig($options); $options->append(array('selected' => null, 'prompt' => true)); $days = array_combine(range(1, 31), range(1, 31)); $selected = $options->selected; unset($options->selected); $prompt = $options->prompt; unset($options->prompt); if ($prompt) { $array = array(JText::_('LIB-AN-SELECTOR-SELECT-DAY')); $days = AnHelperArray::merge($array, $days); } return $this->_html->select($options->name, array('options' => $days, 'selected' => $selected), KConfig::unbox($options)); }
/** * Set a list of notifications subscribers * * @param array $subscribers An array of Ids or person objects * * @return void */ public function setSubscribers($subscribers) { //flatten the array $subscribers = AnHelperArray::getValues(KConfig::unbox($subscribers)); $ids = array(); foreach ($subscribers as $subscriber) { if (is($subscriber, 'AnDomainEntityAbstract')) { $ids[] = $subscriber->id; } else { $ids[] = $subscriber; } } $ids = array_unique($ids); if (count($ids) > 0) { $this->set('subscriberIds', AnDomainAttribute::getInstance('set')->setData($ids)); } else { $this->delete(); } return $this; }
/** * Finds an entity within the entityset the matches the criteria. If $set * is passed then it finds a set. * * @param array|string $needle * @param bool $set * * @return AnDomainEntityAbstract|null */ public function find($needle, $set = false) { if ($needle instanceof KObjectHandlable) { return parent::find($needle); } $entities = array(); foreach ($this as $entity) { foreach ($needle as $key => $value) { $v = AnHelperArray::getValue($entity, $key); if (is($value, 'AnDomainEntityAbstract') || is($value, 'AnDomainEntityProxy')) { $is_equal = $value->eql($v); } else { $is_equal = $value == $v; } if (!$is_equal) { break; } } if ($is_equal) { if ($set) { $entities[] = $entity; } else { return $entity; } } } if (!$set) { return; } return new AnDomainEntityset(new KConfig(array('data' => $entities, 'repository' => $this->_repository))); }
/** * Send a set of notifications * * @param ComNotificationsDomainEntityNotification $notification Notification * * @return void */ public function sendNotification($notification) { $people = $this->getService('repos://site/actors.actor')->getQuery(true)->id($notification->subscriberIds->toArray())->fetchSet(); $settings = $this->getService('repos://site/notifications.setting')->getQuery(true, array('actor.id' => $notification->target->id))->fetchSet(); $settings = AnHelperArray::indexBy($settings, 'person.id'); $mails = $this->_renderMails(array('notification' => $notification, 'people' => $people, 'settings' => $settings)); $debug = $this->getBehavior('mailer')->getTestOptions()->enabled; if ($debug) { $recipients = array(); foreach ($mails as $i => $mail) { $recipients[] = $mail['to']; if ($i < 3) { $body = array(); $body[] = 'Subject : ' . $mail['subject']; $body[] = $mail['body']; $body = implode('<br />', $body); $bodies[] = $body; } } $bodies[] = 'Sending out ' . count($mails) . ' notification mail(s)'; $bodies[] = '<br /><br />' . implode('<br />', $recipients); $mails = array(array('subject' => $notification->name, 'body' => implode('<hr />', $bodies))); } foreach ($mails as $mail) { $this->mail($mail); } }
/** * Initializes the options for the object * * Called from {@link __construct()} as a first step of object instantiation. * * @param object An optional KConfig object with configuration options. * @return void */ protected function _initialize(KConfig $config) { $config->append(array('list_item_view' => KInflector::singularize($this->getIdentifier()->package))); parent::_initialize($config); $config->template_paths = AnHelperArray::insert($config->template_paths, dirname(__FILE__) . '/html', 1); }
/** * Get the proxied entity. Since there could many entities proxied. The getObject method will try to * load all the proxied entities of the same type in order to reduce the number of calls * to the storage later on. * * @return AnDomainEntityAbstract */ public function getObject() { //security check if (!isset($this->_object)) { $condition = array($this->_property => $this->_value); $repository = AnDomain::getRepository($this->getIdentifier()); //check if an entity exiting in the repository with $condition if ($data = $repository->find($condition, false)) { $this->_object = $data; return $this->_object; } //now time to fetch the object from the database //but lets grab all the similar entities all together $handle = $this->getIdentifier() . $this->_property; $values = isset(self::$_values[$handle]) ? self::$_values[$handle] : array(); if (empty($values)) { return; } $values = AnHelperArray::unique($values); $query = $repository->getQuery(); AnDomainQueryHelper::applyFilters($query, $this->_relationship->getQueryFilters()); $query->where(array($this->_property => $values)); $entities = $repository->fetchSet($query); //the object must have been fetched with the set //in the previous line //if the object is still not fetched, then the object //doesn't exists in the databse $this->_object = $repository->find($condition, false); if (!$this->_object) { //lets cache the null result to prevent re-fetching //the same result $query = $repository->getQuery()->where($condition)->limit(1); if ($repository->hasBehavior('cachable')) { $repository->emptyCache($query); } $this->_object = false; //if it's a required one-to-one relationship //then instantaite a new entity if the entity doesn't exists if ($this->_relationship->isOneToOne()) { if ($this->_relationship->isRequired()) { $this->_object = $repository->getEntity(array('data' => array($this->_property => $this->_value))); } } } unset(self::$_values[$handle]); } return $this->_object; }
/** * Insert an entity to the aggregation. If multiple target is passed then * add the all of them to the collection. It prevents adding the same * entity into the its existing collection. * * @param AnDomainEntityAbstract|array $target * @param array $config * * @return AnDomainEntityAbstract */ public function insert($target, $config = array()) { if (AnHelperArray::isIterable($target)) { $targets = AnHelperArray::unique($target); $relations = new AnObjectSet(); foreach ($target as $target) { $relations->insert($this->insert($target, $config)); } return $relations; } $data = array($this->_property => $this->_root, $this->_target_property => $target); //shouldn't be able to add the same entity into the same collection $relation = $this->_child->findOrAddNew($data, $config); return $relation; }
/** * Loads all the necessary objects after each collection fetch. * * @param AnDomainEntityset $stories */ protected function _preloadData($stories) { $node_ids = array(); $comment_ids = array(); foreach ($stories as $story) { $columns = $story->getRowData(); $node_ids = array_merge($node_ids, $story->getIds('owner'), $story->getIds('subject'), $story->getIds('target'), $story->getIds('object')); $comment_ids = array_merge($comment_ids, $story->getIds('comment')); } $node_ids = array_unique($node_ids); $query = $this->getService('repos://site/base.comment')->getQuery()->where('parent.id', 'IN', $node_ids); $author_ids = $query->fetchValues('author.id'); $node_ids = array_unique(array_merge($node_ids, $author_ids, $comment_ids)); //we don't any behavior messes around with the fetched stories $query = $this->getService('repos://site/base.node')->getQuery()->id($node_ids)->disableChain(); $query->columns('*'); $nodes = $query->fetchSet(); $nodes = AnHelperArray::indexBy($nodes, 'id'); $this->_loaded_nodes = $nodes; }