Example #1
0
 /**
  * Sets the adapter and the tablename of the resource retroactively.
  * @param string $database name of the database
  * @param string $table name of the table
  */
 public function init($database, $table = null)
 {
     // get the user adapter
     $username = Daiquiri_Auth::getInstance()->getCurrentUsername();
     // check if this database is the user datasbase
     if ($database === Daiquiri_Config::getInstance()->getUserDbName($username)) {
         $adapter = Daiquiri_Config::getInstance()->getUserDbAdapter();
     } else {
         // get the database id and check permission on database
         $databasesResource = new Data_Model_Resource_Databases();
         $result = $databasesResource->checkACL($database, 'select');
         if ($result !== true) {
             throw new Daiquiri_Exception_NotFound();
         }
         // check permission on table access
         if ($table) {
             $tablesResource = new Data_Model_Resource_Tables();
             $result = $tablesResource->checkACL($database, $table, 'select');
             if ($result !== true) {
                 throw new Daiquiri_Exception_NotFound();
             }
         }
         // if everything went ok get adapter
         $adapter = Daiquiri_Config::getInstance()->getUserDbAdapter($database);
     }
     // set adapter and table
     $this->setAdapter($adapter);
     if ($table) {
         $this->setTablename($table);
     }
 }
Example #2
0
 public function init()
 {
     $this->_items = array('admin' => array('text' => 'Admin overview', 'href' => '/core/admin'), 'config' => array('text' => 'Configuration', 'href' => '/core/config', 'resource' => 'Core_Model_Config', 'permission' => 'index', 'icon' => 'fa-wrench'), 'templates' => array('text' => 'Mail templates', 'href' => '/core/templates', 'resource' => 'Core_Model_Templates', 'permission' => 'index', 'icon' => 'fa-envelope-o'), 'messages' => array('text' => 'Status messages', 'href' => '/core/messages', 'resource' => 'Core_Model_Messages', 'permission' => 'index', 'icon' => 'fa-comment'), 'user' => array('text' => 'User management', 'href' => '/auth/user', 'resource' => 'Auth_Model_User', 'permission' => 'rows', 'icon' => 'fa-users'), 'sessions' => array('text' => 'Sessions management', 'href' => '/auth/sessions', 'resource' => 'Auth_Model_Sessions', 'permission' => 'rows', 'icon' => 'fa-laptop'), 'data' => array('text' => 'Database management', 'href' => '/data', 'resource' => 'Data_Model_Databases', 'permission' => 'show', 'icon' => 'fa-database'), 'static' => array('text' => 'Static HTML management', 'href' => '/data/static', 'resource' => 'Data_Model_Static', 'permission' => 'show', 'icon' => 'fa-file'), 'meetings' => array('text' => 'Meetings management', 'href' => '/meetings/', 'resource' => 'Meetings_Model_Meetings', 'permission' => 'index', 'icon' => 'fa-calendar'), 'contact' => array('text' => 'Contact messages', 'href' => '/contact/messages', 'resource' => 'Contact_Model_Messages', 'permission' => 'rows', 'icon' => 'fa-envelope'), 'examples' => array('text' => 'Query examples', 'href' => '/query/examples', 'resource' => 'Query_Model_Examples', 'permission' => 'index', 'icon' => 'fa-code'), 'query' => array('text' => 'Query jobs', 'href' => '/query/jobs', 'resource' => 'Query_Model_Jobs', 'permission' => 'rows', 'icon' => 'fa-gears'));
     if (Daiquiri_Config::getInstance()->core->cms->enabled && in_array(Daiquiri_Auth::getInstance()->getCurrentRole(), array('manager', 'admin'))) {
         $this->_items['cms'] = array('text' => 'CMS Admin', 'href' => rtrim(Daiquiri_Config::getInstance()->core->cms->url, '/') . '/wp-admin/', 'icon' => 'fa-pencil');
     }
 }
Example #3
0
 /**
  * @brief   internalLink method - returns a link to a Daiquiri related resource if ACL is positive
  * @param   array $options: containing keys: text, href, resource, permission, prepend, append
  * @return  HTML with link
  * 
  * Produces a link to a daiquiri internal resource. Checks if ACL are positive for the user, if not
  * no link will be produced and remains empty. The link is configured through the $option array with the
  * following parameters:
  *      - <b>text</b>: Text shown as link
  *      - <b>href</b>: Daiquiri internal link (relative to base url)
  *      - <b>resource</b>: The resource corresponding to the link
  *      - <b>prepend</b>: Any HTML that should be prepended to the link
  *      - <b>append</b>: Any HTML that should be appended to the link.
  */
 public function internalLink(array $options)
 {
     // check permissions
     if (array_key_exists('resource', $options) && array_key_exists('permission', $options)) {
         if (!Daiquiri_Auth::getInstance()->checkAcl($options['resource'], $options['permission'])) {
             return '';
         }
     }
     $html = '';
     // prepend stuff
     if (array_key_exists('prepend', $options)) {
         $html .= $options['prepend'];
     }
     $html .= "<a href=\"{$this->view->baseUrl($options['href'])}\"";
     foreach ($options as $key => $value) {
         if (!in_array($key, array('resource', 'permission', 'prepend', 'append', 'text', 'href'))) {
             $html .= " {$key}=\"{$value}\"";
         }
     }
     $html .= '>';
     // prepend stuff
     if (array_key_exists('text', $options)) {
         $html .= $options['text'];
     } else {
         $html .= $options['href'];
     }
     $html .= '</a>';
     // append stuff
     if (array_key_exists('append', $options)) {
         $html .= $options['append'];
     }
     return $html;
 }
