/**
  * Set redirect expiration hops
  *
  * @param integer $hops
  */
 public function setExpirationHops($hops = 1)
 {
     // Store setting
     $this->_expirationHops[$this->getNamespace()] = $hops;
     // Set hops
     self::$_session->setExpirationHops((int) $hops, $this->getNamespace());
 }
 /**
  * Initialize session
  */
 protected function _initSes()
 {
     $ses = new \Zend_Session_Namespace(self::SESSION_NAMESPACE, true);
     $ses->setExpirationHops(5, null, true);
     $ses->setExpirationSeconds(60 * 60 * 24);
     $this->_ses = $ses;
 }
Beispiel #3
0
 /**
  * Return checkout data storage
  *
  * @return Zend_Session_Namespace
  */
 public function getStorage()
 {
     if (null === $this->_storage) {
         $this->_storage = Axis::session($this->_code . '-Checkout');
         $this->_storage->setExpirationSeconds(600);
         $this->_storage->setExpirationHops(5);
     }
     return $this->_storage;
 }
Beispiel #4
0
 /**
  * Return checkout data storage
  *
  * @return Zend_Session_Namespace
  */
 public function getStorage()
 {
     if (null === $this->_storage) {
         $this->_storage = new Zend_Session_Namespace($this->_code . '-Checkout');
         $this->_storage->setExpirationSeconds(600);
         $this->_storage->setExpirationHops(5);
     }
     return $this->_storage;
 }
Beispiel #5
0
 /**
  * Get session object
  *
  * @return Zend_Session_Namespace
  */
 public function getSession()
 {
     if (!isset($this->_session) || null === $this->_session) {
         $id = $this->getId();
         $this->_session = new $this->_sessionClass('Zend_Form_Captcha_' . $id);
         $this->_session->setExpirationHops(1, null, true);
         $this->_session->setExpirationSeconds($this->getTimeout());
     }
     return $this->_session;
 }
 /**
  * addMessage() - Add a message to flash message
  *
  * @param string $message
  * @param string $namespace OPTIONAL
  */
 public function addMessage($message, $namespace = null)
 {
     $namespace = isset($namespace) ? (string) $namespace : $this->_namespace;
     if (self::$_messageAdded === false) {
         self::$_sessionNamespace->setExpirationHops(1, null, true);
     }
     if (!is_array(self::$_sessionNamespace->{$namespace})) {
         self::$_sessionNamespace->{$namespace} = array();
     }
     self::$_sessionNamespace->{$namespace}[] = $message;
     return;
 }
 public function indexAction()
 {
     //$this->_helper->layout ()->disableLayout ();
     $auth = Zend_Auth::getInstance();
     $authContent = $auth->getStorage()->read();
     $authAcl = new Zend_Session_Namespace('authAcl');
     $guestID = Authz_Resource_Acl_Guest::GUEST_ID;
     if (is_array($authContent) and $authContent['identity'] != $guestID) {
         return;
     }
     $loginForm = new Auth_Form_Auth_Login($_POST);
     $authAdapter = null;
     if ($this->getRequest()->isPost() and $loginForm->isValid($_POST)) {
         $authService = 'DbTable';
         switch (strtolower($authService)) {
             case 'dbtable':
                 $db = $this->_getParam('db');
                 $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'auth_user', 'user_id', 'sec_passwd');
                 $authAdapter->setIdentity($loginForm->getValue('username'));
                 $authAdapter->setCredential($loginForm->getValue('password'));
                 break;
             case 'ldap':
                 /*TODO Implement LDAP auth */
                 break;
             default:
                 throw new Zend_Exception('Unknown authentication service -> ' . $authService, Zend_Log::ALERT);
         }
         $result = Zend_Auth::getInstance()->authenticate($authAdapter);
         //$this->_helper->logger->debug ( $result );
         switch ($result->getCode()) {
             case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
             case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                 break;
             case Zend_Auth_Result::SUCCESS:
                 Zend_Session::regenerateId();
                 preg_match('/[^.]+\\.[^.]+$/', $_SERVER['SERVER_NAME'], $domain);
                 setcookie(self::AUTH_SID, Zend_Session::getId(), time() + 1200, self::AUTH_PATH, ".{$domain['0']}", null, true);
                 $last = time();
                 setcookie('last', $last, null, '/', ".{$domain['0']}", null, true);
                 $lastLogin = new Zend_Session_Namespace('last');
                 $lastLogin->lastLogin = $last;
                 $lastLogin->setExpirationHops(1, null, 1);
                 $authAcl = new Zend_Session_Namespace('authAcl');
                 $authAcl->authId = $loginForm->getValue('username');
                 $this->_helper->redirector('index', 'index');
                 return;
             default:
                 /** do stuff for other failure **/
                 break;
         }
     }
     $this->view->form = $loginForm;
 }
