/**
  * Should handle execution of the task, taking as much (optional) parameters as needed
  *
  * The parameters should be optional and failing to provide them should be handled by
  * the task
  */
 public function execute($tokenData = null, $userId = null)
 {
     $batch = $this->getBatch();
     $tracker = $this->loader->getTracker();
     $batch->addToCounter('checkedTokens');
     $token = $tracker->getToken($tokenData);
     $wasAnswered = $token->isCompleted();
     if ($result = $token->checkTokenCompletion($userId)) {
         if ($result & \Gems_Tracker_Token::COMPLETION_DATACHANGE) {
             $i = $batch->addToCounter('resultDataChanges');
             $batch->setMessage('resultDataChanges', sprintf($this->_('Results and timing changed for %d tokens.'), $i));
             if ($wasAnswered) {
                 $action = 'token.data-changed';
                 $message = sprintf($this->_("Token '%s' data has changed."), $token->getTokenId());
             } else {
                 $action = 'token.answered';
                 $message = sprintf($this->_("Token '%s' was answered."), $token->getTokenId());
             }
             if (!$this->request instanceof \Zend_Controller_Request_Abstract) {
                 $this->request = \Zend_Controller_Front::getInstance()->getRequest();
             }
             $this->accesslog->logEntry($this->request, $action, true, $message, $token->getArrayCopy(), $token->getRespondentId());
         }
         if ($result & \Gems_Tracker_Token::COMPLETION_EVENTCHANGE) {
             $i = $batch->addToCounter('surveyCompletionChanges');
             $batch->setMessage('surveyCompletionChanges', sprintf($this->_('Answers changed by survey completion event for %d tokens.'), $i));
         }
     }
     if ($token->isCompleted()) {
         $batch->setTask('Tracker_ProcessTokenCompletion', 'tokproc-' . $token->getTokenId(), $tokenData, $userId);
     }
     $batch->setMessage('checkedTokens', sprintf($this->_('Checked %d tokens.'), $batch->getCounter('checkedTokens')));
     // Free memory
     $tracker->removeToken($token);
 }
 /**
  * Hook that allows actions when data was saved
  *
  * When not rerouted, the form will be populated afterwards
  *
  * @param int $changed The number of changed rows (0 or 1 usually, but can be more)
  */
 protected function afterSave($changed)
 {
     parent::afterSave($changed);
     if ($changed) {
         $this->accesslog->logChange($this->request, null, $this->formData);
     }
 }
 public function runSqlAction()
 {
     /*************
      * Make form *
      *************/
     $form = $this->createForm();
     $element = $form->createElement('textarea', 'script');
     $element->setDescription($this->_('Separate multiple commands with semicolons (;).'));
     $element->setLabel('SQL:');
     $element->setRequired(true);
     $form->addElement($element);
     //$element = new \Zend_Form_Element_Submit('submit');
     $element = $form->createElement('submit', 'submit');
     $element->setLabel($this->_('Run'));
     $form->addElement($element);
     /****************
      * Process form *
      ****************/
     if ($this->_request->isPost() && $form->isValid($_POST)) {
         $data = $_POST;
         $data['name'] = '';
         $data['type'] = $this->_('raw');
         $model = $this->getModel();
         $results = $model->runScript($data, true);
         $resultSet = 1;
         $echos = \MUtil_Html::create()->array();
         foreach ($results as $result) {
             if (is_string($result)) {
                 $this->addMessage($result);
             } else {
                 $echo = $echos->echo($result, sprintf($this->_('Result set %s.'), $resultSet++));
                 $echo->class = 'browser';
             }
         }
         $this->accesslog->logChange($this->_request, null, $data['script']);
     } else {
         $form->populate($_POST);
         $resultSet = 0;
     }
     /****************
      * Display form *
      ****************/
     $table = new \MUtil_Html_TableElement(array('class' => 'formTable'));
     $table->setAsFormLayout($form, true, true);
     $table['tbody'][0][0]->class = 'label';
     // Is only one row with formLayout, so all in output fields get class.
     $table['tbody'][0][0]->style = 'vertical-align: top;';
     // Only single cell, this always looks better here.
     if ($links = $this->createMenuLinks()) {
         $table->tf();
         // Add empty cell, no label
         $linksCell = $table->tf($links);
     }
     $this->html->h3($this->_('Execute raw SQL'));
     $this->html[] = $form;
     if ($resultSet > 1) {
         $this->html->h3($this->_('Result sets'));
         $this->html[] = $echos;
     }
 }
 /**
  * Hook for after save
  *
  * @param \MUtil_Task_TaskBatch $batch that was just executed
  * @param \MUtil_Form_Element_Html $element Tetx element for display of messages
  * @return string a message about what has changed (and used in the form)
  */
 public function afterImport(\MUtil_Task_TaskBatch $batch, \MUtil_Form_Element_Html $element)
 {
     $text = parent::afterImport($batch, $element);
     $data = $this->formData;
     // Remove unuseful data
     unset($data['button_spacer'], $data['current_step'], $data[$this->csrfId]);
     // Add useful data
     $data['localfile'] = basename($this->_session->localfile);
     $data['extension'] = $this->_session->extension;
     $data['failureDirectory'] = '...' . substr($this->importer->getFailureDirectory(), -30);
     $data['longtermFilename'] = basename($this->importer->getLongtermFilename());
     $data['successDirectory'] = '...' . substr($this->importer->getSuccessDirectory(), -30);
     $data['tempDirectory'] = '...' . substr($this->tempDirectory, -30);
     $data['importTranslator'] = get_class($this->importer->getImportTranslator());
     $data['sourceModelClass'] = get_class($this->sourceModel);
     $data['targetModelClass'] = get_class($this->targetModel);
     ksort($data);
     $this->accesslog->logChange($this->request, null, array_filter($data));
 }
 /**
  * Add the elements from the model to the bridge for the current step
  *
  * @param \MUtil_Model_Bridge_FormBridgeInterface $bridge
  * @param \MUtil_Model_ModelAbstract $model
  */
 protected function addStepGenerateExportFile(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
 {
     // Things go really wrong (at the session level) if we run this code
     // while the finish button was pressed
     if ($this->isFinishedClicked()) {
         return;
     }
     $this->displayHeader($bridge, $this->_('Creating the export file'), 'h3');
     $this->nextDisabled = true;
     $batch = $this->getExportBatch();
     $form = $bridge->getForm();
     $batch->setFormId($form->getId());
     $batch->autoStart = true;
     // \MUtil_Registry_Source::$verbose = true;
     if ($batch->run($this->request)) {
         exit;
     }
     $element = $form->createElement('html', $batch->getId());
     if ($batch->isFinished()) {
         $this->nextDisabled = $batch->getCounter('export_errors');
         $batch->autoStart = false;
         // Keep the filename after $batch->getMessages(true) cleared the previous
         $downloadName = \MUtil_File::cleanupName($this->trackEngine->getTrackName()) . '.track.txt';
         $localFilename = $batch->getSessionVariable('filename');
         $this->addMessage($batch->getMessages(true));
         $batch->setSessionVariable('downloadname', $downloadName);
         $batch->setSessionVariable('filename', $localFilename);
         // Log Export
         $data = $this->formData;
         // Remove unuseful data
         unset($data['button_spacer'], $data['current_step'], $data[$this->csrfId]);
         // Add useful data
         $data['localfile'] = '...' . substr($localFilename, -30);
         $data['downloadname'] = $downloadName;
         ksort($data);
         $this->accesslog->logChange($this->request, null, array_filter($data));
         if ($this->nextDisabled) {
             $element->pInfo($this->_('Export errors occurred.'));
         } else {
             $p = $element->pInfo($this->_('Export file generated.'), ' ');
             $p->sprintf($this->plural('Click here if the download does not start automatically in %d second:', 'Click here if the download does not start automatically in %d seconds:', $this->downloadWaitSeconds), $this->downloadWaitSeconds);
             $p->append(' ');
             $href = new \MUtil_Html_HrefArrayAttribute(array('file' => 'go', $this->stepFieldName => 'download'));
             $p->a($href, $downloadName, array('type' => 'application/download'));
             $metaContent = sprintf('%d;url=%s', $this->downloadWaitSeconds, $href->render($this->view));
             $this->view->headMeta($metaContent, 'refresh', 'http-equiv');
         }
     } else {
         $element->setValue($batch->getPanel($this->view, $batch->getProgressPercentage() . '%'));
     }
     $form->activateJQuery();
     $form->addElement($element);
 }
 /**
  *
  * @param \MUtil_Batch_BatchAbstract $batch
  * @param string $title
  * @param \Gems_AccessLog $accessLog
  */
 public function direct(\MUtil_Batch_BatchAbstract $batch, $title, $accessLog = null)
 {
     if ($batch->isConsole()) {
         $batch->runContinuous();
         $messages = array_values($batch->getMessages(true));
         echo implode("\n", $messages) . "\n";
         $echo = array_filter(array_map('trim', preg_split('/<[^>]+>/', \MUtil_Echo::out())));
         if ($echo) {
             echo "\n\n================================================================\nECHO OUTPUT:\n\n";
             echo implode("\n", $echo);
         }
         if ($accessLog instanceof \Gems_AccessLog) {
             $accessLog->logChange($this->getRequest(), $messages, $echo);
         }
         exit;
     } elseif ($batch->run($this->getRequest())) {
         exit;
     } else {
         $controller = $this->getActionController();
         $batchContainer = $controller->html->div(array('class' => 'batch-container'));
         $batchContainer->h3($title);
         if ($batch->isFinished()) {
             $controller->addMessage($batch->getMessages(true), 'info');
             $batchContainer->pInfo($batch->getRestartButton($controller->_('Prepare recheck'), array('class' => 'actionlink')));
             if ($accessLog instanceof \Gems_AccessLog) {
                 $echo = array_filter(array_map('trim', preg_split('/<[^>]+>/', \MUtil_Echo::getOutput())));
                 $accessLog->logChange($this->getRequest(), null, $echo);
             }
         } else {
             if ($batch->count()) {
                 $batchContainer->pInfo($batch->getStartButton(sprintf($controller->_('Start %s jobs'), $batch->count())));
                 $batchContainer->append($batch->getPanel($controller->view, $batch->getProgressPercentage() . '%'));
             } else {
                 $batchContainer->pInfo($controller->_('Nothing to do.'));
             }
         }
     }
 }
 /**
  * Take care of exporting the data
  *
  * @param array $data
  */
 public function handleExport($data)
 {
     if (isset($data['type']) && !empty($data['sid'])) {
         //Do the logging
         $message = \Zend_Json::encode($data);
         $this->accesslog->logChange($this->getRequest());
         // Clear possible existing batch
         $batch = $this->loader->getTaskRunnerBatch('export_data');
         $batch->reset();
         // Have a batch handle the export
         $this->_session->exportParams = $data;
         $this->_reroute(array('action' => 'handle-export'));
     }
 }
 /**
  * Action that switches the maintenance lock on or off.
  */
 public function maintenanceAction()
 {
     // Switch lock
     if ($this->util->getMonitor()->reverseMaintenanceMonitor()) {
         $this->accesslog->logChange($this->getRequest(), $this->_('Maintenance mode set ON'));
     } else {
         $this->accesslog->logChange($this->getRequest(), $this->_('Maintenance mode set OFF'));
         // Dump the existing maintenance mode messages.
         $this->escort->getMessenger()->clearCurrentMessages();
         $this->escort->getMessenger()->clearMessages();
         \MUtil_Echo::out();
     }
     // Redirect
     $request = $this->getRequest();
     $this->_reroute(array($request->getActionKey() => 'index'));
 }
 /**
  * Reset password page.
  */
 public function resetpasswordAction()
 {
     $errors = array();
     $form = $this->createResetRequestForm();
     $request = $this->getRequest();
     if ($key = $this->_getParam('key')) {
         $user = $this->loader->getUserLoader()->getUserByResetKey($key);
         if ($user->hasValidResetKey()) {
             $form = $user->getChangePasswordForm(array('askOld' => false, 'askCheck' => true, 'labelWidthFactor' => $this->labelWidthFactor));
             $result = $user->authenticate(null, false);
             if (!$result->isValid()) {
                 $this->addMessage($result->getMessages());
                 $this->addMessage($this->_('For that reason you cannot reset your password.'));
                 return;
             }
             if (!$request->isPost()) {
                 $this->accesslog->logChange($request, sprintf("User %s opened valid reset link.", $user->getLoginName()));
             }
         } else {
             if (!$request->isPost()) {
                 if ($user->getLoginName()) {
                     $message = sprintf("User %s used old reset key.", $user->getLoginName());
                 } else {
                     $message = sprintf("Someone used a non existent reset key.", $user->getLoginName());
                 }
                 $this->accesslog->logChange($request, $message);
                 if ($user->hasPassword() || !$user->isActive()) {
                     $errors[] = $this->_('Your password reset request is no longer valid, please request a new link.');
                 } else {
                     $errors[] = $this->_('Your password input request is no longer valid, please request a new link.');
                 }
             }
             if ($user->isActive()) {
                 $form->getUserNameElement()->setValue($user->getLoginName());
                 $form->getOrganizationElement()->setValue($user->getBaseOrganizationId());
             }
         }
     }
     if ($request->isPost() && $form->isValid($request->getPost())) {
         if ($form instanceof \Gems_User_Form_ResetRequestForm) {
             $user = $form->getUser();
             $result = $user->authenticate(null, false);
             if (!$result->isValid()) {
                 $this->addMessage($result->getMessages());
                 $this->addMessage($this->_('For that reason you cannot request a password reset.'));
                 return;
             }
             $errors = $this->sendUserResetEMail($user);
             if ($errors) {
                 $this->accesslog->logChange($request, sprintf("User %s requested reset password but got %d error(s). %s", $form->getUserNameElement()->getValue(), count($errors), implode(' ', $errors)));
             } else {
                 // Everything went OK!
                 $this->addMessage($this->_('We sent you an e-mail with a reset link. Click on the link in the e-mail.'));
                 $this->accesslog->logChange($request);
                 if ($this->returnToLoginAfterReset) {
                     $this->setCurrentOrganizationTo($user);
                     $this->currentUser->gotoStartPage($this->menu, $request);
                 }
             }
         } elseif ($form instanceof \Gems_User_Form_ChangePasswordForm) {
             $this->addMessage($this->_('New password is active.'));
             // User set before this form was initiated
             $user->setAsCurrentUser();
             /**
              * Log the login
              */
             $this->accesslog->logChange($request, $this->_("User logged in through reset password."));
             $user->gotoStartPage($this->menu, $this->getRequest());
             return;
         }
     }
     $form->populate($request->getParams());
     $this->displayResetForm($form, $errors);
 }
 /**
  *
  * @param \Zend_Cache_Core $cache
  * @param \Zend_Db_Adapter_Abstract $db
  * @param \Gems_Loader $loader
  */
 public function __construct(\Zend_Cache_Core $cache, \Zend_Db_Adapter_Abstract $db, \Gems_Loader $loader)
 {
     $this->_cache = $cache;
     $this->_cacheId = \MUtil_String::toCacheId(GEMS_PROJECT_NAME . APPLICATION_PATH . '__gems__' . __CLASS__);
     $this->_db = $db;
     $this->_loader = $loader;
     $this->_sessionStore = new \Zend_Session_Namespace($this->_cacheId);
     $this->_actions = $this->_getActionsCache();
     if (false === $this->_actions) {
         $this->_actions = $this->_getActionsDb();
     }
     if (!self::$_log) {
         self::$_log = $this;
     }
 }