Example #4
0
 /**
  * Fetches a set of rows from the (pending) job table
  * @throws Exception
  * @return array $rows
  */
 public function fetchRows(array $sqloptions = array())
 {
     $select = $this->select();
     $select->from('Uws_Jobs');
     $select->where("ownerId = ?", Daiquiri_Auth::getInstance()->getCurrentUsername());
     return $this->fetchAll($select);
 }
Example #5
0
 public function indexAction()
 {
     if (Daiquiri_Auth::getInstance()->checkAcl('Query_Model_Jobs', 'rows')) {
         $this->view->status = 'ok';
     } else {
         throw new Daiquiri_Exception_Unauthorized();
     }
 }
Example #6
0
 /**
  * Updates the credentials of the currently logged in user.
  * @param array $formParams
  * @return array $response
  */
 public function update(array $formParams = array())
 {
     // get id
     $id = Daiquiri_Auth::getInstance()->getCurrentId();
     // get user
     $user = $this->getResource()->fetchRow($id);
     // get user detail keys model
     $detailKeyModel = new Auth_Model_DetailKeys();
     $detailKeys = $detailKeyModel->getResource()->fetchRows();
     // create the form object
     $form = new Auth_Form_Account(array('user' => $this->getResource()->fetchRow($id), 'detailKeys' => $detailKeys, 'changeUsername' => Daiquiri_Config::getInstance()->auth->changeUsername, 'changeEmail' => Daiquiri_Config::getInstance()->auth->changeEmail));
     // valiadate the form if POST
     if (!empty($formParams)) {
         if ($form->isValid($formParams)) {
             // get the form values
             $values = $form->getValues();
             // process the details
             $changed = false;
             $values['details'] = array();
             foreach ($detailKeys as $detailKey) {
                 if (is_array($values[$detailKey['key']])) {
                     $values['details'][$detailKey['key']] = Zend_Json::encode($values[$detailKey['key']]);
                 } else {
                     if ($values[$detailKey['key']] === null) {
                         $values['details'][$detailKey['key']] = Zend_Json::encode(array());
                     } else {
                         $values['details'][$detailKey['key']] = $values[$detailKey['key']];
                     }
                 }
                 unset($values[$detailKey['key']]);
                 if ($values['details'][$detailKey['key']] != $user['details'][$detailKey['key']]) {
                     $changed = true;
                 }
             }
             if (Daiquiri_Config::getInstance()->auth->changeUsername && $values['username'] != $user['username']) {
                 $changed = true;
             }
             if (Daiquiri_Config::getInstance()->auth->changeEmail && $values['email'] != $user['email']) {
                 $changed = true;
             }
             if ($changed) {
                 // update the user
                 $this->getResource()->updateRow($id, $values);
                 // log the event
                 Daiquiri_Log::getInstance()->notice('account updated by user');
                 // send a notification
                 if (Daiquiri_Config::getInstance()->core->notification->updateUser) {
                     $newUser = $this->getResource()->fetchRow($id);
                     $this->getModelHelper('notification')->updateUser($user, $newUser);
                 }
             }
             return array('status' => 'ok');
         } else {
             return $this->getModelHelper('CRUD')->validationErrorResponse($form);
         }
     }
     return array('form' => $form, 'status' => 'form');
 }
Example #7
0
 public function indexAction()
 {
     // check acl
     if (Daiquiri_Auth::getInstance()->checkAcl('Data_Model_Databases', 'update')) {
         $this->view->status = 'ok';
     } else {
         throw new Daiquiri_Exception_Unauthorized();
     }
 }
Example #8
0
 /**
  * Constructor. Sets processing and permissions resource.
  */
 public function __construct()
 {
     $this->_permissions = new Query_Model_Resource_Permissions();
     $this->_processing = new Query_Model_Resource_Processing();
     // get current user
     $username = Daiquiri_Auth::getInstance()->getCurrentUsername();
     if ($username === null) {
         $username = '******';
     }
     $this->_userDb = Daiquiri_Config::getInstance()->getUserDbName($username);
 }
Example #9
0
 /**
  * Creates inserts and returns a new token.
  * @param   array   $data   row data
  * @return  string  $token  the new token
  */
 public function insertRow(array $data = array())
 {
     // get lifetime for token
     $lifetime = Daiquiri_Config::getInstance()->auth->tokenLifetime;
     // randomly create the new token
     $token = md5(mt_rand(1, 1000000));
     // set expiration date to tomorrow
     $expires = date("Y-m-d\\TH:i:s", time() + $lifetime);
     // insert into database credentials
     $this->getAdapter()->insert('Auth_Token', array('username' => Daiquiri_Auth::getInstance()->getCurrentUsername(), 'token' => $token, 'path' => $data['path'], 'expires' => $expires));
     // return the id of the newly created user
     return $token;
 }
Example #10
0
 /**
  * Returns the public information about a meetings contributions
  * @param string $slug slug of the meeting
  * @return array $response
  */
 public function info($slug)
 {
     // get model
     $meetingsModel = new Meetings_Model_Meetings();
     $meeting = $meetingsModel->getResource()->fetchRow(array('where' => array('slug = ?' => $slug)));
     if (empty($meeting)) {
         throw new Daiquiri_Exception_NotFound();
     }
     if (!Daiquiri_Auth::getInstance()->checkPublicationRoleId($meeting['participants_publication_role_id'])) {
         return array('status' => 'forbidden', 'message' => $meeting['participants_message']);
     } else {
         return array('status' => 'ok', 'message' => $meeting['participants_message'], 'rows' => $this->getResource()->fetchRows(array('where' => array('`meeting_id` = ?' => $meeting['id'], '(`status` = "accepted") OR (`status` = "organizer") OR (`status` = "invited")'), 'order' => 'lastname ASC')));
     }
 }