Beispiel #8
0
 /**
  * Get session object
  *
  * @return Zend_Session_Namespace
  */
 public function getSession()
 {
     if (!isset($this->_session) || null === $this->_session) {
         $id = $this->getId();
         if (!class_exists($this->_sessionClass)) {
             #require_once 'Zend/Loader.php';
             Zend_Loader::loadClass($this->_sessionClass);
         }
         $this->_session = new $this->_sessionClass('Zend_Form_Captcha_' . $id);
         $this->_session->setExpirationHops(1, null, true);
         $this->_session->setExpirationSeconds($this->getTimeout());
     }
     return $this->_session;
 }
Beispiel #9
0
 public function token($class = null, $element = null, $salt = null)
 {
     if (null === $class) {
         $class = 'Zend_Form_Element_Hash';
     }
     if (null === $element) {
         $element = 'token';
     }
     if (null === $salt) {
         $salt = 'salt';
     }
     $session = new Zend_Session_Namespace($class . '_' . $salt . '_' . $element);
     $session->setExpirationHops(1, null, true);
     $session->setExpirationSeconds(300);
     $session->hash = md5(mt_rand(1, 1000000) . $salt . $element . mt_rand(1, 1000000));
     return $session->hash;
 }
 private function login($userName, $password)
 {
     $authService = 'DbTable';
     switch (strtolower($authService)) {
         case 'dbtable':
             $db = $this->_getParam('db');
             $authAdapter = new Zend_Auth_Adapter_DbTable($db, 'auth_user', 'login_id', 'sec_passwd');
             $authAdapter->setIdentity($userName);
             $authAdapter->setCredential($password);
             break;
         case 'ldap':
             /*TODO Implement LDAP auth */
             break;
         default:
             throw new Zend_Exception('Unknown authentication service -> ' . $authService, Zend_Log::ALERT);
     }
     $result = Zend_Auth::getInstance()->authenticate($authAdapter);
     //$this->_helper->logger->debug ( $result );
     switch ($result->getCode()) {
         case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
         case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
             echo 'Incorrect User Name or Password.';
             break;
         case Zend_Auth_Result::SUCCESS:
             Zend_Session::regenerateId();
             preg_match('/[^.]+\\.[^.]+$/', $_SERVER['SERVER_NAME'], $domain);
             setcookie(self::AUTH_SID, Zend_Session::getId(), time() + 1200, self::AUTH_PATH, ".{$domain['0']}", null, true);
             $last = time();
             setcookie('last', $last, null, '/', ".{$domain['0']}", null, true);
             $lastLogin = new Zend_Session_Namespace('last');
             $lastLogin->lastLogin = $last;
             $lastLogin->setExpirationHops(1, null, 1);
             $authAcl = new Zend_Session_Namespace('authAcl');
             $authAcl->authId = $userName;
             //Zend_Registry::get('logger')->debug($authAcl->authId);
             $this->_helper->redirector('markauth', 'index');
             return;
         default:
             /** do stuff for other failure **/
             break;
     }
 }
