/** * Command handler * * Only handles before.action commands to check ACL rules. * * @param string The command name * @param object The command context * @return boolean Can return both true or false. * @throws KControllerException */ public function execute($name, KCommandContext $context) { $parts = explode('.', $name); if ($parts[0] == 'before') { $action = $parts[1]; //Check if the action exists if (!in_array($action, $context->caller->getActions())) { $context->setError(new KControllerException('Action ' . ucfirst($action) . ' Not Implemented', KHttpResponse::NOT_IMPLEMENTED)); $context->header = array('Allow' => $context->caller->execute('options', $context)); return false; } //Check if the action can be executed $method = 'can' . ucfirst($action); if (method_exists($this, $method)) { if ($this->{$method}() === false) { if ($context->action != 'options') { $context->setError(new KControllerException('Action ' . ucfirst($action) . ' Not Allowed', KHttpResponse::METHOD_NOT_ALLOWED)); $context->header = array('Allow' => $context->caller->execute('options', $context)); } return false; } } } return true; }
/** * Browse Action. * * @param KCommandContext $context Context parameter * * @return AnDomainEntitysetDefault */ protected function _actionBrowse(KCommandContext $context) { $context->append(array('query' => $this->getRepository()->getQuery())); $query = $context->query; if ($this->q) { $query->keyword($this->getService('anahita:filter.term')->sanitize($this->q)); } if ($this->ids) { $ids = KConfig::unbox($this->ids); $query->id($ids); } else { $query->limit($this->limit, $this->start); } $entities = $query->toEntitySet(); if ($this->isOwnable() && $this->actor) { $this->_state->append(array('filter' => 'following')); if ($this->filter == 'administering' && $this->getRepository()->hasBehavior('administrable')) { $entities->where('administrators.id', 'IN', array($this->actor->id)); } elseif ($this->actor->isFollowable()) { $entities->where('followers.id', 'IN', array($this->actor->id)); } } $entities->order('created_on', 'desc'); return $this->setList($entities)->getList(); }
public function _actionGet(KCommandContext $context) { $data = array('url' => $this->_request->url, 'content-length' => false); if (!function_exists('curl_init')) { $context->setError(new KControllerException('Curl library does not exist', KHttpResponse::SERVICE_UNAVAILABLE)); return; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $data['url']); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 20); //CURLOPT_NOBODY changes the request from GET to HEAD curl_setopt($ch, CURLOPT_NOBODY, true); $response = curl_exec($ch); if (curl_errno($ch)) { $context->setError(new KControllerException('Curl Error: ' . curl_error($ch), KHttpResponse::SERVICE_UNAVAILABLE)); return; } $info = curl_getinfo($ch); if (isset($info['http_code']) && $info['http_code'] != 200) { $context->setError(new KControllerException($data['url'] . ' Not Found', $info['http_code'])); } if (isset($info['download_content_length'])) { $data['content-length'] = $info['download_content_length']; } curl_close($ch); return json_encode($data); }
/** * Halts the delete if the category has documents attached to it. * * Also makes sure subcategories are deleted correctly when both * they and their parents are in the rowset to be deleted. * * @param KCommandContext $context */ public function beforeDelete(KCommandContext $context) { $data = $this->getModel()->getList(); $documents = $data->getDocumentMap(); if ($count = count($documents)) { $translator = $this->getService('translator')->getTranslator($this->getIdentifier()); $message = $translator->choose(array('This category or its children has a document attached. You first need to delete or move it before deleting this category.', 'This category or its children has %count% documents attached. You first need to delete or move them before deleting this category.'), $count, array('%count%' => $count)); $context->setError(new KControllerException($message)); return false; } /* * This removes the child categories from the rowset since they will be deleted by their parent. * If we don't do this, rowset gets confused when it tries to delete a non-existant row. */ if ($data instanceof KDatabaseRowsetInterface) { $to_be_deleted = array(); // PHP gets confused if you extract a row and then continue iterating on the rowset $iterator = clone $data; foreach ($iterator as $row) { if (in_array($row->id, $to_be_deleted)) { $data->extract($row); } $to_be_deleted += $row->getDescendants()->getColumn('id'); } } }
protected function _actionPurge(KCommandContext $context) { if (!$this->getModel()->getTable()->getDatabase()->execute($this->getModel()->getPurgeQuery())) { $context->setError(new KControllerException('Delete Action Failed', KHttpResponse::INTERNAL_SERVER_ERROR)); } else { $context->status = KHttpResponse::NO_CONTENT; } }
protected function _actionRead(KCommandContext $context) { $name = ucfirst($this->getView()->getName()); if (!$this->getModel()->getState()->isUnique()) { $context->setError(new KControllerException($name . ' Not Found', KHttpResponse::NOT_FOUND)); } return parent::_actionRead($context); }
public function beforeAdd(KCommandContext $context) { $data = $context->data; $translator = $this->getService('translator')->getTranslator($this->getIdentifier()); $page = JFactory::getApplication()->getMenu()->getItem($this->getRequest()->Itemid); if (!$page) { $context->setError(new KControllerException($translator->translate('Invalid menu item.'))); return false; } foreach ($this->getModel()->getTable()->getColumns() as $key => $column) { if (!in_array($key, array('storage_type', 'title', 'description'))) { unset($data->$key); } } $data->docman_category_id = $page->params->get('category_id'); $data->enabled = $page->params->get('auto_publish') ? 1 : 0; if (empty($data->storage_type)) { $data->storage_type = $data->storage_path_remote ? 'remote' : 'file'; } if ($data->storage_type === 'file') { $file = KRequest::get('files.storage_path_file', 'raw'); if (empty($file) || empty($file['name'])) { $context->setError(new KControllerException($translator->translate('You did not select a file to be uploaded.'))); return false; } try { $controller = $this->getService('com://admin/files.controller.file', array( 'request' => array('container' => 'docman-files', 'Itemid' => $page->id) )); $this->_uploaded = $controller->add(array( 'file' => $file['tmp_name'], 'name' => $file['name'], 'folder' => $page->params->get('folder') )); $data->storage_path = $this->_uploaded->path; } catch (KControllerException $e) { $context->setError($e); return false; } } else { $data->storage_path = $data->{'storage_path_'.$data->storage_type}; } }
/** * Saves a configuration * * @param KCommandContext $context * * @return */ protected function _actionSave(KCommandContext $context) { $context->append(array('data' => array('params' => array()))); //find or create a new component $component = $this->getService('repos://admin/components.component')->findOrAddNew(array('option' => 'com_' . $this->getIdentifier()->package), array('data' => array('name' => ucfirst($this->getIdentifier()->package)))); $params = new JParameter(''); $params->loadArray((array) $context->data['params']); $component->params = $params->toString(); $component->save(); }
/** * Handles callback * * @param KCommandContext $context * @return void */ protected function _actionGetaccesstoken($context) { $this->getAPI()->requestAccessToken($this->getRequest()); $token = (array) $this->getAPI()->getToken(); $consumer = (array) $this->_consumer; KRequest::set('session.oauth', array('api' => $this->getAPI()->getName(), 'token' => $token, 'consumer' => $consumer)); $return = KRequest::get('session.return', 'raw', null); if ($return) { $context->append(array('data' => array('return' => $return))); } }
/** * Error handler. * * @param KCommandContext $context */ public function handleErrors(KCommandContext $context) { $result = $context->result; if ($result->getStatus() !== KDatabase::STATUS_CREATED) { if (JFactory::getApplication()->getCfg('debug')) { // Notify user about error. $translator = $this->getService('com://admin/logman.translator'); $message = $translator->translate($result->getStatusMessage()); JFactory::getApplication()->enqueueMessage($translator->translate('Error while adding Activity', array('%message%' => $message)), 'notice'); } // Avoid exceptions from being thrown. $context->setError(null); } }
/** * @param KCommandContext $context * @return object */ protected function _actionSubmit(KCommandContext $context) { $data = $this->getModel()->getItem(); $row = $this->getService('com://admin/wufoo.database.row.api_entry'); $row->setData($context->data->toArray()); $row->hash = $data->hash; // Save to send the mail if ($row->save() === false) { $error = $row->getStatusMessage(); $context->setError(new KControllerException($error ? $error : 'Add Action Failed', KHttpResponse::INTERNAL_SERVER_ERROR)); } else { $context->status = KHttpResponse::CREATED; } return $row; }
/** * Return a set of entities. * * @param KCommandContext $context Context parameter * * @return AnDomainEntitysetAbstract */ protected function _actionBrowse(KCommandContext $context) { $data = $context->data; $context->append(array('query' => $this->getRepository()->getQuery())); $query = $context->query; $query->order($this->sort, $this->direction)->limit($this->limit, $this->limitstart); $query->keyword = $this->search; if ($this->getRepository()->hasBehavior('parentable')) { if ($this->getState()->parent) { $query->parent($this->getState()->parent); } elseif ($this->pid == -1) { $query->parent(null); } } return $this->getState()->setList($query->toEntitySet())->getList(); }
/** * Method to upload and Add a photo. * * @param KCommandContext $context */ protected function _actionAdd($context) { $data = $context->data; $file = KRequest::get('files.file', 'raw'); $content = @file_get_contents($file['tmp_name']); $filesize = strlen($content); $uploadlimit = $this->_max_upload_limit * 1024 * 1024; $exif = function_exists('exif_read_data') ? @exif_read_data($file['tmp_name']) : array(); if ($filesize == 0) { throw new LibBaseControllerExceptionBadRequest('File is missing'); return; } if ($filesize > $uploadlimit) { throw new LibBaseControllerExceptionBadRequest('Exceed maximum size'); return; } $orientation = 0; if (!empty($exif) && isset($exif['Orientation'])) { $orientation = $exif['Orientation']; } $data['portrait'] = array('data' => $content, 'rotation' => $orientation, 'mimetype' => isset($file['type']) ? $file['type'] : null); $photo = $this->actor->photos->addNew($data); $photo->setExifData($exif); $photo->save(); $this->setItem($photo); $this->getResponse()->status = KHttpResponse::CREATED; if ($photo->body && preg_match('/\\S/', $photo->body)) { $context->append(array('story' => array('body' => $photo->body))); } return $photo; }
protected function _actionMove(KCommandContext $context) { $data = $this->getModel()->getItem(); if (!$data->isNew()) { $data->setData(KConfig::unbox($context->data)); //Only throw an error if the action explicitly failed. if ($data->move() === false) { $error = $data->getStatusMessage(); $context->setError(new KControllerException($error ? $error : 'Move Action Failed', KHttpResponse::INTERNAL_SERVER_ERROR)); } else { $context->status = $data->getStatus() === KDatabase::STATUS_CREATED ? KHttpResponse::CREATED : KHttpResponse::NO_CONTENT; } } else { $context->setError(new KControllerException('Resource Not Found', KHttpResponse::NOT_FOUND)); } return $data; }
/** * Command handler * * @param string The command name * @param object The command context * * @return boolean */ public final function execute($name, KCommandContext $context) { $result = true; if (isset($this->_callbacks[$name])) { $callbacks = $this->_callbacks[$name]; $params = $this->_params[$name]; foreach ($callbacks as $key => $callback) { //Append the config to the context $context->append($params[$key]); //Call the callback $result = call_user_func($callback, $context); if ($result === false) { break; } } } return $result === false ? false : true; }
/** * Command handler * * @param string The command name * @param object The command context * * @return boolean */ public function execute($name, KCommandContext $context) { $result = true; if (isset($this->_callbacks[$name])) { $callbacks = $this->_callbacks[$name]; $params = $this->_params[$name]; foreach ($callbacks as $key => $callback) { $param = $params[$key]; if (is_array($param) && is_numeric(key($param))) { $result = call_user_func_array($callback, $params); } else { $result = call_user_func($callback, $context->append($param)); } //Call the callback if ($result === false) { break; } } } return $result === false ? false : true; }
public function execute($name, KCommandContext $context) { /* * For config and file controllers, we have specific checks for all actions on them */ $result = true; if ($this->_mixer->getIdentifier()->name === 'config') { $result = $this->canAdmin(); } if ($this->_mixer->getIdentifier()->name === 'file' || $this->getRequest()->routed) { if (!in_array($context->action, array('get', 'display', 'read', 'browse'))) { $result = JFactory::getUser()->authorise('com_docman.upload', 'com_docman'); } else { $result = $this->canManage() || $this->canChangeAnything(); } } if ($result === false) { $context->setError(new KControllerException('Action ' . ucfirst($context->action) . ' Not Allowed', KHttpResponse::METHOD_NOT_ALLOWED)); return false; } return parent::execute($name, $context); }
protected function _databaseBeforeCopy(KCommandContext $context) { $row = $context->caller; if (!array_intersect(array('destination_folder', 'destination_name'), $row->getModified())) { $context->setError(JText::_('Please supply a destination.')); return false; } if ($row->fullpath === $row->destination_fullpath) { $context->setError(JText::_('Source and destination are the same.')); return false; } $dest_adapter = $row->container->getAdapter($row->getIdentifier()->name, array('path' => $row->destination_fullpath)); $exists = $dest_adapter->exists(); if ($exists) { if (!$row->overwrite) { $context->setError(JText::_('Destination resource already exists.')); return false; } else { $row->overwritten = true; } } return true; }
/** * Get action. * * @param KCommandContext $context */ protected function _actionPost(KCommandContext $context) { $context->append(array('data' => KRequest::get('post', 'raw', array()))); //backward compatiblity if ($context->data['action']) { $context->data['_action'] = $context->data['action']; } $action = 'post'; if ($context->data['_action']) { $action = $context->data['_action']; if (in_array($action, array('browse', 'read', 'display'))) { throw new LibBaseControllerExceptionMethodNotAllowed('Action: ' . $action . ' not allowed'); } } if ($context->request->getFormat() == 'json' || $context->request->isAjax()) { $this->registerCallback('after.post', array($this, 'forward')); } else { $context->response->setRedirect(KRequest::get('server.HTTP_REFERER', 'url')); } return $this->getController()->execute($action, $context); }
protected function _saveFiles(KCommandContext $context) { if ($context->error) { return; } $row = $context->result; $count = $this->getService('com://admin/attachments.controller.attachment')->row($row->id)->table($row->getTable()->getBase())->browse(); $count = count($count); $limit = $this->_attachment_limit; foreach ($this->_attachments as $attachment) { if ($limit !== false && $count >= $limit) { $context->setError(new KControllerException('You have reached the attachment limit for this item.')); return false; } if ($this->_saveFile($context, $attachment)) { $count++; } } return true; }
/** * Generic delete function * * @param KCommandContext A command context object * @return KDatabaseRowset A rowset object containing the deleted rows */ protected function _actionDelete(KCommandContext $context) { $data = $this->getModel()->getData(); if (count($data)) { $data->setData(KConfig::unbox($context->data)); //Only throw an error if the action explicitly failed. if ($data->delete() === false) { $error = $data->getStatusMessage(); $context->setError(new KControllerException($error ? $error : 'Delete Action Failed', KHttpResponse::INTERNAL_SERVER_ERROR)); } else { $context->status = KHttpResponse::NO_CONTENT; } } else { $context->setError(new KControllerException('Resource Not Found', KHttpResponse::NOT_FOUND)); } return $data; }
/** * Fetches an entity. * * @param object POST data */ public function fetchEntity(KCommandContext $context) { if ($context->action == 'addphoto') { if ($context->data->id) { $this->id = $context->data->id; } //clone the context so it's not touched $set = $this->__call('fetchEntity', array($context)); if (!$set) { $context->setError(null); //if the action is addphoto and there are no sets then create an set $set = $this->add($context); } return $set; } else { return $this->__call('fetchEntity', array($context)); } }
/** * Can be used as a cabllack to automatically create a story. * * @param KCommandContext $context * * @return ComStoriesDomainEntityStory */ public function createStoryCallback(KCommandContext $context) { if ($context->result !== false) { $data = $context->data; $name = $this->getIdentifier()->name . '_' . $context->action; $context->append(array('story' => array('component' => 'com_' . $this->getIdentifier()->package, 'name' => $name, 'owner' => $this->actor, 'object' => $this->getItem(), 'target' => $this->actor, 'comment' => $this->isCommentable() ? $data->comment : null))); $story = $this->createStory(KConfig::unbox($context->story)); $data->story = $story; return $story; } return $context->result; }
/** * Authorizes an action on resources owned by the actor. * * @param KCommandContext $context Context parameter * * @return bool */ protected function _authorizeAction(KCommandContext $context) { //if entity is not privatable then it doesn't have access to allow method if (!$this->_entity->isPrivatable()) { return true; } //if viewer is admin then return true on the action if (is_person($this->_viewer) && $this->_viewer->admin()) { return true; } $action = $context->action; //any action on the actor requires being a follower by default $context->append(array('default' => LibBaseDomainBehaviorPrivatable::FOLLOWER)); //not access to the entiy if ($this->_entity->authorize('access') === false) { return false; } $parts = explode(':', $action); $component = array_shift($parts); //check if it's a social app then if it's enabled if ($component) { $component = $this->getService('repos://site/components.component')->find(array('component' => $component)); if ($component && $component->authorize('action', array('actor' => $this->_entity, 'action' => $parts[1], 'resource' => $parts[0])) === false) { return false; } } return $this->_entity->allows($this->_viewer, $action, $context->default); }
/** * If item is not translated, display the item in the original language with a warning message. * If item is not enabled, display the item in the original language (if enabled) with a warning message. * Note: only works in html format * * @param KCommandContext $context */ protected function _afterRead(KCommandContext $context) { if ($this->format == 'html') { if ($context->getError() && $context->getError()->getCode() === 404 || $context->result->translated == 0) { $itemInOtherLanguage = $this->_getItemInOriginalLanguage($context); if ($itemInOtherLanguage != null) { // Forbid search engines to index the page JFactory::getDocument()->setMetaData('robots', 'noindex'); // Remove the error so there won't be a 404 response $context->setError(null); $context->result = $itemInOtherLanguage; // Display the message $this->__loadLanguageFile(JFactory::getLanguage()); JFactory::getApplication()->enqueueMessage(JText::_('ONLY_AVAILABLE_' . strtoupper(substr($itemInOtherLanguage->language, 0, 2))), 'danger'); } } } }
/** * Fetches an entity. * * @param KCommandContext $context */ public function fetchEntity(KCommandContext $context) { $context->append(array('identity_scope' => array())); $identifiable_key = $this->getIdentifiableKey(); if ($values = $this->{$identifiable_key}) { $scope = KConfig::unbox($context->identity_scope); $values = KConfig::unbox($values); $scope[$identifiable_key] = $values; if (is_array($values)) { $mode = AnDomain::FETCH_ENTITY_SET; } else { $mode = AnDomain::FETCH_ENTITY; } $query = $this->getRepository()->getQuery(); $query->where($scope); $entity = $this->getRepository()->fetch($query, $mode); if (empty($entity) || !count($entity)) { $exception = new LibBaseControllerExceptionNotFound('Resource Not Found'); //see if the entity exits or not if ($query->disableChain()->fetch()) { if ($this->viewer && !$this->viewer->guest()) { $exception = new LibBaseControllerExceptionForbidden('Forbidden'); } else { $exception = new LibBaseControllerExceptionNotFound('Not Found'); } } throw $exception; } $this->setItem($entity); return $entity; } }