Example #11
0
 /**
  * Proxies calls to member function to the model. Implements security layer.
  * @param string $methodname
  * @param array $arguments
  * @throws Daiquiri_Exception_Forbidden
  * @return type (return value of model function)
  */
 public function __call($methodname, array $arguments)
 {
     // check if method exists
     if (!method_exists($this->_model, $methodname)) {
         throw new Exception('Method ' . $methodname . ' not found in ' . get_class($this->_model));
     }
     // check the acl
     $result = Daiquiri_Auth::getInstance()->checkMethod(get_class($this->_model), $methodname);
     // call function or throw exception if not allowed
     if ($result === true) {
         return call_user_func_array(array($this->_model, $methodname), $arguments);
     } else {
         throw new Daiquiri_Exception_Unauthorized();
     }
 }
Example #12
0
 public function adminMenu($listOnly = true)
 {
     $html = '';
     if (Daiquiri_Auth::getInstance()->checkAcl('Auth_Model_User', 'rows')) {
         if ($listOnly === true) {
             $html .= '<li class="dropdown">';
             $html .= '<a class="dropdown-toggle" data-toggle="dropdown" href="#">Admin</a>';
             $html .= '<ul class = "dropdown-menu">';
         }
         $html .= $this->view->action('menu', 'admin', 'core');
         if ($listOnly === true) {
             $html .= '</ul></li>';
         }
     }
     return $html;
 }
Example #13
0
 public function accountMenu($listOnly = true)
 {
     $html = '';
     if (Daiquiri_Auth::getInstance()->checkAcl('Auth_Model_User', 'edit') || Daiquiri_Auth::getInstance()->checkAcl('Auth_Model_Password', 'change')) {
         if ($listOnly === true) {
             $html .= '<li class="dropdown">';
             $html .= '<a class="dropdown-toggle" data-toggle="dropdown" href="#">My Account</a>';
             $html .= '<ul class = "dropdown-menu">';
         }
         $html .= $this->view->internalLink(array('href' => '/auth/account/update?redirect=' . $this->view->path(), 'text' => 'Update Profile', 'resource' => 'Auth_Model_Account', 'permission' => 'update', 'prepend' => '<li class="nav-item">', 'append' => '</li>'));
         $html .= $this->view->internalLink(array('href' => '/auth/password/change?redirect=' . $this->view->path(), 'text' => 'Change Password', 'resource' => 'Auth_Model_Password', 'permission' => 'change', 'prepend' => '<li class="nav-item">', 'append' => '</li>'));
         if ($listOnly === true) {
             $html .= '</ul></li>';
         }
     }
     return $html;
 }
Example #14
0
 /**
  * Submits a contact message.
  * @param array $formParams
  * @return array $response
  */
 public function contact(array $formParams = array())
 {
     // get categories
     $categoriesModel = new Contact_Model_Categories();
     $categories = $categoriesModel->getResource()->fetchValues('category');
     // get user if one is logged in
     $userId = Daiquiri_Auth::getInstance()->getCurrentId();
     if ($userId > 0) {
         // get the user model for getting user details
         $userModel = new Auth_Model_User();
         $user = $userModel->getResource()->fetchRow($userId);
     } else {
         $user = array();
     }
     // create the form object
     $form = new Contact_Form_Submit(array('categories' => $categories, 'user' => $user));
     if (!empty($formParams)) {
         if ($form->isValid($formParams)) {
             // form is valid, get values
             $values = $form->getValues();
             unset($values['submit']);
             // set the user_id
             $values['user_id'] = $userId;
             // set timestamp
             $values['datetime'] = date("Y-m-d H:i:s");
             // set status of new message to active
             $statusModel = new Contact_Model_Status();
             $values['status_id'] = $statusModel->getResource()->fetchId(array('where' => array('`status` = "active"')));
             // store in database (if enabled)
             $this->getResource()->insertRow($values);
             // get the category
             $row = $categoriesModel->getResource()->fetchRow($values['category_id']);
             $values['category'] = $row['category'];
             // send mail to user who used the contact form
             $this->getModelHelper('mail')->send('contact.submit_user', array('to' => $values['email'], 'firstname' => $values['firstname'], 'lastname' => $values['lastname']));
             // send mail to support
             $userResource = new Auth_Model_Resource_User();
             $this->getModelHelper('mail')->send('contact.submit_support', array('to' => array_merge($userResource->fetchEmailByRole('manager'), $userResource->fetchEmailByRole('admin')), 'reply_to' => $values['email'], 'firstname' => $values['firstname'], 'lastname' => $values['lastname'], 'email' => $values['email'], 'category' => $values['category'], 'subject' => $values['subject'], 'message' => $values['message'], 'link' => Daiquiri_Config::getInstance()->getSiteUrl() . '/contact/messages'));
             return array('status' => 'ok');
         } else {
             return array('status' => 'error', 'errors' => $form->getMessages(), 'form' => $form);
         }
     }
     return array('form' => $form, 'status' => 'form');
 }