Beispiel #11
0
 /**
  * test expiration of namespace variables by hops; expect expiration of specified keys in the proper number of hops
  *
  * @return void
  */
 public function testSetExpireSessionVarsByHopsOnUse()
 {
     if (strtolower(substr(PHP_OS, 0, 3)) === 'win') {
         $this->markTestIncomplete('Fails on Windows, see ZF-2629');
     }
     $s = new Zend_Session_Namespace('expireGuava');
     $expireBeforeHop = 2;
     $s->setExpirationHops($expireBeforeHop, 'g', true);
     // only count a hop, when namespace is used
     $s->g = 'guava';
     $s->p = 'peach';
     $s->p = 'plum';
     $id = session_id();
     session_write_close();
     // release session so process below can use it
     // we are not accessing (using) the "expireGuava" namespace, so these hops should have no effect
     for ($i = 1; $i <= $expireBeforeHop + 2; $i++) {
         exec("{$this->_script} expireAll {$id} notused", $result);
         $result = $this->sortResult($result);
         $this->assertTrue($result === '', "iteration over named Zend_Session namespace failed (result='{$result}'; hop #{$i})");
     }
     for ($i = 1; $i <= $expireBeforeHop + 2; $i++) {
         exec("{$this->_script} expireAll {$id} expireGuava", $result);
         $result = $this->sortResult($result);
         if ($i > $expireBeforeHop) {
             $expect = ';p === plum';
             $this->assertTrue($result === $expect, "unexpected results iterating over named Zend_Session namespace (result='{$result}'; expected '{$expect}'; hop #{$i})");
         } else {
             $expect = ';g === guava;p === plum';
             $this->assertTrue($result === $expect, "unexpected results iterating over named Zend_Session namespace (result='{$result}'; expected '{$expect}'; hop #{$i})");
         }
     }
     session_start();
     // resume artificially suspended session
     Zend_Session::destroy();
 }
 public function contentAction()
 {
     $this->view->messages = $this->_helper->flashMessenger->getMessages();
     $url = $this->_getParam('url');
     $proxy = new SxCms_Page_Proxy();
     $page = $proxy->getPageByUrl($url, null, $this->_getParam('lng', 'nl'));
     if ($page->getId() === false) {
         throw new Zend_Controller_Action_Exception('Page not found', 404);
     }
     $identity = Zend_Auth::getInstance()->getIdentity();
     if (!$page->isAllowed($identity)) {
         $this->_forward('unauthorized', 'index', null, array('url' => $this->view->url()));
         return;
     }
     if ($page->isExpired()) {
         throw new Zend_Controller_Action_Exception('Page expired', 404);
     }
     if ($page->getInvisible()) {
         throw new Zend_Controller_Action_Exception('Page expired', 404);
     }
     /** Gebruik Nederlandse vertaling indien nodig * */
     if ($page->hasContentFallback()) {
         $pageFallback = $proxy->getPageById($page->getId(), 'nl');
         $page->setContent($pageFallback->getContent());
     }
     $this->view->page = $page;
     $this->_helper->layout->setLayout($page->getLayout());
     if ($page->getType() == SxCms_Page::SUMMARY) {
         $children = $proxy->getPagesByParentId($page->getId(), null, $this->_getParam('lng', 'nl'), true, true);
         $childrenArr = array();
         foreach ($children as $child) {
             $pageFallback = false;
             if ($child->hasSummaryFallback()) {
                 $pageFallback = $proxy->getPageById($child->getId(), 'nl');
                 $child->setSummary($pageFallback->getSummary());
             }
             array_push($childrenArr, $child);
         }
         $this->view->children = $childrenArr;
         $this->renderScript('index/summary.phtml');
         return;
     }
     if ($page->getType() == SxCms_Page::ARTICLE) {
         $this->view->comment = new SxCms_Comment();
         $captchaSession = new Zend_Session_Namespace('captcha');
         $captchaSession->setExpirationHops(3);
         if ($captchaSession->token) {
             $captcha = $captchaSession->token;
         } else {
             $captcha = new Zend_Captcha_Image();
             $captcha->setName('captcha')->setWordLen(6)->setDotNoiseLevel(20)->setLineNoiseLevel(0)->setFont(APPLICATION_PATH . '/var/fonts/BRLNSR.TTF')->setImgDir(APPLICATION_ROOT . '/public_html/images/captcha');
             $captcha->generate();
             $captchaSession->token = $captcha;
         }
         $this->view->captcha = $captcha;
     }
     if ($page->getPageform()) {
         if ($this->getRequest()->isGet()) {
             $this->view->captchaId = $this->generateCaptcha();
         }
         $pageformproxy = new SxModule_Pageform_Proxy();
         $subscription = new SxModule_Pageform_Subscription();
         $pageform = $pageformproxy->getActiveById($page->getPageform(), $_SESSION['System']['lng']);
         $this->view->pageform = $pageform;
         if ($this->getRequest()->isPost() && $this->_getParam('comment-submit')) {
             $this->view->errors = array();
             $validator = new SxCms_Comment_BaseValidator();
             $validator->setCaptcha($captcha)->setUserCaptcha($this->_getParam('captcha'));
             $comment = new SxCms_Comment();
             $comment->setMessage($this->_getParam('message'));
             $author = new SxCms_Comment_Author();
             $author->setName($this->_getParam('name'))->setEmail($this->_getParam('email'))->setWebsite($this->_getParam('website'));
             $comment->setPage($page);
             $comment->setCommenter($author);
             if (!$validator->validate($comment)) {
                 $this->view->errors = $validator->getErrors();
                 $this->view->comment = $comment;
                 $this->view->userCaptcha = $this->_getParam('captcha');
             } else {
                 $mapper = new SxCms_Comment_DataMapper();
                 $mapper->save($comment);
                 $captchaSession->unsetAll();
                 $this->_helper->flashMessenger->addMessage('Uw bericht werd succcesvol verwerk.
                 Na goedkeuring door een administrator zal dit op de website verschijnen.');
                 $this->_helper->redirector->gotoRoute(array('url' => $page->getLink()), 'content');
             }
         }
         if ($this->getRequest()->isPost() && $this->_getParam('pageform-submit')) {
             $data = $this->_getParam('pageform');
             $subscription->setPageformId($pageform->getId())->setPageformname($pageform->getName())->setIp($this->getRequest()->getServer('REMOTE_ADDR'))->setAgent($this->getRequest()->getServer('HTTP_USER_AGENT'))->setLng($this->_getParam('lng'))->setUrl('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
             foreach ($pageform->getField() as $field) {
                 if (isset($data[$field->getKey()])) {
                     # Tijd instellen
                     if ($field->getFieldType() == 'text' && $field->getValidation() == 'time' && is_array($data[$field->getKey()])) {
                         $data[$field->getKey()] = $data[$field->getKey()]['hh'] . ':' . $data[$field->getKey()]['mm'];
                     }
                     # Tijd & datum instellen
                     if ($field->getFieldType() == 'text' && $field->getValidation() == 'datetime' && is_array($data[$field->getKey()])) {
                         $data[$field->getKey()] = $data[$field->getKey()]['date'] . ' ' . $data[$field->getKey()]['hh'] . ':' . $data[$field->getKey()]['mm'];
                     }
                 }
                 $metaObject = new SxModule_Pageform_Subscription_Meta();
                 $metaObject->setFieldId($field->getId())->setLabel($field->getTsl()->getName())->setName($field->getKey())->setValue(isset($data[$field->getKey()]) ? $data[$field->getKey()] : null);
                 $subscription->addMeta($metaObject);
             }
             $fielderrors = APPLICATION_ROOT . '/application/var/locale/fielderrors.tmx';
             $validator = new SxModule_Pageform_Subscription_Validator();
             $validator->setTmx(new Zend_Translate('tmx', $fielderrors, $_SESSION['System']['lng']));
             //$validator->setTmx( new Zend_Translate('tmx', APPLICATION_ROOT . '/application/var/locale/pageform.tmx', $_SESSION['System']['lng']) );
             $captchaOk = true;
             if ($pageform->getCaptcha()) {
                 $captchaOk = false;
                 $captcha = $this->_getParam('captcha');
                 if ($this->validateCaptcha($captcha)) {
                     $captchaOk = true;
                 }
             }
             $this->view->captchaId = $this->generateCaptcha();
             if ($captchaOk) {
                 if ($validator->validate($subscription, $pageform)) {
                     $subscription->save();
                     if ($pageform->getMailoption() == 1) {
                         $mail = new Zend_Mail('utf-8');
                         $mail->setSubject('Formulier verzonden op website: ' . $pageform->getName())->setFrom(Zend_Registry::get('config')->company->email, "formulier: " . $pageform->getName());
                         $body = 'Datum : ' . date('Y-m-d H:i:s') . "\n";
                         foreach ($subscription->getMeta() as $meta) {
                             $body .= " " . $meta->getLabel() . ": " . $meta->getValue() . "\n";
                         }
                         $mail->setBodyText($body);
                         $mail->addTo($pageform->getMailto());
                         $mail->send();
                     }
                     if ($pageform->getTsl()->getConfirm() == 1) {
                         foreach ($subscription->getMeta() as $meta) {
                             if ($meta->getLabel() == $pageform->getTsl()->getConfirmto()) {
                                 $sendto = $meta->getValue();
                             }
                         }
                         $mail = new Zend_Mail('utf-8');
                         $mail->setSubject($pageform->getTsl()->getConfirmsubject())->setFrom(Zend_Registry::get('config')->company->email, Zend_Registry::get('config')->company->name);
                         $mail->setBodyHtml($pageform->getTsl()->getConfirmcontent());
                         $mail->addTo($sendto);
                         $mail->send();
                     }
                     $subscription = new SxModule_Pageform_Subscription();
                     $this->view->message = "Formulier verzonden!";
                 } else {
                     $this->view->error = "Er ging iets mis...";
                     //var_dump($subscription->getMeta());
                     //exit;
                 }
             } else {
                 $this->view->error = "Neem de captcha code correct over...";
             }
         }
         $this->view->subscription = $subscription;
     }
     $this->view->mode = $this->_getParam('mode') ? $this->_getParam('mode') : '';
     $this->view->messages = Sanmax_MessageStack::getInstance('SxModule_Pageform_Subscription');
 }
 /**
  * Helper to generate csv file.
  */
 private function _generateCsv($args)
 {
     // Get variables from args array passed into detached process.
     $fileImport = $args['file_import'];
     $xmlFolder = $args['xml_folder'];
     $formatFilename = $args['format_filename'];
     if ($fileImport == 'file') {
         $fileList = $args['file_list'];
     } else {
         $fileList = $this->_listRecursiveDirectory($xmlFolder, $formatFilename, $fileImport == 'recursive');
     }
     $csvFilename = $args['csv_filename'];
     $format = $args['format'];
     $action = $args['action'];
     $identifierField = $args['identifier_field'];
     $itemTypeId = $args['item_type_id'];
     $collectionId = $args['collection_id'];
     $recordsArePublic = $args['public'];
     $recordsAreFeatured = $args['featured'];
     $elementsAreHtml = $args['html_elements'];
     $createCollections = $args['create_collections'];
     $containsExtraData = $args['extra_data'];
     $tagName = $args['tag_name'];
     $columnDelimiter = $args['column_delimiter'];
     $enclosure = $args['enclosure'];
     $elementDelimiter = $args['element_delimiter'];
     $tagDelimiter = $args['tag_delimiter'];
     $fileDelimiter = $args['file_delimiter'];
     $stylesheet = $args['stylesheet'];
     $stylesheetParameters = $args['stylesheet_parameters'];
     // Delimiters for Csv Report are fixed.
     if ($format == 'Report') {
         $columnDelimiter = ',';
         $enclosure = '"';
         $elementDelimiter = CsvImport_ColumnMap_ExportedElement::DEFAULT_ELEMENT_DELIMITER;
         $tagDelimiter = ',';
         $fileDelimiter = ',';
     }
     $endOfLine = "\n";
     // No paramater for this option: fields are always automapped.
     $automapColumns = 1;
     $csvFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'omeka_xml_import_' . date('Ymd-His') . '_' . $this->_sanitizeString($csvFilename) . '.csv';
     $csvFilename = 'Via Xml Import: ' . $csvFilename;
     // Prepare parameters for the stylesheet.
     $parameters = array('delimiter' => $columnDelimiter, 'enclosure' => $enclosure, 'delimiter_element' => $elementDelimiter, 'delimiter_tag' => $tagDelimiter, 'delimiter_file' => $fileDelimiter, 'end_of_line' => $endOfLine, 'node' => $tagName);
     if ($format == 'Manage') {
         $parameters['identifier_field'] = $identifierField;
     }
     // Add custom parameters. Allowed types are already checked.
     $parametersAdded = trim($stylesheetParameters) == '' ? array() : array_values(array_map('trim', explode('><', trim($stylesheetParameters, ' <>'))));
     foreach ($parametersAdded as $value) {
         if (strpos($value, '=') !== FALSE) {
             list($paramName, $paramValue) = explode('=', $value);
             if ($paramName != '') {
                 $parameters[trim($paramName)] = trim($paramValue);
             }
         }
     }
     try {
         // Flag used to keep or remove headers in the first row.
         $flag_first = TRUE;
         // Convert each xml file to csv with the selected stylesheet and
         // parameters. A result can be empty for a file when there are no
         // metadata to import or if the xml file is not a good one.
         foreach ($fileList as $filepath => $filename) {
             // Let headers only for the first file.
             if ($flag_first) {
                 $flag_first = FALSE;
             } else {
                 $parameters['headers'] = 'false';
             }
             $result = $this->_apply_xslt_and_save($filepath, $stylesheet, '', $parameters);
             if ($result === NULL) {
                 $this->_helper->flashMessenger(__('Error when transforming xml file "%s" with the xsl sheet "%s".', $filepath, $stylesheet), 'error');
                 $this->_helper->redirector->goto('index');
             }
             $output = $result;
             // @todo Use Zend/Omeka api.
             $result = $this->_append_file($csvFilePath, $output);
             if ($result === FALSE) {
                 $this->_helper->flashMessenger(__('Error saving data, because the filepath "%s" is not writable.', $filepath), 'error');
                 $this->_helper->redirector->goto('index');
             }
         }
         // Check final resulted file.
         if (filesize($csvFilePath) == 0) {
             $this->_helper->flashMessenger(__('The conversion of the xml file "%s" to csv via the xslt style sheet "%s" gives an empty file. Check your options and your files.', basename($filepath), basename($stylesheet)), 'error');
             $this->_helper->redirector->goto('index');
         }
         // Get the view.
         $view = $this->view;
         // Set up CsvImport validation and column mapping if needed.
         $file = XmlImportPlugin::isFullCsvImport() ? new CsvImport_File($csvFilePath, $columnDelimiter, $enclosure) : new CsvImport_File($csvFilePath, $columnDelimiter);
         if (!$file->parse()) {
             $msg = __('Your CSV file is incorrectly formatted.') . ' ' . $file->getErrorString();
             $this->_helper->flashMessenger($msg, 'error');
             $this->_helper->redirector->goto('index');
         }
         // Go directly to the correct view of CsvImport plugin.
         $csvImportSession = new Zend_Session_Namespace('CsvImport');
         // @see CsvImport_IndexController::indexAction().
         $csvImportSession->setExpirationHops(2);
         $csvImportSession->originalFilename = $csvFilename;
         $csvImportSession->filePath = $csvFilePath;
         // Option used with full Csv Import only.
         $csvImportSession->format = $format;
         $csvImportSession->action = $action;
         $csvImportSession->identifierField = $identifierField;
         $csvImportSession->itemTypeId = $itemTypeId;
         $csvImportSession->collectionId = $collectionId;
         if (XmlImportPlugin::isFullCsvImport()) {
             $csvImportSession->recordsArePublic = $recordsArePublic;
             $csvImportSession->recordsAreFeatured = $recordsAreFeatured;
         } else {
             $csvImportSession->itemsArePublic = $recordsArePublic;
             $csvImportSession->itemsAreFeatured = $recordsAreFeatured;
         }
         // Options used with full Csv Import only.
         $csvImportSession->elementsAreHtml = $elementsAreHtml;
         $csvImportSession->createCollections = $createCollections;
         $csvImportSession->automapColumns = $automapColumns;
         $csvImportSession->containsExtraData = $containsExtraData;
         // Options used with Csv Import standard only.
         $csvImportSession->automapColumnNamesToElements = $automapColumns;
         $csvImportSession->columnDelimiter = $columnDelimiter;
         $csvImportSession->enclosure = $enclosure;
         $csvImportSession->columnNames = $file->getColumnNames();
         $csvImportSession->columnExamples = $file->getColumnExamples();
         // A bug appears in CsvImport when examples contain UTF-8 characters
         // like 'ГЧ„чŁ'.
         foreach ($csvImportSession->columnExamples as &$value) {
             $value = iconv('ISO-8859-15', 'UTF-8', @iconv('UTF-8', 'ISO-8859-15' . '//IGNORE', $value));
         }
         $csvImportSession->elementDelimiter = $elementDelimiter;
         $csvImportSession->tagDelimiter = $tagDelimiter;
         $csvImportSession->fileDelimiter = $fileDelimiter;
         $csvImportSession->ownerId = $this->getInvokeArg('bootstrap')->currentuser->id;
         // All is valid, so we save settings.
         set_option('xml_import_format', $args['format']);
         set_option('xml_import_stylesheet', $args['stylesheet']);
         set_option('xml_import_stylesheet_parameters', $args['stylesheet_parameters']);
         set_option('xml_import_format_filename', $args['format_filename']);
         if (XmlImportPlugin::isFullCsvImport()) {
             set_option(CsvImport_ColumnMap_IdentifierField::IDENTIFIER_FIELD_OPTION_NAME, $args['identifier_field']);
         }
         set_option(CsvImport_RowIterator::COLUMN_DELIMITER_OPTION_NAME, $args['column_delimiter']);
         if (XmlImportPlugin::isFullCsvImport()) {
             set_option(CsvImport_RowIterator::ENCLOSURE_OPTION_NAME, $args['enclosure']);
         }
         set_option(CsvImport_ColumnMap_Element::ELEMENT_DELIMITER_OPTION_NAME, $args['element_delimiter']);
         set_option(CsvImport_ColumnMap_Tag::TAG_DELIMITER_OPTION_NAME, $args['tag_delimiter']);
         set_option(CsvImport_ColumnMap_File::FILE_DELIMITER_OPTION_NAME, $args['file_delimiter']);
         set_option('csv_import_html_elements', $args['html_elements']);
         set_option('csv_import_create_collections', $args['create_collections']);
         set_option('csv_import_extra_data', $args['extra_data']);
         if ($csvImportSession->containsExtraData == 'manual' && $this->session->format != 'Report') {
             $this->_helper->redirector->goto('map-columns', 'index', 'csv-import');
         }
         switch ($format) {
             case 'Manage':
                 $this->_helper->redirector->goto('check-manage-csv', 'index', 'csv-import');
             case 'Report':
                 $this->_helper->redirector->goto('check-omeka-csv', 'index', 'csv-import');
             case 'Mix':
                 $this->_helper->redirector->goto('check-mix-csv', 'index', 'csv-import');
             case 'Update':
                 $this->_helper->redirector->goto('check-update-csv', 'index', 'csv-import');
             default:
                 $this->_helper->redirector->goto('map-columns', 'index', 'csv-import');
         }
     } catch (Exception $e) {
         $msg = __('Error in your xml file, in your xsl sheet or in your options.') . ' ' . __('The xsl sheet should produce a valid csv file with a header and at least one row of metadata.') . ' ' . $e->getMessage();
         $this->_helper->flashMessenger($msg, 'error');
         $this->view->error = $msg;
         $this->_helper->redirector->goto('index');
     }
 }
Beispiel #14
0
 /**
  * test expiration of namespace variables by hops; expect expiration of specified keys in the proper number of hops
  *
  * @runInSeparateProcess
  * @return void
  */
 public function testSetExpireSessionVarsByHopsOnUse()
 {
     $s = new Zend_Session_Namespace('expireGuava');
     $expireBeforeHop = 2;
     $s->setExpirationHops($expireBeforeHop, 'g', true);
     // only count a hop, when namespace is used
     $s->g = 'guava';
     $s->p = 'peach';
     $s->p = 'plum';
     $id = session_id();
     // we are not accessing (using) the "expireGuava" namespace, so these hops should have no effect
     for ($i = 1; $i <= $expireBeforeHop + 2; $i++) {
         session_write_close();
         // release session so process below can use it
         exec("{$this->_script} expireAll {$id} notused", $result);
         session_start();
         // resume artificially suspended session
         $result = $this->sortResult($result);
         $this->assertTrue($result === '', "iteration over named Zend_Session namespace failed (result='{$result}'; hop #{$i})");
     }
     for ($i = 1; $i <= $expireBeforeHop + 2; $i++) {
         session_write_close();
         // release session so process below can use it
         exec("{$this->_script} expireAll {$id} expireGuava", $result);
         session_start();
         // resume artificially suspended session
         $result = $this->sortResult($result);
         if ($i > $expireBeforeHop) {
             $expect = ';p === plum';
             $this->assertTrue($result === $expect, "unexpected results iterating over named Zend_Session namespace (result='{$result}'; expected '{$expect}'; hop #{$i})");
         } else {
             $expect = ';g === guava;p === plum';
             $this->assertTrue($result === $expect, "unexpected results iterating over named Zend_Session namespace (result='{$result}'; expected '{$expect}'; hop #{$i})");
         }
     }
     // Do not destroy session since it still may be used by other tests
     // Zend_Session::destroy();
 }
Beispiel #15
0
 /**
  * Add a comment
  *
  * @return void
  */
 public function addAction()
 {
     /**
      * @var $request Zend_Controller_Request_Http
      */
     $request = $this->getRequest();
     // Retrieve id of commented object
     $pid = intval($request->getParam('pid'));
     $ns = new Zend_Session_Namespace('Comment_CommentsController');
     $ns->setExpirationHops(1);
     $form = new Comment_Form_Comment();
     if (isset($ns->commentFormData)) {
         $form->setDefaults($ns->commentFormData);
         foreach ($ns->commentFormErrorsMessages as $elementName => $error) {
             $form->getElement($elementName)->addErrors($error);
         }
     }
     $fromRoute = Zend_Controller_Front::getInstance()->getRouter()->getCurrentRouteName();
     $toRoute = $this->urlHelper->url();
     if ('comment_add' !== $fromRoute) {
         $ns->commentFromRoute = $fromRoute;
         $toRoute = $toRoute . '/comment';
     }
     $form->setAction($toRoute);
     if ($request->isPost()) {
         $parentModel = new $this->_parentModelClass();
         $parentObject = $parentModel->find($pid)->current();
         if (!$parentObject) {
             throw new Zend_Controller_Action_Exception('Unable to find commented object in database', 500);
         }
         if ($form->isValid($request->getParam('commentForm'))) {
             $commentsModel = new Comment_Model_DbTable_Comment();
             $data = $form->getValues(true);
             $data['pid'] = $pid;
             $identity = Zend_Auth::getInstance();
             if ($identity->hasIdentity()) {
                 $data['uid'] = $identity->getIdentity()->uid;
                 $data['name'] = $identity->getIdentity()->username;
                 $data['email'] = $identity->getIdentity()->email;
             }
             $data['created_on'] = time();
             $commentsModel->insert($data);
         } else {
             $ns->commentFormData = $form->getValues();
             $ns->commentFormErrorsMessages = $form->getMessages(null, true);
         }
         $this->_redirect($this->urlHelper->url(array('pid' => $pid), $ns->commentFromRoute));
     }
     $this->view->assign('form', $form);
 }
 public function uploadAction()
 {
     $translator = \Zend_Registry::get('container')->getService('translator');
     // get next redirect param
     $nextRedirect = new Zend_Session_Namespace('upload-next');
     $path = $this->parsePath($this->_getParam('path', ''));
     $plupload = $this->getHelper('plupload');
     $form = new Admin_Form_Upload();
     $form->setMethod('post');
     $form->getElement('submit')->setLabel($translator->trans('Done uploading', array(), 'themes'));
     $request = $this->getRequest();
     if ($request->isPost() && $form->isValid($request->getPost())) {
         $files = $plupload->getUploadedFiles();
         foreach ($files as $basename => $tmp) {
             $this->service->storeItem("{$path}/{$basename}", file_get_contents($tmp));
         }
         $this->_helper->flashMessenger($this->formatMessage(array_keys($files), $translator->trans('uploaded', array(), 'themes')));
         // redirect by next parameter
         if (!is_null($nextRedirect->next)) {
             $this->_helper->redirector->gotoRouteAndExit($nextRedirect->next);
         } else {
             $this->_helper->redirector->gotoSimple("index", "themes", "admin");
         }
     }
     // prelong next parameter
     $nextRedirect->setExpirationHops(7, 'next', true);
     $this->view->form = $form;
     $this->view->path = $this->view->basePath . $path;
     $this->view->isWritable = $this->service->isWritable($path);
 }
 /**
  * allows a user to signup for an account
  *
  */
 public function signupAction()
 {
     $realm = $this->_getParam('realm', null);
     if (is_null($realm)) {
         throw new Ot_Exception_Input('msg-error-realmNotFound');
     }
     // Set up the auth adapter
     $authAdapter = new Ot_Model_DbTable_AuthAdapter();
     $adapter = $authAdapter->find($realm);
     if (is_null($adapter)) {
         throw new Ot_Exception_Data($this->view->translate('ot-login-signup:realmNotFound', array('<b>' . $realm . '</b>')));
     }
     if ($adapter->enabled == 0) {
         throw new Ot_Exception_Access('msg-error-authNotSupported');
     }
     $className = (string) $adapter->class;
     $auth = new $className();
     if (!$auth->manageLocally()) {
         throw new Ot_Exception_Access('msg-error-authNotSupported');
     }
     if (!$auth->allowUserSignUp()) {
         throw new Ot_Exception_Access('msg-error-authNotAllowed');
     }
     $form = new Ot_Form_Signup();
     $form->removeElement('realm');
     if ($this->_request->isPost()) {
         if ($form->isValid($_POST)) {
             if ($form->getValue('password') == $form->getValue('passwordConf')) {
                 $accountData = array('username' => $form->getValue('username'), 'password' => md5($form->getValue('password')), 'realm' => $realm, 'role' => $this->_helper->configVar('newAccountRole'), 'emailAddress' => $form->getValue('emailAddress'), 'firstName' => $form->getValue('firstName'), 'lastName' => $form->getValue('lastName'), 'timezone' => $form->getValue('timezone'));
                 $account = new Ot_Model_DbTable_Account();
                 if ($account->accountExists($accountData['username'], $accountData['realm'])) {
                     $this->_helper->messenger->addError('msg-error-usernameTaken');
                 } else {
                     $dba = Zend_Db_Table::getDefaultAdapter();
                     $dba->beginTransaction();
                     try {
                         $accountData['accountId'] = $account->insert($accountData);
                         $aar = new Ot_Account_Attribute_Register();
                         $vars = $aar->getVars($accountData['accountId']);
                         $values = $form->getValues();
                         foreach ($vars as $varName => $var) {
                             if (isset($values['accountAttributes'][$varName])) {
                                 $var->setValue($values['accountAttributes'][$varName]);
                                 $aar->save($var, $accountData['accountId']);
                             }
                         }
                         $cahr = new Ot_CustomAttribute_HostRegister();
                         $thisHost = $cahr->getHost('Ot_Profile');
                         if (is_null($thisHost)) {
                             throw new Ot_Exception_Data('msg-error-objectNotSetup');
                         }
                         $customAttributes = $thisHost->getAttributes($accountData['accountId']);
                         foreach ($customAttributes as $attributeName => $a) {
                             if (array_key_exists($attributeName, $values['customAttributes'])) {
                                 $a['var']->setValue($values['customAttributes'][$attributeName]);
                                 $thisHost->saveAttribute($a['var'], $accountData['accountId'], $a['attributeId']);
                             }
                         }
                     } catch (Exception $e) {
                         $dba->rollback();
                         throw $e;
                     }
                     $dba->commit();
                     $loggerOptions = array('attributeName' => 'accountId', 'attributeId' => $accountData['accountId']);
                     $this->_helper->log(Zend_Log::INFO, 'User ' . $accountData['username'] . ' created an account.', $loggerOptions);
                     $dt = new Ot_Trigger_Dispatcher();
                     $dt->setVariables($accountData);
                     $dt->password = $form->getValue('password');
                     $dt->loginMethod = $realm;
                     $dt->dispatch('Login_Index_Signup');
                     $authAdapterModel = new Ot_Model_DbTable_AuthAdapter();
                     $adapter = $authAdapterModel->find($realm);
                     $className = (string) $adapter->class;
                     // Set up the authentication adapter
                     $authAdapter = new $className($accountData['username'], $form->getValue('password'));
                     $auth = Zend_Auth::getInstance();
                     $authRealm = new Zend_Session_Namespace('authRealm');
                     $authRealm->setExpirationHops(1);
                     $authRealm->realm = $realm;
                     $authRealm->autoLogin = $authAdapter->autoLogin();
                     // Attempt authentication, saving the result
                     $result = $auth->authenticate($authAdapter);
                     $authRealm->unsetAll();
                     $req = new Zend_Session_Namespace(Zend_Registry::get('siteUrl') . '_request');
                     $this->_helper->messenger->addSuccess('msg-info-accountCreated');
                     if ($result->isValid()) {
                         $account = new Ot_Model_DbTable_Account();
                         $thisAccount = $account->getByUsername($accountData['username'], $realm);
                         $auth->getStorage()->write($thisAccount);
                         if (isset($req->uri) && $req->uri != '') {
                             $uri = $req->uri;
                             $req->unsetAll();
                             $this->_helper->redirector->gotoUrl($uri);
                         } else {
                             $this->_helper->redirector->gotoRoute(array(), 'default', true);
                         }
                     } else {
                         $this->_helper->redirector->gotoRoute(array('realm' => $realm), 'login', true);
                     }
                 }
             } else {
                 $this->_helper->messenger->addError('msg-error-passwordsNotMatch');
             }
         } else {
             $this->_helper->messenger->addError('msg-error-invalidFormInfo');
         }
     }
     $this->_helper->pageTitle('ot-login-signup:title');
     $this->view->headScript()->appendFile($this->view->baseUrl() . '/scripts/ot/jquery.plugin.passStrength.js');
     $this->view->assign(array('realm' => $realm, 'form' => $form));
 }