/** * Add a new admin to the system * * @param array $args * @return void */ public function add(array $args = array()) { $ini = Garp_Auth::getInstance()->getConfigValues(); if (empty($ini['adapters']['db'])) { Garp_Cli::errorOut('Error: DB adapter is not configured in application.ini.'); } elseif (empty($ini['adapters']['db']['identityColumn']) || empty($ini['adapters']['db']['credentialColumn'])) { Garp_Cli::errorOut('Error: identityColumn or credentialColumn not configured in application.ini'); } else { $newUserData = array('role' => 'admin'); $promptData = array(); // Pull required fields from Spawner config $modelSet = Garp_Spawn_Model_Set::getInstance(); $userModelConfig = $modelSet['User']; $requiredFields = $userModelConfig->fields->getFields('required', true); foreach ($requiredFields as $field) { if ($field->origin == 'config' && $field->name !== 'id') { $promptData[] = $field->name; } elseif ($field->origin == 'relation') { Garp_Cli::errorOut('Field ' . $field->name . ' is required but must be filled by way of relation. ' . 'This makes it impossible to create an admin from the commandline.'); } } if (!in_array($ini['adapters']['db']['identityColumn'], $promptData)) { $promptData[] = $ini['adapters']['db']['identityColumn']; } // prompt for the new data Garp_Cli::lineOut('Please fill the following columns:'); foreach ($promptData as $key) { $newUserData[$key] = trim(Garp_Cli::prompt($key . ':')); } $newAuthLocalData = array('password' => trim(Garp_Cli::prompt('Choose a password:'******'s entirely possible to circumvent these * conventions and come up with project-specific standards. * In that case however, this CLI command is not for you. */ $user = new Model_User(); try { $id = $user->insert($newUserData); $authLocal = new Model_AuthLocal(); $newAuthLocalData['user_id'] = $id; if ($authLocal->insert($newAuthLocalData)) { Garp_Cli::lineOut('Successfully created the administrator. (id: ' . $id . ')'); } else { Garp_Cli::errorOut('Error: could not create administrator.'); } } catch (Zend_Db_Statement_Exception $e) { if (strpos($e->getMessage(), 'Duplicate entry') !== false && strpos($e->getMessage(), 'email_unique') !== false) { Garp_Cli::errorOut('Error: this email address is already in use. ' . 'Maybe you meant to use Garp Admin make?'); } else { throw $e; } } } }
/** * Format a recordset * * @param Garp_Model $model * @param array $rowset * @return string */ public function format(Garp_Model $model, array $rowset) { $phpexcel = new PHPExcel(); PHPExcel_Cell::setValueBinder(new PHPExcel_Cell_AdvancedValueBinder()); // set metadata $props = $phpexcel->getProperties(); if (Garp_Auth::getInstance()->isLoggedIn()) { $userData = Garp_Auth::getInstance()->getUserData(); $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap'); if ($bootstrap) { $view = $bootstrap->getResource('view'); $userName = $view->fullName($userData); $props->setCreator($userName)->setLastModifiedBy($userName); } } $props->setTitle('Garp content export – ' . $model->getName()); if (count($rowset)) { $this->_addContent($phpexcel, $model, $rowset); } /** * Hm, PHPExcel seems to only be able to write to a file (instead of returning * an XLS binary string). Therefore, we save a temporary file, read its contents * and return those, after which we unlink the temp file. */ $tmpFileName = APPLICATION_PATH . '/data/logs/tmp.xls'; $writer = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5'); $writer->save($tmpFileName); $contents = file_get_contents($tmpFileName); unlink($tmpFileName); return $contents; }
/** * Get Garp_Auth instance * @param Garp_Store_Interface $store Session or cookie, for instance * @return Garp_Auth */ public static function getInstance(Garp_Store_Interface $store = null) { if (!Garp_Auth::$_instance) { Garp_Auth::$_instance = new Garp_Auth($store); } return Garp_Auth::$_instance; }
public function beforeUpdate(&$args) { $data =& $args[1]; $auth = Garp_Auth::getInstance(); if ($auth->isLoggedIn()) { $userData = $auth->getUserData(); $data[self::_MODIFIER_COLUMN] = $userData['id']; } }
protected function _getUserVars() { // Add logged in user data to log $auth = Garp_Auth::getInstance(); $output = array(); if ($auth->isLoggedIn()) { $output['_user_data'] = $auth->getUserData(); } return $output; }
/** * Before fetch callback. * Adds the WHERE clause. * @param Array $args * @return Void */ public function beforeFetch(&$args) { $is_cms = Zend_Registry::isRegistered('CMS') && Zend_Registry::get('CMS'); $is_preview = $this->_isPreview() && Garp_Auth::getInstance()->isLoggedIn(); $force = $this->_force; if (($is_cms || $is_preview) && !$force) { // don't use in the CMS, or in preview mode return; } $model =& $args[0]; $select =& $args[1]; if ($this->_blockOfflineItems) { $this->addWhereClause($model, $select); } }
/** * Return the API layout, e.g. which methods may be called on which entities. * @return stdClass */ public function getLayout() { $methods = array('fetch' => array('fetch', 'fetch_own'), 'create', 'update' => array('update', 'update_own'), 'destroy' => array('destroy', 'destroy_own'), 'count' => array('fetch'), 'relate'); $auth = Garp_Auth::getInstance(); if (is_null($this->_layout)) { // read content managing configuration from content.ini // note; Garp_Cache_Config is not used here because we always want fresh data in the CMS, // no cached versions $config = Garp_Content_Api::_getConfig(); $classes = $config->content->commands; $api = new stdClass(); $api->actions = array(); foreach ($classes as $key => $class) { $alias = !empty($class->alias) ? $class->alias : $key; $modelName = self::modelAliasToClass($alias); if (!array_key_exists($alias, $api->actions)) { $api->actions[$alias] = array(); } foreach ($methods as $method => $privileges) { if (is_numeric($method)) { $method = $privileges; $privileges = array($method); } // Check if any of the given privileges allow for the method to be executed $allowed = false; foreach ($privileges as $privilege) { if ($auth->isAllowed($modelName, $privilege)) { $allowed = true; break; } } // If the method is not allowed, don't mention it in the SMD if (!$allowed) { continue; } $api->actions[$alias][] = array('name' => $method, 'len' => 1); } } $this->_layout = $api; } return $this->_layout; }
/** * Called before all actions * * @return Void */ public function init() { // Do not cache CMS pages. This prevents a common situation where people logout, return to // the CMS, and see the interface but none of the content feeds load. Only after a browser // refresh they'll get bounced to the login page. $this->_helper->cache->setNoCacheHeaders($this->getResponse()); $config = Zend_Registry::get('config'); $this->_setCmsClosedMessage(); if (!$config->cms || !$config->cms->ipfilter || !count($config->cms->ipfilter->toArray())) { return true; } $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null; if ($ip === '127.0.0.1') { // i mean come on return true; } if (!in_array($ip, $config->cms->ipfilter->toArray())) { $authVars = Garp_Auth::getInstance()->getConfigValues(); $this->_helper->flashMessenger(__($authVars['noPermissionMsg'])); $this->_helper->redirector->gotoRoute(array(), $authVars['login']['route']); return false; } }
/** * Store user role in cookie, so it can be used with Javascript * * @return void */ protected function _storeRoleInCookie() { $userRecord = Garp_Auth::getInstance()->getUserData(); if (!empty($userRecord['role'])) { $cookie = new Garp_Store_Cookie('Garp_Auth'); $cookie->userData = array('role' => $userRecord['role']); } }
protected function _getPasswordlessModel() { $authPwlessModel = new Model_AuthPasswordless(); $userModel = new Model_User(); $userConditions = $userModel->select()->from($userModel->getName(), Garp_Auth::getInstance()->getSessionColumns()); $authPwlessModel->bindModel('Model_User', array('conditions' => $userConditions, 'rule' => 'User')); return $authPwlessModel; }
/** * Maps methods to Garp_Auth * @param String $method * @param Array $args * @return Mixed */ public function __call($method, $args) { $auth = Garp_Auth::getInstance(); return call_user_func_array(array($auth, $method), $args); }
/** * Prevent admins from saving a user's role greater than their own. * Note: will return TRUE if no user is logged in. This is because * we sometimes have to manipulate roles from apis and cli commands * where no physical user session is present. * Will also return TRUE when ACL is not defined. * @param String $role The role that is about to be saved. * @return Boolean */ protected function _isRoleAllowed($role) { $currentAdminRole = Garp_Auth::getInstance()->getCurrentRole(); $currentAdminIsVisitor = Garp_Auth::DEFAULT_VISITOR_ROLE == $currentAdminRole; $zendAclIsNotRegistered = !Zend_Registry::isRegistered('Zend_Acl'); $roleIsEqualToCurrentAdminRole = $role == $currentAdminRole; if ($currentAdminIsVisitor || $zendAclIsNotRegistered || $roleIsEqualToCurrentAdminRole) { return true; } // Check if the role that is about to be manipulated is a child of the // current role. If so, that role is considered greater than the current // role. // Note that this logic does not check ACL branches that can be considered // siblings, or nephews. // For instance Visitor > User > Admin vs Visitor > Teacher. Is teacher greater // or less than Admin? These semantics must be written customly. $children = Garp_Auth::getInstance()->getRoleChildren($currentAdminRole); return !in_array($role, $children); }
/** * Check a record belongs to the currently logged in user. * This check is based on the author_id column. * * @param array $data The record data. Primary key must be present here. * @param string $where A WHERE clause to find the record * @return bool */ protected function _itemBelongsToUser($data, $where = false) { $userData = Garp_Auth::getInstance()->getUserData(); $userId = $userData['id']; if (!array_key_exists('author_id', $data)) { if (!$where) { return false; } // fetch the record based on the given WHERE clause $row = $this->_model->fetchRow($where); if (!$row || !$row->author_id) { return false; } $data = $row->toArray(); } return $userId == $data['author_id']; }
/** * Store targetUrl in session. After login the user is redirected * back to this url. * @return Void */ protected function _storeTargetUrl() { $request = $this->getRequest(); // Only store targetUrl when method = GET. A redirect to a POST request is useless. if (!$request->isGet()) { return; } // Allow ?targetUrl=/path/to/elsewhere on any URL if (!($targetUrl = $request->getParam('targetUrl'))) { $targetUrl = $request->getRequestUri(); $baseUrl = $request->getBaseUrl(); /** * Remove the baseUrl from the targetUrl. This is neccessary * when Garp is installed in a subfolder. */ $targetUrl = Garp_Util_String::strReplaceOnce($baseUrl, '', $targetUrl); } if ($targetUrl !== '/favicon.ico' && !$request->isXmlHttpRequest()) { $store = Garp_Auth::getInstance()->getStore(); $store->targetUrl = $targetUrl; } }
/** * Return array of columns that are stored in the session cookie * @return Array|String (can also be Zend_Db_Select::SQL_WILDCARD) */ protected function _getSessionColumns() { return Garp_Auth::getInstance()->getSessionColumns(); }
public function getAclRolesThatAreNotAllowedModelPrivilege(Garp_Spawn_Model_Base $model, $privilege) { if (!Zend_Registry::isRegistered('Zend_Acl')) { return; } $acl = Zend_Registry::get('Zend_Acl'); $modelResourceName = ($model->module === 'garp' ? 'G_' : null) . 'Model_' . $model->id; if ($acl->has($modelResourceName)) { $auth = Garp_Auth::getInstance(); $roles = $auth->getRoles(); $rolesThatDontHaveThisPrivilege = array(); foreach ($roles as $role) { if (!$acl->isAllowed($role, $modelResourceName, $privilege)) { $rolesThatDontHaveThisPrivilege[] = $role; } } return $rolesThatDontHaveThisPrivilege; } }
protected static function _composeFullErrorMessage(ArrayObject $errors) { $appName = self::_getApplicationName(); $errorMessage = "Application: {$appName}\n\n"; $errorMessage .= "Exception: {$errors->exception->getMessage()}\n\n"; $errorMessage .= "Stacktrace: {$errors->exception->getTraceAsString()}\n\n"; if (isset($errors->request)) { $errorMessage .= "Request URL: {$errors->request->getRequestUri()}\n\n"; } // Referer if (!empty($_SERVER['HTTP_REFERER'])) { $errorMessage .= "Referer: {$_SERVER['HTTP_REFERER']}\n\n"; } else { $errorMessage .= "Referer: n/a\n\n"; } // IP Addr if (!empty($_SERVER['REMOTE_ADDR'])) { $errorMessage .= "IP address: {$_SERVER['REMOTE_ADDR']}\n\n"; } else { $errorMessage .= "IP address: n/a\n\n"; } // User agent if (!empty($_SERVER['HTTP_USER_AGENT'])) { $errorMessage .= "User agent: {$_SERVER['HTTP_USER_AGENT']}\n\n"; } else { $errorMessage .= "User agent: n/a\n\n"; } // Request params $errorMessage .= 'Request parameters: ' . print_r($errors->request->getParams(), true) . "\n\n"; // User data $errorMessage .= 'User data: '; $auth = Garp_Auth::getInstance(); if ($auth->isLoggedIn()) { $errorMessage .= print_r($auth->getUserData(), true); } else { $errorMessage .= 'n/a'; } $errorMessage .= "\n\n"; return $errorMessage; }
/** * Set Vimeo access token * @param Garp_Service_Vimeo_Pro $vimeo * @return Void */ protected function _setVimeoAccessToken(Garp_Service_Vimeo_Pro $vimeo) { // See if the currently logged in user has Vimeo credentials related to her, and use the token // and token secret. That way a user can fetch private videos thru the API. $garpAuth = Garp_Auth::getInstance(); if (!$garpAuth->isLoggedIn()) { return; } $currentUser = $garpAuth->getUserData(); $authVimeoModel = new Model_AuthVimeo(); $authVimeoRecord = $authVimeoModel->fetchRow($authVimeoModel->select()->where('user_id = ?', $currentUser['id'])); if ($authVimeoRecord) { $vimeo->setAccessToken($authVimeoRecord->access_token); $vimeo->setAccessTokenSecret($authVimeoRecord->access_token_secret); } }