Example #15
0
 public function indexAction()
 {
     $this->view->status = 'ok';
     // get the csrf token
     $session = new Zend_Session_Namespace('csrf');
     $csrf = $session->hash;
     // get the forms to display
     $options = array('defaultForm' => Null, 'polling' => Daiquiri_Config::getInstance()->query->polling->toArray(), 'forms' => array(), 'csrf' => $csrf);
     foreach (Daiquiri_Config::getInstance()->query->forms as $key => $form) {
         if ($form->default) {
             $options['defaultForm'] = $key;
         }
         $options['forms'][] = array('key' => $key, 'title' => $form->title);
     }
     $this->view->options = $options;
     // get options for the query plan
     $queryModel = new Query_Model_Query();
     $this->view->plan = array('enabled' => $queryModel->canShowPlan(), 'editable' => $queryModel->canAlterPlan(), 'mail' => Daiquiri_Config::getInstance()->query->processor->mail->enabled);
     // get the different download options
     $this->view->downloadAdapter = Daiquiri_Config::getInstance()->getQueryDownloadAdapter();
     // check if imageviewer is enabled
     if (Daiquiri_Config::getInstance()->query->images->enabled) {
         $this->view->images = true;
     } else {
         $this->view->images = false;
     }
     // check if the table cols/rows should be selectable
     if (Daiquiri_Config::getInstance()->query->results->select) {
         $this->view->select = true;
     } else {
         $this->view->select = false;
     }
     // check if samp is enabled
     if (Daiquiri_Config::getInstance()->query->samp->enabled && Daiquiri_Auth::getInstance()->getCurrentUsername() !== 'guest') {
         $this->view->samp = true;
     } else {
         $this->view->samp = false;
     }
     // check if plot is enabled
     if (Daiquiri_Config::getInstance()->query->plot->enabled) {
         $this->view->plot = true;
     } else {
         $this->view->plot = false;
     }
 }
Example #16
0
 public function preDispatch(Zend_Controller_Request_Abstract $request)
 {
     parent::preDispatch($request);
     $username = null;
     $password = null;
     if (isset($_SERVER['PHP_AUTH_USER'])) {
         $username = $_SERVER['PHP_AUTH_USER'];
     } else {
         if ($request->getQuery('username') !== null) {
             $username = $request->getQuery('username');
             $request->setParam('username', null);
         }
     }
     if (isset($_SERVER['PHP_AUTH_PW'])) {
         $password = $_SERVER['PHP_AUTH_PW'];
     } else {
         if ($request->getQuery('password')) {
             $password = $request->getQuery('password');
             $request->setParam('password', null);
         }
     }
     // get the authorisation headers
     if (!empty($username) && !empty($password)) {
         // try to authenticate as user
         $result = Daiquiri_Auth::getInstance()->authenticateUser($username, $password);
         if (!$result) {
             // try to authenticate with the samp token
             $result = Daiquiri_Auth::getInstance()->authenticateToken($username, $password, $request->getPathInfo());
             if (!$result) {
                 // try to authenticate as app
                 $result = Daiquiri_Auth::getInstance()->authenticateApp($username, $password);
                 if (!$result) {
                     $this->getResponse()->clearHeaders()->setHttpResponseCode(401)->sendResponse();
                     die(0);
                 }
             }
         }
         Daiquiri_Auth::getInstance()->unsetCsrf();
         $this->_active = true;
     }
 }
Example #17
0
 /**
  * Goes through the SQL parse tree and checks whether the user tries to use
  * a SQL command he should not.
  * @param array of PHPSQLParser objects $sqlParseTrees
  * @param array $multiLineUsedDBs array with used database for each multiline query
  * @param error array $error or array of NULLs if OK
  * @return TRUE if ok, FALSE if not
  */
 private function _aclSQLCommands(&$sqlParseTrees, &$multiLineUsedDBs, array &$error)
 {
     $auth = Daiquiri_Auth::getInstance();
     $sum = 0;
     foreach ($multiLineUsedDBs as $db) {
         if ($this->_checkTableDBACL("SELECT", $db, false, $auth, $error) !== true) {
             return false;
         }
     }
     foreach ($sqlParseTrees as $key => $currQuery) {
         if ($currQuery === false) {
             $error['aclError'] = "Error in line " . ($key + 1) . ": " . "Could not parse query. Are you sure this is SQL?";
             return false;
         }
         $errorStr = array();
         if ($this->_checkACLSQLCommands_r($currQuery, $auth, $errorStr, $multiLineUsedDBs[$key]) !== true) {
             $error['aclError'] = "Error in line " . ($key + 1) . ": " . $errorStr[0];
             return false;
         }
     }
     return true;
 }
Example #18
0
 /**
  * Returns the public information about a meetings contributions
  * @param string $slug slug of the meeting
  * @return array $response
  */
 public function info($slug)
 {
     // get model
     $meetingsModel = new Meetings_Model_Meetings();
     $meeting = $meetingsModel->getResource()->fetchRow(array('where' => array('slug = ?' => $slug)));
     if (empty($meeting)) {
         throw new Daiquiri_Exception_NotFound();
     }
     if (!Daiquiri_Auth::getInstance()->checkPublicationRoleId($meeting['contributions_publication_role_id'])) {
         return array('status' => 'forbidden', 'message' => $meeting['contributions_message']);
     } else {
         $dbRows = $this->getResource()->fetchRows(array('where' => array('`meeting_id` = ?' => $meeting['id'], '`accepted` = 1'), 'order' => 'participant_lastname ASC'));
         $rows = array();
         foreach ($dbRows as $dbRow) {
             if (!array_key_exists($dbRow['contribution_type'], $rows)) {
                 $rows[$dbRow['contribution_type']] = array();
             }
             $rows[$dbRow['contribution_type']][] = $dbRow;
         }
         return array('status' => 'ok', 'message' => $meeting['contributions_message'], 'rows' => $rows);
     }
 }
Example #19
0
 /**
  * Constructor. Sets writer and filter for log.
  */
 function __construct()
 {
     if (Daiquiri_Config::getInstance()->core->log->enabled && php_sapi_name() !== 'cli') {
         // configure formatter for log
         $ip = Daiquiri_Auth::getInstance()->getRemoteAddr();
         $username = Daiquiri_Auth::getInstance()->getCurrentUSername();
         $formatstring = '%timestamp% ' . $ip . ' "' . $username . '" %priorityName% "%message%"' . PHP_EOL;
         $formatter = new Zend_Log_Formatter_Simple($formatstring);
         // open log file and get writer for log
         $stream = @fopen(Daiquiri_Config::getInstance()->core->log->logfile, 'a', false);
         if (!$stream) {
             throw new Exception('Failed to open log file');
         }
         $writer = new Zend_Log_Writer_Stream($stream);
         $writer->setFormatter($formatter);
         // set loglevel
         $loglevel = strtoupper(Daiquiri_Config::getInstance()->core->log->loglevel);
         $filter = new Zend_Log_Filter_Priority(constant("Zend_Log::{$loglevel}"));
         // configure log object
         $this->_log = new Zend_Log();
         $this->_log->addWriter($writer);
         $this->_log->addFilter($filter);
     }
 }
Example #20
0
 /**
  * Authenticates a given user.
  * @param array $formParams
  * @return $response
  */
 public function login(array $formParams = array())
 {
     // get the form object
     $form = new Auth_Form_Login();
     // check if request is POST
     if (!empty($formParams)) {
         if ($form->isValid($formParams)) {
             // form is valid, get values
             $values = $form->getValues();
             // create DbAuth model and authenticate
             $result = Daiquiri_Auth::getInstance()->authenticateUser($values['username'], $values['password'], $values['remember']);
             // redirect depending on result of authentication
             if ($result) {
                 return array('status' => 'redirect');
             } else {
                 $form->setDescription('Wrong credentials provided');
                 return $this->getModelHelper('CRUD')->validationErrorResponse($form);
             }
         } else {
             return $this->getModelHelper('CRUD')->validationErrorResponse($form);
         }
     }
     return array('form' => $form, 'status' => 'form');
 }
Example #21
0
 /**
  * Updates a column entry.
  * @param mixed $input int id or array with "db","table" and "column" keys
  * @param array $formParams
  * @return array $response
  */
 public function update($input, array $formParams = array())
 {
     if (is_int($input)) {
         $entry = $this->getResource()->fetchRow($input);
     } elseif (is_array($input)) {
         if (empty($input['db']) || empty($input['table']) || empty($input['column'])) {
             throw new Exception('Either int id or array with "db","table" and "column" keys must be provided as $input');
         }
         $entry = $this->getResource()->fetchRowByName($input['db'], $input['table'], $input['column']);
     } else {
         throw new Exception('$input has wrong type.');
     }
     if (empty($entry)) {
         throw new Daiquiri_Exception_NotFound();
     }
     // get tables and ucds
     $tablesResource = new Data_Model_Resource_Tables();
     $ucdsResource = new Daiquiri_Model_Resource_Table();
     $ucdsResource->setTablename('Data_UCD');
     // get roles
     $roles = array_merge(array(0 => 'not published'), Daiquiri_Auth::getInstance()->getRoles());
     $form = new Data_Form_Columns(array('tables' => $tablesResource->fetchValues('name'), 'tableId' => $entry['table_id'], 'ucds' => $ucdsResource->fetchRows(), 'roles' => $roles, 'submit' => 'Update column entry', 'entry' => $entry));
     // valiadate the form if POST
     if (!empty($formParams)) {
         if ($form->isValid($formParams)) {
             // get the form values
             $values = $form->getValues();
             unset($values['ucd_list']);
             // check if the order needs to be set to NULL
             if ($values['order'] === '') {
                 $values['order'] = NULL;
             }
             $values['database'] = $entry['database'];
             $values['table'] = $entry['table'];
             try {
                 $this->getResource()->updateRow($entry['id'], $values);
             } catch (Exception $e) {
                 return $this->getModelHelper('CRUD')->validationErrorResponse($form, $e->getMessage());
             }
             return array('status' => 'ok');
         } else {
             return $this->getModelHelper('CRUD')->validationErrorResponse($form);
         }
     }
     return array('form' => $form, 'status' => 'form');
 }
Example #22
0
 /**
  * Returns all config databases for export.
  * @return array $response
  */
 public function export()
 {
     $rows = array();
     foreach ($this->getResource()->fetchRows() as $dbRow) {
         $rows[] = array('name' => $dbRow['name'], 'order' => $dbRow['order'], 'description' => $dbRow['description'], 'publication_select' => $dbRow['publication_select'], 'publication_update' => $dbRow['publication_update'], 'publication_insert' => $dbRow['publication_insert'], 'publication_show' => $dbRow['publication_show'], 'publication_role' => Daiquiri_Auth::getInstance()->getRole($dbRow['publication_role_id']));
     }
     return array('data' => array('databases' => $rows), 'status' => 'ok');
 }
Example #23
0
 /**
  * Sets the status of a given user from 'disabled' to 'active'.
  * @param int $userId id of the user
  * @param array $formParams
  * @return array $response
  */
 public function reenable($userId, array $formParams = array())
 {
     // create the form object
     $form = new Daiquiri_Form_Confirm(array('submit' => 'Reenable user'));
     // valiadate the form if POST
     if (!empty($formParams)) {
         if ($form->isValid($formParams)) {
             // get the user credentials
             $user = $this->getResource()->fetchRow($userId);
             // update the use
             if ($user['status'] === 'active') {
                 $form->setDescription('User status is already "active"');
                 return $this->getModelHelper('CRUD')->validationErrorResponse($form);
             } else {
                 // get the new status id
                 $statusId = Daiquiri_Auth::getInstance()->getStatusId('active');
                 // activate user in database
                 $this->getResource()->updateRow($userId, array('status_id' => $statusId));
                 // send a notification mail
                 if (Daiquiri_Config::getInstance()->auth->notification->updateUser) {
                     $user = $this->getResource()->fetchRow($userId);
                     $this->getModelHelper('mail')->send('auth.updateUser', array('to' => Daiquiri_Config::getInstance()->auth->notification->mail->toArray(), 'id' => $user['id'], 'username' => $user['username'], 'firstname' => $user['details']['firstname'], 'lastname' => $user['details']['lastname']));
                 }
                 // log the event and return
                 Daiquiri_Log::getInstance()->notice("user '{$user['username']}' reenabled");
                 return array('status' => 'ok');
             }
         } else {
             return $this->getModelHelper('CRUD')->validationErrorResponse($form);
         }
     }
     return array('form' => $form, 'status' => 'form');
 }
Example #24
0
 /**
  * Registers a participant.
  * @param string $slug slug of the meeting
  * @param array $formParams
  * @return array $response
  */
 public function register($slug, array $formParams = array())
 {
     // get models
     $meetingsModel = new Meetings_Model_Meetings();
     $meeting = $meetingsModel->getResource()->fetchRow(array('where' => array('slug = ?' => $slug)));
     if (empty($meeting)) {
         throw new Daiquiri_Exception_NotFound();
     }
     if (!Daiquiri_Auth::getInstance()->checkPublicationRoleId($meeting['registration_publication_role_id'])) {
         return array('status' => 'forbidden', 'message' => $meeting['registration_message']);
     }
     // get user if one is logged in
     $userId = Daiquiri_Auth::getInstance()->getCurrentId();
     if ($userId > 0) {
         // get the user model for getting user details
         $userModel = new Auth_Model_User();
         $user = $userModel->getResource()->fetchRow($userId);
     } else {
         $user = array();
     }
     // create the form object
     $form = new Meetings_Form_Registration(array('submit' => 'Register for this meeting', 'meeting' => $meeting, 'user' => $user));
     // valiadate the form if POST
     if (!empty($formParams)) {
         if ($form->isValid($formParams)) {
             // get the form values
             $values = $form->getValues();
             $values['meeting_id'] = $meeting['id'];
             $values['details'] = array();
             foreach ($meeting['participant_detail_keys'] as $keyId => $detailKey) {
                 if (is_array($values[$detailKey['key']])) {
                     $values['details'][$keyId] = Zend_Json::encode($values[$detailKey['key']]);
                 } else {
                     if ($values[$detailKey['key']] === null) {
                         $values['details'][$keyId] = Zend_Json::encode(array());
                     } else {
                         $values['details'][$keyId] = $values[$detailKey['key']];
                     }
                 }
                 unset($values[$detailKey['key']]);
             }
             $values['contributions'] = array();
             foreach ($meeting['contribution_types'] as $contributionTypeId => $contributionType) {
                 if ($values[$contributionType . '_bool'] === '1') {
                     $values['contributions'][$contributionTypeId] = array('title' => $values[$contributionType . '_title'], 'abstract' => $values[$contributionType . '_abstract']);
                 } else {
                     $values['contributions'][$contributionTypeId] = false;
                 }
                 unset($values[$contributionType . '_bool']);
                 unset($values[$contributionType . '_title']);
                 unset($values[$contributionType . '_abstract']);
             }
             // get the right status
             $participantStatusModel = new Meetings_Model_ParticipantStatus();
             if (empty(Daiquiri_Config::getInstance()->meetings->autoAccept)) {
                 $values['status_id'] = $participantStatusModel->getResource()->fetchId(array('where' => array('`status` = "registered"')));
             } else {
                 $values['status_id'] = $participantStatusModel->getResource()->fetchId(array('where' => array('`status` = "accepted"')));
             }
             if (Daiquiri_Config::getInstance()->meetings->validation) {
                 $code = $this->createRandomString(32);
                 // store the values in the database
                 $id = $this->getResource()->insertRow(array('email' => $values['email'], 'code' => $code, 'values' => Zend_Json::encode($values), 'meeting_id' => $meeting['id']));
                 // prepare and send mail
                 $link = Daiquiri_Config::getInstance()->getSiteUrl() . '/meetings/registration/validate/id/' . $id . '/code/' . $code;
                 $this->getModelHelper('mail')->send('meetings.validate', array('to' => $values['email'], 'meeting' => $meeting['title'], 'firstname' => $values['firstname'], 'lastname' => $values['lastname'], 'link' => $link));
                 return array('status' => 'validate');
             } else {
                 $participantModel = new Meetings_Model_Participants();
                 $id = $participantModel->getResource()->insertRow($values);
                 $participant = $participantModel->getResource()->fetchRow($id);
                 $mailValues = array('to' => $participant['email'], 'meeting' => $meeting['title'], 'firstname' => $participant['firstname'], 'lastname' => $participant['lastname'], 'affiliation' => $participant['affiliation'], 'email' => $participant['email'], 'arrival' => $participant['arrival'], 'departure' => $participant['departure']);
                 foreach ($meeting['participant_detail_keys'] as $d) {
                     if (in_array(Meetings_Model_ParticipantDetailKeys::$types[$d['type_id']], array('radio', 'select'))) {
                         $options = Zend_Json::decode($d['options']);
                         $mailValues[$d['key']] = $options[$participant['details'][$d['key']]];
                     } else {
                         if (in_array(Meetings_Model_ParticipantDetailKeys::$types[$d['type_id']], array('checkbox', 'multiselect'))) {
                             $options = Zend_Json::decode($d['options']);
                             $values = array();
                             foreach (Zend_Json::decode($participant['details'][$d['key']]) as $value_id) {
                                 $values[] = $options[$value_id];
                             }
                             $mailValues[$d['key']] = implode(', ', $values);
                         } else {
                             $mailValues[$d['key']] = $participant['details'][$d['key']];
                         }
                     }
                 }
                 foreach ($meeting['contribution_types'] as $contribution_type) {
                     if (!empty($participant['contributions'][$contribution_type])) {
                         $mailValues[$contribution_type . '_title'] = $participant['contributions'][$contribution_type]['title'];
                         $mailValues[$contribution_type . '_abstract'] = $participant['contributions'][$contribution_type]['abstract'];
                     } else {
                         $mailValues[$contribution_type . '_title'] = '---';
                     }
                 }
                 $this->getModelHelper('mail')->send('meetings.register', $mailValues);
                 return array('status' => 'ok');
             }
         } else {
             return $this->getModelHelper('CRUD')->validationErrorResponse($form);
         }
     }
     return array('form' => $form, 'status' => 'form', 'message' => $meeting['registration_message']);
 }
Example #25
0
 /**
  * Checks whether the user can access this table
  * @param string $database the name of the database
  * @param string $table the name of the table
  * @param string $command SQL command
  * @return bool
  */
 public function checkACL($database, $table, $command)
 {
     if (empty($database) || empty($table) || empty($command)) {
         throw new Exception('$database, $table or $command not provided in ' . get_class($this) . '::' . __FUNCTION__ . '()');
     }
     $select = $this->select();
     $select->from('Data_Tables');
     $select->join('Data_Databases', '`Data_Databases`.`id` = `Data_Tables`.`database_id`', array());
     $select->where("`Data_Databases`.`name` = ?", trim($database));
     $select->where("`Data_Tables`.`name` = ?", trim($table));
     $row = $this->fetchOne($select);
     if (empty($row)) {
         return false;
     }
     $command = strtolower($command);
     // check if the database is published for this role
     $result = Daiquiri_Auth::getInstance()->checkPublicationRoleId($row['publication_role_id']);
     if (($command === "select" || $command === "set") && $row['publication_select'] === "1") {
         return $result;
     } else {
         if (($command === "alter" || $command === "update") && $row['publication_update'] === "1") {
             return $result;
         } else {
             if (($command === "create" || $command === "drop" || $command === "insert") && $row['publication_insert'] === "1") {
                 return $result;
             } else {
                 return false;
             }
         }
     }
 }
Example #26
0
 /**
  * Creates a downloadable file from the given table of the users database
  * @param string $table table in the users database
  * @param string $suffix
  * @return array $response
  */
 private function _createDownloadFile($table, $format, $regen = false)
 {
     // sanity check for format
     if (!in_array($format, Daiquiri_Config::getInstance()->query->download->adapter->enabled->toArray())) {
         throw new Exception('Error: format not valid.');
     }
     // create link and file sysytem path for table dump
     $username = Daiquiri_Auth::getInstance()->getCurrentUsername();
     $suffix = Daiquiri_Config::getInstance()->query->download->adapter->config->{$format}->suffix;
     $filename = $this->_generateFileName($table, $suffix);
     $url = '/query/download/file?table=' . $table . '&format=' . $format;
     $dir = Daiquiri_Config::getInstance()->query->download->dir . DIRECTORY_SEPARATOR . $username;
     $file = $dir . DIRECTORY_SEPARATOR . $filename;
     // get queue type and validate
     $queueType = strtolower(Daiquiri_Config::getInstance()->query->download->type);
     if ($queueType !== "direct" and $queueType !== "gearman") {
         throw new Exception('Download queue type not valid');
     }
     // create dir if neccessary
     if (!is_dir($dir)) {
         if (mkdir($dir) === false) {
             return array('status' => 'error', 'error' => 'Configuration of download directory wrong, please contact support.');
         }
         chmod($dir, 0775);
     }
     // delete the old file if regen is set
     if ($regen === true) {
         if (file_exists($file . ".lock")) {
             throw new Daiquiri_Exception_Forbidden();
         }
         // delete the files...
         if (file_exists($file)) {
             unlink($file);
         }
         if (file_exists($file . ".err")) {
             unlink($file . ".err");
         }
     }
     if (!file_exists($file) && ($queueType === "direct" || empty($queueType))) {
         //get the user db name
         $username = Daiquiri_Auth::getInstance()->getCurrentUsername();
         $db = Daiquiri_Config::getInstance()->getUserDbName($username);
         // get the resource and create dump
         $resource = new Data_Model_Resource_Viewer();
         $resource->init($db, $table);
         try {
             $resource->dumpTable($format, $file);
         } catch (Exception $e) {
             return array('status' => 'error', 'error' => array('form' => $e->getMessage() . ' Please contact support.'));
         }
     }
     if ((!file_exists($file) || file_exists($file . ".lock")) && $queueType === "gearman") {
         // check if gearman is up and running
         exec('pgrep gearmand', $output, $return);
         if ($return != 0) {
             throw new Exception('gearmand is not running.');
         }
         // check if
         $restartGeamanManager = false;
         $pidfile = Daiquiri_Config::getInstance()->query->download->gearman->pid;
         if (file_exists($pidfile)) {
             $pid = file_get_contents($pidfile);
             exec('ps -p ' . $pid, $output, $return);
             if ($return != 0) {
                 $restartGeamanManager = true;
             }
         } else {
             $restartGeamanManager = true;
         }
         if ($restartGeamanManager) {
             // check if we have write access to actually create this PID file
             if (!is_writable(dirname(Daiquiri_Config::getInstance()->query->download->gearman->pid))) {
                 return array('status' => 'error', 'error' => 'Cannot write to the gearman PID file, please contact support.');
             }
             $gearmanConf = Daiquiri_Config::getInstance()->query->download->gearman;
             // not there, start GearmanManager
             $cmd = escapeshellcmd($gearmanConf->manager) . ' -d' . ' -D ' . escapeshellcmd($gearmanConf->numThread) . ' -h ' . escapeshellcmd($gearmanConf->host) . ':' . escapeshellcmd($gearmanConf->port) . ' -P ' . escapeshellcmd($gearmanConf->pid) . ' -w ' . escapeshellcmd($gearmanConf->workerDir) . ' -r 1 > /tmp/Daiquiri_GearmanManager.log &';
             shell_exec($cmd);
             // DOES NOT WORK IN NEWER PHP, NEED TO BE FIXED
             // http://stackoverflow.com/questions/12322811/call-time-pass-by-reference-has-been-removed
             // check if pid exists, if not, an error occured - wait for 10 seconds to start gearman manager
             $count = 0;
             while (!file_exists($gearmanConf->pid)) {
                 $count += 1;
                 sleep(1);
                 if ($count > 10) {
                     throw new Exception('Error: Could not start GearmanManager.');
                 }
             }
         }
         // check if lockfile is present and if not, create
         if (!file_exists($file . ".lock")) {
             if (file_exists($file . ".err")) {
                 return array('status' => 'error', 'error' => 'An error file exists on the server, please contact support.');
             }
             // write lock file
             touch($file . ".lock");
             // get the user db name
             $username = Daiquiri_Auth::getInstance()->getCurrentUsername();
             $db = Daiquiri_Config::getInstance()->getUserDbName($username);
             // get the resource and create dump
             $resource = new Data_Model_Resource_Viewer();
             $resource->init($db, $table);
             try {
                 $resource->dumpTableGearman($format, $file);
             } catch (Exception $e) {
                 unlink($file . ".lock");
                 return array('status' => 'error', 'error' => array('form' => $e->getMessage() . ' Please contact support.'));
             }
             return array('status' => 'pending', 'format' => $format);
         } else {
             return array('status' => 'pending', 'format' => $format);
         }
     }
     return array('status' => 'ok', 'link' => Daiquiri_Config::getInstance()->getSiteUrl() . $url, 'format' => $format);
 }
Example #27
0
 /**
  * Returns all tables for export.
  * @return array $response
  */
 public function export()
 {
     // get databases
     $databasesModel = new Data_Model_Databases();
     $databases = $databasesModel->getResource()->fetchValues('name');
     $rows = array();
     foreach ($this->getResource()->fetchRows() as $dbRow) {
         $rows[] = array('database' => $databases[$dbRow['database_id']], 'name' => $dbRow['name'], 'order' => $dbRow['order'], 'description' => $dbRow['description'], 'publication_select' => $dbRow['publication_select'], 'publication_update' => $dbRow['publication_update'], 'publication_insert' => $dbRow['publication_insert'], 'publication_role' => Daiquiri_Auth::getInstance()->getRole($dbRow['publication_role_id']));
     }
     return array('data' => array('tables' => $rows), 'status' => 'ok');
 }
Example #28
0
 /**
  * Edits the password of the currenly logged in user.
  * @param array $formParams
  * @return array $response
  */
 public function change(array $formParams = array())
 {
     // get the id of the user from the request
     $userId = Daiquiri_Auth::getInstance()->getCurrentId();
     // create the form object
     $form = new Auth_Form_ChangePassword();
     // valiadate the form if POST
     if (!empty($formParams)) {
         if ($form->isValid($formParams)) {
             // get the form values
             $values = $form->getValues();
             // get the user credentials
             $user = $this->getResource()->fetchRow($userId);
             // check if the old password is valid
             $result = Daiquiri_Auth::getInstance()->authenticateUser($user['username'], $values['old_password']);
             if ($result) {
                 // update the user and redirect
                 $this->getResource()->updatePassword($userId, $values['new_password']);
                 // log the event
                 Daiquiri_Log::getInstance()->notice('password changed by user');
                 // send a notification mail
                 if (Daiquiri_Config::getInstance()->auth->notification->changePassword) {
                     $this->getModelHelper('mail')->send('auth.changePassword', array('to' => Daiquiri_Config::getInstance()->auth->notification->mail->toArray(), 'id' => $user['id'], 'username' => $user['username'], 'firstname' => $user['details']['firstname'], 'lastname' => $user['details']['lastname']));
                 }
                 return array('status' => 'ok');
             } else {
                 return $this->getModelHelper('CRUD')->validationErrorResponse($form, 'Wrong (old) password provided');
             }
         } else {
             return $this->getModelHelper('CRUD')->validationErrorResponse($form);
         }
     }
     return array('form' => $form, 'status' => 'form');
 }
Example #29
0
 /**
  * Returns the filename of the static content or raises an exception.
  * @param  string $alias static file alias
  * @param  string $path  url path of the file
  * @return array $response
  */
 public function file($alias, $path)
 {
     // look for matching static entry
     $row = $this->getResource()->fetchRow(array('where' => array('alias = ?' => $alias)));
     // check if the row is there
     if (empty($row)) {
         throw new Daiquiri_Exception_NotFound();
     }
     // check permissions
     if (Daiquiri_Auth::getInstance()->checkPublicationRoleId($row['publication_role_id']) !== true) {
         throw new Daiquiri_Exception_Unauthorized();
     }
     // create absolute file path
     $file = realpath($row['path'] . $path);
     // ensure that the file is not BELOW the give path
     if ($file === false || strpos($file, rtrim($row['path'], '/')) !== 0) {
         throw new Daiquiri_Exception_NotFound();
     }
     // see if the file is there
     if (is_file($file)) {
         return array('status' => 'ok', 'file' => $file);
     } elseif (is_dir($file)) {
         // look for and index file
         $file .= '/index.html';
         if (is_file($file)) {
             return array('status' => 'ok', 'file' => $file);
         } else {
             throw new Daiquiri_Exception_NotFound();
         }
     } else {
         throw new Daiquiri_Exception_NotFound();
     }
 }
Example #30
0
 /**
  * Add a hash element for security against CSRF attacks.
  * @param  string $name name of the element
  * @return mixed  $name name of the element or 'false'
  */
 public function addCsrfElement($name = 'csrf')
 {
     if (php_sapi_name() !== 'cli' && Daiquiri_Auth::getInstance()->useCsrf()) {
         $this->addElement(new Daiquiri_Form_Element_Csrf($name));
         return $name;
     } else {
         return false;
     }
 }