From: <gem...@li...> - 2013-03-18 18:04:22
|
Revision: 1192 http://sourceforge.net/p/gemstracker/code/1192 Author: matijsdejong Date: 2013-03-18 18:04:19 +0000 (Mon, 18 Mar 2013) Log Message: ----------- Fixed bug in EventCaculations where 0 was equal to null (pulse #568) Added sort handling to transformer Modified Paths: -------------- trunk/library/classes/Gems/Event/EventCalculations.php trunk/library/classes/Gems/Tracker/Token.php trunk/library/classes/MUtil/Model/ModelAbstract.php trunk/library/classes/MUtil/Model/ModelTransformerAbstract.php trunk/library/classes/MUtil/Model/ModelTransformerInterface.php trunk/library/classes/MUtil/Model/Transform/JoinTransformer.php Modified: trunk/library/classes/Gems/Event/EventCalculations.php =================================================================== --- trunk/library/classes/Gems/Event/EventCalculations.php 2013-03-18 13:16:50 UTC (rev 1191) +++ trunk/library/classes/Gems/Event/EventCalculations.php 2013-03-18 18:04:19 UTC (rev 1192) @@ -149,7 +149,7 @@ foreach($values as $name => $result) { $result = intval($result); - if ($tokenAnswers[$name] != $result) { + if (($tokenAnswers[$name] != $result) && ($tokenAnswers[$name] !== null)) { $results[$name] = $result; } } Modified: trunk/library/classes/Gems/Tracker/Token.php =================================================================== --- trunk/library/classes/Gems/Tracker/Token.php 2013-03-18 13:16:50 UTC (rev 1191) +++ trunk/library/classes/Gems/Tracker/Token.php 2013-03-18 18:04:19 UTC (rev 1192) @@ -385,11 +385,11 @@ // added to the url. $surveyReturn['RouteReset'] = true; + // MUtil_Echo::track($currentUri, MUtil_Html::urlString($surveyReturn)); return $currentUri . MUtil_Html::urlString($surveyReturn); - // MUtil_Echo::track($currentUri . MUtil_Html::urlString($surveyReturn)); } - // Ultimate backup solution for reutrn + // Ultimate backup solution for return return $currentUri . '/ask/forward/' . MUtil_Model::REQUEST_ID . '/' . urlencode($this->getTokenId()); } Modified: trunk/library/classes/MUtil/Model/ModelAbstract.php =================================================================== --- trunk/library/classes/MUtil/Model/ModelAbstract.php 2013-03-18 13:16:50 UTC (rev 1191) +++ trunk/library/classes/MUtil/Model/ModelAbstract.php 2013-03-18 18:04:19 UTC (rev 1192) @@ -132,7 +132,7 @@ } /** - * Checks the filter on sematic correctness and replaces the text seacrh filter + * Checks the filter on sematic correctness and replaces the text search filter * with the real filter. * * @param mixed $filter True for the filter stored in this model or a filter array @@ -143,7 +143,7 @@ if (true === $filter) { $filter = $this->getFilter(); } - if ($filter && is_array($filter)) { + if (is_array($filter)) { foreach ($this->_transformers as $transformer) { $filter = $transformer->transformFilter($this, $filter); } @@ -162,16 +162,27 @@ return array(); } + /** + * Checks the sort on sematic correctness + * + * @param mixed $sort True for the sort stored in this model or a sort array or a single sort value + * @return array The filter to use + */ protected function _checkSortUsed($sort) { if (true === $sort) { - return $this->getSort(); + $sort = $this->getSort(); + } elseif (false === $sort) { + $sort = array(); + } else { + $sort = $this->_checkSortValue($sort); } - if (false === $sort) { - return array(); + + foreach ($this->_transformers as $transformer) { + $sort = $transformer->transformSort($this, $sort); } - return $this->_checkSortValue($sort); + return $sort; } protected function _checkSortValue($value) @@ -1313,13 +1324,21 @@ return $this; } - public function setAlias($name, $alias) + /** + * Set the value to be an alias of another field + * + * @param string $name + * @param string $aliasOf + * @return \MUtil_Model_ModelAbstract + * @throws MUtil_Model_ModelException + */ + public function setAlias($name, $aliasOf) { - if ($this->has($alias)) { - $this->set($name, self::ALIAS_OF, $alias); + if ($this->has($aliasOf)) { + $this->set($name, self::ALIAS_OF, $aliasOf); return $this; } - throw new MUtil_Model_ModelException("Alias for '$name' set to non existing field '$alias'"); + throw new MUtil_Model_ModelException("Alias for '$name' set to non existing field '$aliasOf'"); } /** Modified: trunk/library/classes/MUtil/Model/ModelTransformerAbstract.php =================================================================== --- trunk/library/classes/MUtil/Model/ModelTransformerAbstract.php 2013-03-18 13:16:50 UTC (rev 1191) +++ trunk/library/classes/MUtil/Model/ModelTransformerAbstract.php 2013-03-18 18:04:19 UTC (rev 1192) @@ -156,7 +156,7 @@ /** * This transform function checks the filter for * a) retreiving filters to be applied to the transforming data, - * b) adding filters that are the result + * b) adding filters that are needed * * @param MUtil_Model_ModelAbstract $model * @param array $filter @@ -169,6 +169,21 @@ } /** + * This transform function checks the sort to + * a) remove sorts from the main model that are not possible + * b) add sorts that are required needed + * + * @param MUtil_Model_ModelAbstract $model + * @param array $sort + * @return array The (optionally changed) sort + */ + public function transformSort(MUtil_Model_ModelAbstract $model, array $sort) + { + // No changes + return $sort; + } + + /** * The transform function performs the actual transformation of the data and is called after * the loading of the data in the source model. * Modified: trunk/library/classes/MUtil/Model/ModelTransformerInterface.php =================================================================== --- trunk/library/classes/MUtil/Model/ModelTransformerInterface.php 2013-03-18 13:16:50 UTC (rev 1191) +++ trunk/library/classes/MUtil/Model/ModelTransformerInterface.php 2013-03-18 18:04:19 UTC (rev 1192) @@ -60,15 +60,26 @@ /** * This transform function checks the filter for * a) retreiving filters to be applied to the transforming data, - * b) adding filters that are the result + * b) adding filters that are needed * * @param MUtil_Model_ModelAbstract $model * @param array $filter * @return array The (optionally changed) filter */ public function transformFilter(MUtil_Model_ModelAbstract $model, array $filter); - + /** + * This transform function checks the sort to + * a) remove sorts from the main model that are not possible + * b) add sorts that are required needed + * + * @param MUtil_Model_ModelAbstract $model + * @param array $sort + * @return array The (optionally changed) sort + */ + public function transformSort(MUtil_Model_ModelAbstract $model, array $sort); + + /** * The transform function performs the actual transformation of the data and is called after * the loading of the data in the source model. * Modified: trunk/library/classes/MUtil/Model/Transform/JoinTransformer.php =================================================================== --- trunk/library/classes/MUtil/Model/Transform/JoinTransformer.php 2013-03-18 13:16:50 UTC (rev 1191) +++ trunk/library/classes/MUtil/Model/Transform/JoinTransformer.php 2013-03-18 18:04:19 UTC (rev 1192) @@ -120,6 +120,29 @@ } /** + * This transform function checks the sort to + * a) remove sorts from the main model that are not possible + * b) add sorts that are required needed + * + * @param MUtil_Model_ModelAbstract $model + * @param array $sort + * @return array The (optionally changed) sort + */ + public function transformSort(MUtil_Model_ModelAbstract $model, array $sort) + { + foreach ($this->_subModels as $sub) { + foreach ($sort as $key => $value) { + if ($sub->has($key)) { + // Remove all sorts on columns from the submodel + unset($sort[$key]); + } + } + } + + return $sort; + } + + /** * The transform function performs the actual transformation of the data and is called after * the loading of the data in the source model. * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2013-03-25 14:00:53
|
Revision: 1206 http://sourceforge.net/p/gemstracker/code/1206 Author: mennodekker Date: 2013-03-25 14:00:49 +0000 (Mon, 25 Mar 2013) Log Message: ----------- Some more fixes on handling openrosa forms, still needs more error checking on the form Modified Paths: -------------- trunk/library/classes/Gems/Default/OpenrosaAction.php trunk/library/classes/GemsEscort.php trunk/library/classes/OpenRosa/Tracker/Source/OpenRosa/Form.php Modified: trunk/library/classes/Gems/Default/OpenrosaAction.php =================================================================== --- trunk/library/classes/Gems/Default/OpenrosaAction.php 2013-03-25 11:53:12 UTC (rev 1205) +++ trunk/library/classes/Gems/Default/OpenrosaAction.php 2013-03-25 14:00:49 UTC (rev 1206) @@ -193,7 +193,7 @@ * this only handles storing form data and can be used for resubmission too. * * @param type $xmlFile - * @return string DeviceID or false on failure + * @return string ResultID or false on failure */ private function processReceivedForm($answerXmlFile) { @@ -214,10 +214,8 @@ ); if ($formData = $model->loadFirst($filter)) { $form = new OpenRosa_Tracker_Source_OpenRosa_Form($this->formDir . $formData['gof_form_xml']); - $form->saveAnswer($answerXmlFile); - - $deviceId = $xml->DeviceId[0]; - return $deviceId; + $answers = $form->saveAnswer($answerXmlFile); + return $answers['orf_id']; } else { return false; } @@ -279,6 +277,7 @@ $formCnt = 0; $addCnt = 0; + $files = array(); $rescan = $this->getRequest()->getParam('rescan', false); while (false !== ($filename = $eDir->read())) { $ext = substr($filename, -4); @@ -355,8 +354,8 @@ if ($upload->receive('xml_submission_file')) { $xmlFile = $upload->getFileInfo('xml_submission_file'); $answerXmlFile = $xmlFile['xml_submission_file']['tmp_name']; - $deviceId = $this->processReceivedForm($answerXmlFile); - if ($deviceId === false) { + $resultId = $this->processReceivedForm($answerXmlFile); + if ($resultId === false) { //form not accepted! foreach ($xml->children() as $child) { $log->log($child->getName() . ' -> ' . $child, Zend_Log::ERR); @@ -366,9 +365,9 @@ //$log->log($deviceId, Zend_Log::ERR); foreach ($upload->getFileInfo() as $file => $info) { if ($info['received'] != 1) { - //Rename to deviceid_md5(time)_filename + //Rename to responseid_filename //@@TODO: move to form subdir, for better separation - $upload->addFilter('Rename', $deviceId . '_' . md5(time()) . '_' . $info['name'], $file); + $upload->addFilter('Rename', $resultId . '_' . $info['name'], $file); } } Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2013-03-25 11:53:12 UTC (rev 1205) +++ trunk/library/classes/GemsEscort.php 2013-03-25 14:00:49 UTC (rev 1206) @@ -444,6 +444,9 @@ $this->getLoader()->addPrefixPath('OpenRosa', GEMS_LIBRARY_DIR . '/classes/OpenRosa', true); + $autoloader = Zend_Loader_Autoloader::getInstance(); + $autoloader->registerNamespace('OpenRosa_'); + /** * Add Source for OpenRosa */ Modified: trunk/library/classes/OpenRosa/Tracker/Source/OpenRosa/Form.php =================================================================== --- trunk/library/classes/OpenRosa/Tracker/Source/OpenRosa/Form.php 2013-03-25 11:53:12 UTC (rev 1205) +++ trunk/library/classes/OpenRosa/Tracker/Source/OpenRosa/Form.php 2013-03-25 14:00:49 UTC (rev 1206) @@ -108,7 +108,11 @@ foreach ($this->instance as $name => $element) { $bindName = str_replace('_', '/', '_data_' . $name); - $bindInfo = $this->bind[$bindName]; + if (array_key_exists($bindName, $this->bind)) { + $bindInfo = $this->bind[$bindName]; + } else { + $bindInfo['type'] = 'string'; + } $field = array(); switch ($bindInfo['type']) { @@ -247,6 +251,8 @@ $result['value'] = (string) $element; break; + case 'trigger': + case 'upload': case 'input': case 'select': case 'select1': @@ -381,7 +387,12 @@ $checkbox[0] = $this->translate->_('Not checked'); foreach ($this->instance as $name => $element) { $bindName = str_replace('_', '/', '_data_' . $name); - $bindInfo = $this->bind[$bindName]; + if (array_key_exists($bindName, $this->bind)) { + $bindInfo = $this->bind[$bindName]; + } else { + $bindInfo['type'] = 'string'; + } + switch ($bindInfo['type']) { case 'select': @@ -413,7 +424,7 @@ } $this->model = $model; } - + return $this->model; } @@ -460,7 +471,11 @@ //Now we should parse the response, extract the options given for a (multi)select foreach ($this->instance as $name => $element) { $bindName = str_replace('_', '/', '_data_' . $name); - $bindInfo = $this->bind[$bindName]; + if (array_key_exists($bindName, $this->bind)) { + $bindInfo = $this->bind[$bindName]; + } else { + $bindInfo['type'] = 'string'; + } if ($bindInfo['type'] == 'dateTime') { $answers[$name] = new Zend_Date($answers[$name], Zend_Date::ISO_8601); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2013-04-15 12:36:27
|
Revision: 1230 http://sourceforge.net/p/gemstracker/code/1230 Author: mennodekker Date: 2013-04-15 12:36:24 +0000 (Mon, 15 Apr 2013) Log Message: ----------- Fixing urlencode errors: only use get parameters, not post (post is stored in requestcache when needed) Modified Paths: -------------- trunk/library/classes/GemsEscort.php trunk/library/classes/MUtil/Html/UrlArrayAttribute.php Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2013-04-15 12:15:09 UTC (rev 1229) +++ trunk/library/classes/GemsEscort.php 2013-04-15 12:36:24 UTC (rev 1230) @@ -1025,7 +1025,7 @@ // Organization switcher $orgSwitch = MUtil_Html::create('div', array('id' => 'organizations')); $currentId = $user->getCurrentOrganizationId(); - $params = $this->request->getParams(); //Use only get params, not post + $params = $this->request->getQuery(); //Use only get params, not post unset($params['error_handler']); // If present, this is an object and causes a warning unset($params[Gems_Util_RequestCache::RESET_PARAM]); $currentUri = $this->view->url($params, null, true); Modified: trunk/library/classes/MUtil/Html/UrlArrayAttribute.php =================================================================== --- trunk/library/classes/MUtil/Html/UrlArrayAttribute.php 2013-04-15 12:15:09 UTC (rev 1229) +++ trunk/library/classes/MUtil/Html/UrlArrayAttribute.php 2013-04-15 12:36:24 UTC (rev 1230) @@ -123,7 +123,7 @@ // will add the existing parameters without escaping. $request = $this->getRequest(); - foreach ($request->getParams() as $key => $value) { + foreach ($request->getQuery() as $key => $value) { if (!array_key_exists($key, $url_parameters)) { // E.g. Exceptions are stored as parameters :( if (is_array($value)) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-10-25 14:32:21
|
Revision: 137 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=137&view=rev Author: matijsdejong Date: 2011-10-25 14:32:10 +0000 (Tue, 25 Oct 2011) Log Message: ----------- Locks now set using LockFile object. #29 closed, mail jobs can be set on or off. Modified Paths: -------------- trunk/library/classes/Gems/Controller/ModelSnippetActionAbstract.php trunk/library/classes/Gems/Default/CronAction.php trunk/library/classes/Gems/Default/MailJobAction.php trunk/library/classes/Gems/Default/ProjectInformationAction.php trunk/library/classes/Gems/Menu/MenuAbstract.php trunk/library/classes/Gems/Util.php trunk/library/classes/GemsEscort.php Added Paths: ----------- trunk/library/classes/Gems/Util/LockFile.php Modified: trunk/library/classes/Gems/Controller/ModelSnippetActionAbstract.php =================================================================== --- trunk/library/classes/Gems/Controller/ModelSnippetActionAbstract.php 2011-10-25 12:17:39 UTC (rev 136) +++ trunk/library/classes/Gems/Controller/ModelSnippetActionAbstract.php 2011-10-25 14:32:10 UTC (rev 137) @@ -85,6 +85,12 @@ public $escort; /** + * + * @var Gems_Menu + */ + public $menu; + + /** * The snippets used for the index action, before those in autofilter * * @var mixed String or array of snippets name Modified: trunk/library/classes/Gems/Default/CronAction.php =================================================================== --- trunk/library/classes/Gems/Default/CronAction.php 2011-10-25 12:17:39 UTC (rev 136) +++ trunk/library/classes/Gems/Default/CronAction.php 2011-10-25 14:32:10 UTC (rev 137) @@ -69,6 +69,12 @@ /** * + * @var Gems_Menu + */ + public $menu; + + /** + * * @var Zend_Session_Namespace */ public $session; @@ -83,6 +89,25 @@ public $useHtmlView = true; /** + * + * @var Gems_Util + */ + public $util; + + /** + * Action that switches the cron job lock on or off. + */ + public function cronLockAction() + { + // Switch lock + $this->util->getCronJobLock()->reverse(); + + // Redirect + $request = $this->getRequest(); + $this->_reroute($this->menu->getCurrentParent()->toRouteUrl()); + } + + /** * Loads an e-mail template * * @param integer|null $templateId @@ -106,7 +131,12 @@ public function indexAction() { $this->initHtml(); - $this->mailJob(); + + if ($this->util->getCronJobLock()->isLocked()) { + $this->html->append($this->_('Cron jobs turned off.')); + } else { + $this->mailJob(); + } } public function mailJob() @@ -165,8 +195,13 @@ } } - $this->html->append($mailer->getMessages()); + $msg = $mailer->getMessages(); + if (! $msg) { + $msg[] = $this->_('No mails sent'); + } + $this->html->append($msg); + if ($currentUser) { $this->escort->loadLoginInfo($currentUser); } else { Modified: trunk/library/classes/Gems/Default/MailJobAction.php =================================================================== --- trunk/library/classes/Gems/Default/MailJobAction.php 2011-10-25 12:17:39 UTC (rev 136) +++ trunk/library/classes/Gems/Default/MailJobAction.php 2011-10-25 14:32:10 UTC (rev 137) @@ -185,6 +185,16 @@ { $this->html->h3($this->_('Automatic mail jobs')); + $lock = $this->util->getCronJobLock(); + if ($lock->isLocked()) { + $this->addMessage(sprintf($this->_('Automatic mails have been turned off since %s.'), $lock->getLockTime())); + + $request = $this->getRequest(); + if ($menuItem = $this->menu->findFirst(array($request->getControllerKey() => 'cron', $request->getActionKey() => 'cron-lock'))) { + $menuItem->set('label', $this->_('Turn Automatic Mail Jobs ON')); + } + } + parent::indexAction(); $this->html->pInfo($this->_('With automatic mail jobs and a cron job on the server, mails can be sent without manual user action.')); Modified: trunk/library/classes/Gems/Default/ProjectInformationAction.php =================================================================== --- trunk/library/classes/Gems/Default/ProjectInformationAction.php 2011-10-25 12:17:39 UTC (rev 136) +++ trunk/library/classes/Gems/Default/ProjectInformationAction.php 2011-10-25 14:32:10 UTC (rev 137) @@ -144,7 +144,8 @@ $data[$this->_('Server OS')] = php_uname('s'); $data[$this->_('Time on server')] = date('r'); - if (file_exists($this->escort->getMaintenanceLockFilename())) { + $lock = $this->util->getMaintenanceLock(); + if ($lock->isLocked()) { $label = $this->_('Turn Maintenance Mode OFF'); } else { $label = $this->_('Turn Maintenance Mode ON'); @@ -161,14 +162,13 @@ $this->html->buttonDiv($buttonList); } + /** + * Action that switches the maintenance lock on or off. + */ public function maintenanceAction() { - $lockFile = $this->escort->getMaintenanceLockFilename(); - if (file_exists($lockFile)) { - unlink($lockFile); - } else { - touch($lockFile); - } + // Switch lock + $this->util->getMaintenanceLock()->reverse(); // Dump the existing maintenance mode messages. $this->escort->getMessenger()->clearCurrentMessages(); Modified: trunk/library/classes/Gems/Menu/MenuAbstract.php =================================================================== --- trunk/library/classes/Gems/Menu/MenuAbstract.php 2011-10-25 12:17:39 UTC (rev 136) +++ trunk/library/classes/Gems/Menu/MenuAbstract.php 2011-10-25 14:32:10 UTC (rev 137) @@ -199,6 +199,23 @@ return $page; } + /** + * Add a menu item that is never added to the navigation tree and only shows up as a button. + * + * @param string $label + * @param string $privilege + * @param string $controller + * @param string $action + * @param array $other + * @return Gems_Menu_SubMenuItem + */ + public function addButtonOnly($label, $privilege, $controller, $action = 'index', array $other = array()) + { + $other['button_only'] = true; + + return $this->addPage($label, $privilege, $controller, $action, $other); + } + public function addContainer($label, $privilege = null, array $other = array()) { $other['label'] = $label; @@ -210,13 +227,6 @@ return $this->add($other); } - public function addButtonOnly($label, $privilege, $controller, $action = 'index', array $other = array()) - { - $other['button_only'] = true; - - return $this->addPage($label, $privilege, $controller, $action, $other); - } - /** * Add a Mail menu tree to the menu * @@ -237,6 +247,8 @@ // MAIL JOB CONTROLLER $page = $setup->addBrowsePage($this->_('Automatic mail'), 'pr.mail.job', 'mail-job'); + $page->addButtonOnly($this->_('Turn Automatic Mail Jobs OFF'), 'pr.mail.job', 'cron', 'cron-lock'); + $page->addPage($this->_('Run'), null, 'cron', 'index'); // MAIL SERVER CONTROLLER $page = $setup->addBrowsePage($this->_('Servers'), 'pr.mail.server', 'mail-server'); Added: trunk/library/classes/Gems/Util/LockFile.php =================================================================== --- trunk/library/classes/Gems/Util/LockFile.php (rev 0) +++ trunk/library/classes/Gems/Util/LockFile.php 2011-10-25 14:32:10 UTC (rev 137) @@ -0,0 +1,124 @@ +<?php + +/** + * Copyright (c) 2011, Erasmus MC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Erasmus MC nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * @package Gems + * @subpackage Util + * @author Matijs de Jong <mj...@ma...> + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @version $Id: Sample.php 203 2011-07-07 12:51:32Z matijs $ + */ + +/** + * A simple file based locking mechanism. + * + * @package Gems + * @subpackage Util + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @since Class available since version 1.4.4 + */ +class Gems_Util_LockFile +{ + /** + * + * @var string + */ + protected $lockFileName; + + /** + * + * @param string $lockFileName The name of the lockfile + */ + public function __construct($lockFileName) + { + $this->lockFileName = $lockFileName; + } + + /** + * Last time the lock was set. + * + * @return MUtil_Date or null when not locked. + */ + public function getLockTime() + { + if ($this->isLocked()) { + return new MUtil_Date(filectime($this->lockFileName)); + } + } + + /** + * Returns true if this lock exists. + * + * @return boolean + */ + public function isLocked() + { + return file_exists($this->lockFileName); + } + + /** + * Lock this file and updates lock time. + * + * @return Gems_Util_LockFile (continuation pattern) + */ + public function lock() + { + touch($this->lockFileName); + return $this; + } + + /** + * Switches from lock to unlocked state. + * + * @return Gems_Util_LockFile (continuation pattern) + */ + public function reverse() + { + if ($this->isLocked()) { + $this->unlock(); + } else { + $this->lock(); + } + return $this; + } + + /** + * Unlocks this lock file by deleting it + * + * @return Gems_Util_LockFile (continuation pattern) + */ + public function unlock() + { + if ($this->isLocked()) { + unlink($this->lockFileName); + } + return $this; + } +} Modified: trunk/library/classes/Gems/Util.php =================================================================== --- trunk/library/classes/Gems/Util.php 2011-10-25 12:17:39 UTC (rev 136) +++ trunk/library/classes/Gems/Util.php 2011-10-25 14:32:10 UTC (rev 137) @@ -1,6 +1,5 @@ <?php - /** * Copyright (c) 2011, Erasmus MC * All rights reserved. @@ -117,6 +116,16 @@ return array_combine($consentTypes, $consentTypes); } + /** + * Returns the cron job lock + * + * @return Gems_Util_LockFile + */ + public function getCronJobLock() + { + return $this->_loadClass('lockFile', true, array(GEMS_ROOT_DIR . '/var/settings/cron_lock.txt')); + } + public function getCurrentURI($subpath = '') { static $uri; @@ -169,7 +178,17 @@ } /** + * Returns the maintenance lock * + * @return Gems_Util_LockFile + */ + public function getMaintenanceLock() + { + return $this->_loadClass('lockFile', null, array(GEMS_ROOT_DIR . '/var/settings/lock.txt')); + } + + /** + * * @param string $sourceAction The action to get the cache from if not the current one. * @param boolean $readonly Optional, tell the cache not to store any new values * @return Gems_Util_RequestCache Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2011-10-25 12:17:39 UTC (rev 136) +++ trunk/library/classes/GemsEscort.php 2011-10-25 14:32:10 UTC (rev 137) @@ -1133,15 +1133,6 @@ } /** - * - * @return string Name of the file that performs the maintenance lock - */ - public function getMaintenanceLockFilename() - { - return GEMS_ROOT_DIR . '/var/settings/lock.txt'; - } - - /** * Retrieve the GemsEscort object * * @return GemsEscort @@ -1532,7 +1523,7 @@ * Check if we are in maintenance mode or not. This is triggeren by a file in the var/settings * directory with the name lock.txt */ - if (file_exists($this->getMaintenanceLockFilename())) { + if ($this->getUtil()->getMaintenanceLock()->isLocked()) { if ($this->session->user_id && $this->session->user_role !== 'master') { //Still allow logoff so we can relogin as master if (!('index' == $request->getControllerName() && 'logoff' == $request->getActionName())) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-11-01 14:16:24
|
Revision: 161 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=161&view=rev Author: mennodekker Date: 2011-11-01 14:16:18 +0000 (Tue, 01 Nov 2011) Log Message: ----------- Doc fix and minor optimization Modified Paths: -------------- trunk/library/classes/Gems/Tracker/Source/LimeSurvey1m9Database.php trunk/library/classes/GemsEscort.php Modified: trunk/library/classes/Gems/Tracker/Source/LimeSurvey1m9Database.php =================================================================== --- trunk/library/classes/Gems/Tracker/Source/LimeSurvey1m9Database.php 2011-11-01 14:03:23 UTC (rev 160) +++ trunk/library/classes/Gems/Tracker/Source/LimeSurvey1m9Database.php 2011-11-01 14:16:18 UTC (rev 161) @@ -191,7 +191,7 @@ */ protected function _getSid($surveyId) { - return $this->getSurveyData($surveyId, 'gsu_surveyor_id'); + return $this->tracker->getSurvey($surveyId)->getSourceSurveyId(); } /** Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2011-11-01 14:03:23 UTC (rev 160) +++ trunk/library/classes/GemsEscort.php 2011-11-01 14:16:18 UTC (rev 161) @@ -329,7 +329,7 @@ * * Use $this->project to access afterwards * - * @return Zend_View + * @return ArrayObject */ protected function _initProject() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-11-03 12:23:42
|
Revision: 169 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=169&view=rev Author: michieltcs Date: 2011-11-03 12:23:36 +0000 (Thu, 03 Nov 2011) Log Message: ----------- Add parameter to afterLogin(), don't force it to read POST data Modified Paths: -------------- trunk/library/classes/Gems/Default/IndexAction.php trunk/library/classes/GemsEscort.php Modified: trunk/library/classes/Gems/Default/IndexAction.php =================================================================== --- trunk/library/classes/Gems/Default/IndexAction.php 2011-11-03 12:05:46 UTC (rev 168) +++ trunk/library/classes/Gems/Default/IndexAction.php 2011-11-03 12:23:36 UTC (rev 169) @@ -231,7 +231,7 @@ /** * Perform any project specific post login activities */ - $this->escort->afterLogin(); + $this->escort->afterLogin($_POST['userlogin']); /** * Fix current locale Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2011-11-03 12:05:46 UTC (rev 168) +++ trunk/library/classes/GemsEscort.php 2011-11-03 12:23:36 UTC (rev 169) @@ -911,14 +911,14 @@ } } - public function afterLogin() + public function afterLogin($userName) { /** * Reset number of failed logins */ try { $sql = "UPDATE gems__users SET gsu_failed_logins = 0, gsu_last_failed = NULL WHERE gsu_login = ?"; - $this->db->query($sql, array($_POST['userlogin'])); + $this->db->query($sql, array($userName)); } catch (Exception $e) { // swallow exception } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-11-08 12:46:26
|
Revision: 193 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=193&view=rev Author: mennodekker Date: 2011-11-08 12:46:17 +0000 (Tue, 08 Nov 2011) Log Message: ----------- Quickfix for storing organization ID from successful login in a cookie (to be discussed, escort getCurrentOrganization commented code do we really need that?) Modified Paths: -------------- trunk/library/classes/Gems/Cookies.php trunk/library/classes/Gems/Default/IndexAction.php trunk/library/classes/GemsEscort.php Modified: trunk/library/classes/Gems/Cookies.php =================================================================== --- trunk/library/classes/Gems/Cookies.php 2011-11-08 10:42:02 UTC (rev 192) +++ trunk/library/classes/Gems/Cookies.php 2011-11-08 12:46:17 UTC (rev 193) @@ -45,7 +45,8 @@ */ class Gems_Cookies { - const LOCALE_COOKIE = 'gems_locale'; + const LOCALE_COOKIE = 'gems_locale'; + const ORGANIZATION_COOKIE = 'gems_organization'; /** * Get a specific cookie from the request. @@ -72,6 +73,17 @@ } /** + * Get the organization from the cookie. + * + * @param Zend_Controller_Request_Abstract $request + * @return int The organization + */ + public static function getOrganization(Zend_Controller_Request_Abstract $request) + { + return self::get($request, self::ORGANIZATION_COOKIE); + } + + /** * Store this cookie in a generic save method that works for both sub-directory * installations and own url installations. * @@ -104,4 +116,17 @@ // Set the cookie for 30 days return self::set(self::LOCALE_COOKIE, $locale, 30, $basepath); } + + /** + * Store the organization in a cookie. + * + * @param int $locale Organization to store + * @param string $basepath The folder of the domain, if any. + * @return boolean True if the cookie was stored. + */ + public static function setOrganization($locale, $basepath = '/') + { + // Set the cookie for 30 days + return self::set(self::ORGANIZATION_COOKIE, $locale, 30, $basepath); + } } Modified: trunk/library/classes/Gems/Default/IndexAction.php =================================================================== --- trunk/library/classes/Gems/Default/IndexAction.php 2011-11-08 10:42:02 UTC (rev 192) +++ trunk/library/classes/Gems/Default/IndexAction.php 2011-11-08 12:46:17 UTC (rev 193) @@ -234,9 +234,10 @@ $this->escort->afterLogin($_POST['userlogin']); /** - * Fix current locale + * Fix current locale & organization */ Gems_Cookies::setLocale($this->session->user_locale, $this->basepath->getBasePath()); + Gems_Cookies::setOrganization($this->session->user_organization_id, $this->basepath->getBasePath()); /** * Ready Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2011-11-08 10:42:02 UTC (rev 192) +++ trunk/library/classes/GemsEscort.php 2011-11-08 12:46:17 UTC (rev 193) @@ -1115,6 +1115,7 @@ */ public function getCurrentOrganization() { + /* if ($this instanceof Gems_Project_Organization_MultiOrganizationInterface) { return $this->getUserOrganization(); } @@ -1122,11 +1123,12 @@ if ($this instanceof Gems_Project_Organization_SingleOrganizationInterface) { return $this->getRespondentOrganization(); } + */ if (isset($this->session->user_organization_id)) { return $this->session->user_organization_id; } else { - return 0; + return Gems_Cookies::getOrganization(Zend_Controller_Front::getInstance()->getRequest()); } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-11-16 13:19:51
|
Revision: 222 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=222&view=rev Author: matijsdejong Date: 2011-11-16 13:19:44 +0000 (Wed, 16 Nov 2011) Log Message: ----------- On windows servers the PHP session ID was stored for '/' instead of '\'. Many browsers lost the session ID because of this. Modified Paths: -------------- trunk/library/classes/Gems/Default/OrganizationAction.php trunk/library/classes/GemsEscort.php Modified: trunk/library/classes/Gems/Default/OrganizationAction.php =================================================================== --- trunk/library/classes/Gems/Default/OrganizationAction.php 2011-11-15 15:35:22 UTC (rev 221) +++ trunk/library/classes/Gems/Default/OrganizationAction.php 2011-11-16 13:19:44 UTC (rev 222) @@ -26,20 +26,25 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * @author Matijs de Jong - * @since 1.0 - * @version 1.1 - * @package Gems + * + * @package Gems * @subpackage Default + * @author Matijs de Jong <mj...@ma...> + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @version $Id$ */ /** + * Generic controller class for showing and editing organizations * - * @author Matijs de Jong - * @package Gems + * @package Gems * @subpackage Default + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @since Class available since version 1.0 */ -class Gems_Default_OrganizationAction extends Gems_Controller_BrowseEditAction +class Gems_Default_OrganizationAction extends Gems_Controller_BrowseEditAction // Gems_Controller_ModelSnippetActionAbstract { public $autoFilter = false; @@ -92,7 +97,7 @@ } $this->session->requestCache = $requestCache; - if (Gems_Cookies::set('organization', $orgId)) { + if (Gems_Cookies::setOrganization($orgId, $this->basepath->getBasePath())) { $this->getResponse()->setRedirect($url); return; } Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2011-11-15 15:35:22 UTC (rev 221) +++ trunk/library/classes/GemsEscort.php 2011-11-16 13:19:44 UTC (rev 222) @@ -90,12 +90,10 @@ $firebug = $application->getOption('firebug'); $this->_startFirebird = $firebug['log']; - Zend_Session::start( - array( - 'name' => GEMS_PROJECT_NAME_UC . 'SESSID', - 'cookie_path' => dirname($_SERVER['SCRIPT_NAME']) - ) - ); + $sessionOptions['name'] = GEMS_PROJECT_NAME_UC . 'SESSID'; + $sessionOptions['cookie_path'] = strtr(dirname($_SERVER['SCRIPT_NAME']), '\\', '/'); + + Zend_Session::start($sessionOptions); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-11-18 11:26:06
|
Revision: 234 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=234&view=rev Author: matijsdejong Date: 2011-11-18 11:26:00 +0000 (Fri, 18 Nov 2011) Log Message: ----------- Bug in handling whenNew items. Made code more readable. Modified Paths: -------------- trunk/library/classes/Gems/Auth.php trunk/library/classes/MUtil/Model/ModelAbstract.php Modified: trunk/library/classes/Gems/Auth.php =================================================================== --- trunk/library/classes/Gems/Auth.php 2011-11-18 09:34:55 UTC (rev 233) +++ trunk/library/classes/Gems/Auth.php 2011-11-18 11:26:00 UTC (rev 234) @@ -93,7 +93,8 @@ private function _error($code, $value1 = null, $value2 = null) { $messages = func_get_args(); - array_splice($messages, 0, 1, $this->_messageTemplates[$code]); + // array_splice($messages, 0, 1, $this->_messageTemplates[$code]); + $messages[0] = $this->_messageTemplates[$code]; return new Zend_Auth_Result($code, null, (array) $messages); } Modified: trunk/library/classes/MUtil/Model/ModelAbstract.php =================================================================== --- trunk/library/classes/MUtil/Model/ModelAbstract.php 2011-11-18 09:34:55 UTC (rev 233) +++ trunk/library/classes/MUtil/Model/ModelAbstract.php 2011-11-18 11:26:00 UTC (rev 234) @@ -660,11 +660,11 @@ { if ($call = $this->get($name, self::SAVE_TRANSFORMER)) { - if (is_callable($call)) { - $value = call_user_func($call, $value, $new, $name, $context); - } else { - $value = $call; - } + if (is_callable($call)) { + $value = call_user_func($call, $value, $new, $name, $context); + } else { + $value = $call; + } } return $value; @@ -812,7 +812,7 @@ if ($test = $this->get($name, self::SAVE_WHEN_TEST)) { if (is_callable($test)) { - return call_user_func($test, $name, $value, $new); + return call_user_func($test, $value, $new, $name, $context); } return $test; @@ -1263,7 +1263,7 @@ public function setSaveWhenNew($name) { $this->setAutoSave($name); - return $this->setSaveWhen($name, array(__CLASS__, 'whenNotNew')); + return $this->setSaveWhen($name, array(__CLASS__, 'whenNew')); } /** @@ -1318,9 +1318,9 @@ * @param array $context Optional, the other values being saved * @return boolean */ - public static function whenNotNew($value, $isNew = false, $name = null, array $context = array()) + public static function whenNew($value, $isNew = false, $name = null, array $context = array()) { - return $new; + return $isNew; } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-11-21 10:18:28
|
Revision: 247 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=247&view=rev Author: matijsdejong Date: 2011-11-21 10:18:22 +0000 (Mon, 21 Nov 2011) Log Message: ----------- The plan was to stop using these $this->project|session->variablenames. (Plus I got a warning as session did not exist.) Modified Paths: -------------- trunk/library/classes/Gems/Project/ProjectSettings.php trunk/library/classes/GemsEscort.php Modified: trunk/library/classes/Gems/Project/ProjectSettings.php =================================================================== --- trunk/library/classes/Gems/Project/ProjectSettings.php 2011-11-21 09:54:34 UTC (rev 246) +++ trunk/library/classes/Gems/Project/ProjectSettings.php 2011-11-21 10:18:22 UTC (rev 247) @@ -47,6 +47,15 @@ class Gems_Project_ProjectSettings extends ArrayObject { /** + * The default session time out for this project in seconds. + * + * Can be overruled in sesssion.idleTimeout + * + * @var int + */ + protected $defaultSessionTimeout = 1800; + + /** * The minimum length for the password of a super admin * on a production server. * @@ -215,6 +224,20 @@ } /** + * Timeout for sessions in seconds. + * + * @return int + */ + public function getSessionTimeOut() + { + if (isset($this->session, $this->session['idleTimeout'])) { + return $this->session['idleTimeout']; + } else { + return $this->defaultSessionTimeout; + } + } + + /** * Returns the super admin name, if any * * @return string Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2011-11-21 09:54:34 UTC (rev 246) +++ trunk/library/classes/GemsEscort.php 2011-11-21 10:18:22 UTC (rev 247) @@ -58,7 +58,7 @@ private $_copyDestinations; private $_startFirebird; - + /** * The menu variable * @@ -89,7 +89,7 @@ $firebug = $application->getOption('firebug'); $this->_startFirebird = $firebug['log']; - + $sessionOptions['name'] = GEMS_PROJECT_NAME_UC . 'SESSID'; $sessionOptions['cookie_path'] = strtr(dirname($_SERVER['SCRIPT_NAME']), '\\', '/'); @@ -385,10 +385,11 @@ */ protected function _initSession() { + $session = new Zend_Session_Namespace('gems.' . GEMS_PROJECT_NAME . '.session'); - - $idleTimeout = ($this->project->session['idleTimeout'] ? $this->project->session['idleTimeout'] : 1800); - + + $idleTimeout = $this->project->getSessionTimeOut(); + $session->setExpirationSeconds($idleTimeout); if (! isset($session->user_role)) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-11-22 17:34:58
|
Revision: 274 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=274&view=rev Author: matijsdejong Date: 2011-11-22 17:34:49 +0000 (Tue, 22 Nov 2011) Log Message: ----------- Allow org switching for orgs accessible by others for #40 Modified Paths: -------------- trunk/library/classes/Gems/Default/OrganizationAction.php trunk/library/classes/Gems/User/OldStaffUserDefinition.php trunk/library/classes/Gems/User/ProjectUserDefinition.php trunk/library/classes/Gems/User/StaffUserDefinition.php trunk/library/classes/Gems/User/User.php trunk/library/classes/Gems/User/UserLoader.php trunk/library/classes/GemsEscort.php Modified: trunk/library/classes/Gems/Default/OrganizationAction.php =================================================================== --- trunk/library/classes/Gems/Default/OrganizationAction.php 2011-11-22 15:59:21 UTC (rev 273) +++ trunk/library/classes/Gems/Default/OrganizationAction.php 2011-11-22 17:34:49 UTC (rev 274) @@ -52,6 +52,10 @@ { $org = $this->loader->getOrganization($data['gor_id_organization']); $org->invalidateCache(); + + // Make sure any changes in the allowed list are reflected. + $this->loader->getCurrentUser()->refreshAllowedOrganizations(); + return parent::afterSave($data, $isNew); } Modified: trunk/library/classes/Gems/User/OldStaffUserDefinition.php =================================================================== --- trunk/library/classes/Gems/User/OldStaffUserDefinition.php 2011-11-22 15:59:21 UTC (rev 273) +++ trunk/library/classes/Gems/User/OldStaffUserDefinition.php 2011-11-22 17:34:49 UTC (rev 274) @@ -148,7 +148,7 @@ // For a multi-layout project we need to select the appropriate style too, // but as PATCHES may not be in effect we have to try two selects $select2 = clone $select; - $select2->columns(array('user_style' => 'gor_style', 'user_allowed_ip_ranges' => 'ggp_allowed_ip_ranges'), 'gems__organizations'); + $select2->columns(array('user_style' => 'gor_style', 'user_allowed_ip_ranges' => 'ggp_allowed_ip_ranges', 'accessible_by' => 'gor_accessible_by'), 'gems__organizations'); try { // Fails before patch has run... Modified: trunk/library/classes/Gems/User/ProjectUserDefinition.php =================================================================== --- trunk/library/classes/Gems/User/ProjectUserDefinition.php 2011-11-22 15:59:21 UTC (rev 273) +++ trunk/library/classes/Gems/User/ProjectUserDefinition.php 2011-11-22 17:34:49 UTC (rev 274) @@ -77,7 +77,6 @@ 'user_organization_id' => $organization, 'user_organization_name' => 'SUPER ADMIN', 'user_allowed_ip_ranges' => $this->project->getSuperAdminIPRanges(), - 'allowedOrgs' => array($organization => 'SUPER ADMIN') ); } } \ No newline at end of file Modified: trunk/library/classes/Gems/User/StaffUserDefinition.php =================================================================== --- trunk/library/classes/Gems/User/StaffUserDefinition.php 2011-11-22 15:59:21 UTC (rev 273) +++ trunk/library/classes/Gems/User/StaffUserDefinition.php 2011-11-22 17:34:49 UTC (rev 274) @@ -193,9 +193,10 @@ ->join('gems__groups', 'gsf_id_primary_group = ggp_id_group', array('user_role'=>'ggp_role', 'user_allowed_ip_ranges' => 'ggp_allowed_ip_ranges')) ->join('gems__organizations', 'gul_id_organization = gor_id_organization', array( - 'user_organization_id'=>'gor_id_organization', - 'user_organization_name'=>'gor_name', - 'user_style' => 'gor_style')) + 'user_organization_id' => 'gor_id_organization', + 'user_organization_name' => 'gor_name', + 'user_style' => 'gor_style', + 'accessible_by' => 'gor_accessible_by')) ->joinLeft('gems__user_passwords', 'gul_id_user = gup_id_user', array('user_password_reset' => 'gup_reset_required')) ->where('ggp_group_active = 1') Modified: trunk/library/classes/Gems/User/User.php =================================================================== --- trunk/library/classes/Gems/User/User.php 2011-11-22 15:59:21 UTC (rev 273) +++ trunk/library/classes/Gems/User/User.php 2011-11-22 17:34:49 UTC (rev 274) @@ -66,6 +66,12 @@ /** * + * @var Zend_Db_Adapter_Abstract + */ + protected $db; + + /** + * * @var Gems_User_UserDefinitionInterface */ protected $definition; @@ -204,9 +210,9 @@ public function authenticate($formValues) { $auth = Gems_Auth::getInstance(); - + $formValues['allowed_ip_ranges'] = $this->getAllowedIPRanges(); - + $adapter = $this->definition->getAuthAdapter($formValues); $authResult = $auth->authenticate($adapter, $formValues); @@ -280,17 +286,33 @@ $this->setAsCurrentUser(); } } + + if (! $this->_hasVar('__allowedOrgs')) { + // Is always requested so no win in waiting. + $this->refreshAllowedOrganizations(); + } + return true; } /** + * Returns the list of allowed IP ranges (separated by colon) + * + * @return string + */ + public function getAllowedIPRanges() + { + return $this->_getVar('user_allowed_ip_ranges'); + } + + /** * Get an array of OrgId => Org Name for all allowed organizations for the current loggedin user * * @return array */ public function getAllowedOrganizations() { - return $this->_getVar('allowedOrgs'); + return $this->_getVar('__allowedOrgs'); } /** @@ -346,16 +368,6 @@ { return $this->_getVar('user_group'); } - - /** - * Returns the list of allowed IP ranges (separated by colon) - * - * @return string - */ - public function getAllowedIPRanges() - { - return $this->_getVar('user_allowed_ip_ranges'); - } /** * The locale set for this user.. @@ -519,7 +531,18 @@ } /** + * Returns true if the role of the current user has the given privilege * + * @param string $privilege + * @return bool + */ + public function hasPrivilege($privilege) + { + return (! $this->acl) || $this->acl->isAllowed($this->getRole(), null, $privilege); + } + + /** + * * @return boolean True when a user can log in. */ public function isActive() @@ -558,6 +581,47 @@ } /** + * Allowes a refresh of the existing list of organizations + * for this user. + * + * @return Gems_User_User (continuation pattern) + */ + public function refreshAllowedOrganizations() + { + $sql = "SELECT gor_id_organization, gor_name FROM gems__organizations WHERE "; + + // Privilege overrules organizational settings + if (! $this->hasPrivilege('pr.organization-switch')) { + if ($by = $this->_getVar('accessible_by')) { + $orgs = explode(':', trim($by, ':')); + + if ($orgs) { + // Not to forget: the users own organization + $orgs[] = $this->getOrganizationId(); + + $sql .= "gor_id_organization IN ("; + $sql .= implode(', ', $orgs); + $sql .= ") AND "; + } else { + $sql = false; + } + } else { + $sql = false; + } + } + if ($sql) { + $sql .= " gor_active = 1 ORDER BY gor_name"; + $orgs = $this->db->fetchPairs($sql); + } else { + $orgs = array(); + } + + $this->_setVar('__allowedOrgs', $orgs); + + return $this; + } + + /** * Check for password weakness. * * @param string $password Modified: trunk/library/classes/Gems/User/UserLoader.php =================================================================== --- trunk/library/classes/Gems/User/UserLoader.php 2011-11-22 15:59:21 UTC (rev 273) +++ trunk/library/classes/Gems/User/UserLoader.php 2011-11-22 17:34:49 UTC (rev 274) @@ -207,10 +207,6 @@ $values['user_active'] = true; } - if (! isset($values['allowedOrgs'])) { - //Load the allowed organizations - $values['allowedOrgs'] = $this->getAllowedOrganizations(); - } $values['__user_definition'] = $defName; return $this->_loadClass('User', true, array($values, $definition)); Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2011-11-22 15:59:21 UTC (rev 273) +++ trunk/library/classes/GemsEscort.php 2011-11-22 17:34:49 UTC (rev 274) @@ -795,7 +795,8 @@ */ protected function _layoutOrganizationSwitcher() // Gems_Project_Organization_MultiOrganizationInterface { - if ($this->hasPrivilege('pr.organization-switch')) { + $user = $this->getLoader()->getCurrentUser(); + if ($orgs = $user->getAllowedOrganizations()) { // Organization switcher $orgSwitch = MUtil_Html::create('div', array('id' => 'organizations')); $currentUri = base64_encode($this->view->url()); @@ -805,9 +806,9 @@ 'controller' => 'organization', 'action' => 'change-ui'), null, true); $orgSwitch->raw('<form method="get" action="' . $url . '"><div><input type="hidden" name="current_uri" value="' . $currentUri . '" /><select name="org" onchange="javascript:this.form.submit();">'); - foreach ($this->getLoader()->getCurrentUser()->getAllowedOrganizations() as $id => $org) { + foreach ($orgs as $id => $org) { $selected = ''; - if ($id == $this->session->user_organization_id) { + if ($id == $user->getOrganizationId()) { $selected = ' selected="selected"'; } else { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-11-24 15:13:50
|
Revision: 281 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=281&view=rev Author: matijsdejong Date: 2011-11-24 15:13:38 +0000 (Thu, 24 Nov 2011) Log Message: ----------- Split User->getOrganizationId into User->getBaseOrganizationId and User->getCurrentOrganizationId. user_organization info no longer part of return of getUserData(), but set buy setCurrentOrganization. Added checks on $this->menu to _layout functions so that error messages remain displayed, even when the menu is not active. ($#&@!) Modified Paths: -------------- trunk/library/classes/Gems/Default/AskAction.php trunk/library/classes/Gems/Default/IndexAction.php trunk/library/classes/Gems/Default/OrganizationAction.php trunk/library/classes/Gems/User/NoLoginDefinition.php trunk/library/classes/Gems/User/OldStaffUserDefinition.php trunk/library/classes/Gems/User/Organization.php trunk/library/classes/Gems/User/ProjectUserDefinition.php trunk/library/classes/Gems/User/StaffUserDefinition.php trunk/library/classes/Gems/User/User.php trunk/library/classes/Gems/User/UserLoader.php trunk/library/classes/GemsEscort.php trunk/library/classes/MUtil/Controller/Action.php Modified: trunk/library/classes/Gems/Default/AskAction.php =================================================================== --- trunk/library/classes/Gems/Default/AskAction.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/Default/AskAction.php 2011-11-24 15:13:38 UTC (rev 281) @@ -121,7 +121,7 @@ $this->view->headMeta()->appendHttpEquiv('Refresh', $delay . '; url=' . $url); } - $organizationData = $this->db->fetchRow("SELECT * FROM gems__organizations WHERE gor_id_organization = ?", $token->getOrganizationId()); + $organization = $this->loader->getOrganization($token->getOrganizationId()); Gems_Html::init(); // Turn on Gems specific html like pInfo $this->html->h3($this->_('Token')); @@ -131,8 +131,8 @@ $this->html->pInfo(sprintf($this->_('Thank you for answering the survey for token %s.'), strtoupper($this->_getParam(MUtil_Model::REQUEST_ID)))); $this->html->pInfo($this->_('Please click the button below to answer the next survey.')); } else { - if ($organizationData['gor_welcome']) { - $this->html->pInfo()->raw(MUtil_Markup::render($this->_($organizationData['gor_welcome']), 'Bbcode', 'Html')); + if ($welcome = $organization->getWelcome()) { + $this->html->pInfo()->raw(MUtil_Markup::render($this->_($welcome), 'Bbcode', 'Html')); } $this->html->pInfo(sprintf($this->_('Please click the button below to answer the survey for token %s.'), strtoupper($tokenId))); } @@ -157,8 +157,8 @@ 'After this survey there are another %d surveys we would like you to answer.', $next), $next)); } - if ($organizationData['gor_signature']) { - $this->html->pInfo()->raw(MUtil_Markup::render($this->_($organizationData['gor_signature']), 'Bbcode', 'Html')); + if ($sig = $organization->getSignature()) { + $this->html->pInfo()->raw(MUtil_Markup::render($this->_($sig), 'Bbcode', 'Html')); } return; @@ -216,20 +216,20 @@ if ($this->_request->isPost()) { $throttleSettings = $this->project->getAskThrottleSettings(); - + // Prune the database for (very) old attempts - $this->db->query("DELETE FROM gems__token_attempts WHERE gta_datetime < DATE_SUB(NOW(), INTERVAL ? second)", + $this->db->query("DELETE FROM gems__token_attempts WHERE gta_datetime < DATE_SUB(NOW(), INTERVAL ? second)", $throttleSettings['period'] * 20); - + // Retrieve the number of failed attempts that occurred within the specified window - $attemptData = $this->db->fetchRow("SELECT COUNT(1) AS attempts, UNIX_TIMESTAMP(MAX(gta_datetime)) AS last " . + $attemptData = $this->db->fetchRow("SELECT COUNT(1) AS attempts, UNIX_TIMESTAMP(MAX(gta_datetime)) AS last " . "FROM gems__token_attempts WHERE gta_datetime > DATE_SUB(NOW(), INTERVAL ? second)", $throttleSettings['period']); - + $remainingDelay = ($attemptData['last'] + $throttleSettings['delay']) - time(); - + if ($attemptData['attempts'] > $throttleSettings['threshold'] && $remainingDelay > 0) { $this->escort->logger->log("Possible token brute force attack, throttling for $remainingDelay seconds", Zend_Log::ERR); - + $this->addMessage($this->_('The server is currently busy, please wait a while and try again.')); } else if ($form->isValid($_POST)) { $this->_forward('forward'); Modified: trunk/library/classes/Gems/Default/IndexAction.php =================================================================== --- trunk/library/classes/Gems/Default/IndexAction.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/Default/IndexAction.php 2011-11-24 15:13:38 UTC (rev 281) @@ -164,7 +164,7 @@ $element->setRequired(true); if (! $this->_request->isPost()) { - $element->setValue($this->loader->getCurrentUser()->getOrganizationId()); + $element->setValue($this->loader->getCurrentUser()->getCurrentOrganizationId()); } } @@ -293,7 +293,6 @@ * Fix current locale / organization in cookies */ Gems_Cookies::setLocale($user->getLocale(), $this->basepath->getBasePath()); - Gems_Cookies::setOrganization($user->getOrganizationId(), $this->basepath->getBasePath()); /** * Ready Modified: trunk/library/classes/Gems/Default/OrganizationAction.php =================================================================== --- trunk/library/classes/Gems/Default/OrganizationAction.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/Default/OrganizationAction.php 2011-11-24 15:13:38 UTC (rev 281) @@ -75,7 +75,6 @@ $request = $this->getRequest(); $orgId = urldecode($request->getParam('org')); $url = base64_decode($request->getParam('current_uri')); - $oldOrgId = $user->getOrganizationId(); $allowedOrganizations = $user->getAllowedOrganizations(); if (isset($allowedOrganizations[$orgId])) { Modified: trunk/library/classes/Gems/User/NoLoginDefinition.php =================================================================== --- trunk/library/classes/Gems/User/NoLoginDefinition.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/User/NoLoginDefinition.php 2011-11-24 15:13:38 UTC (rev 281) @@ -69,7 +69,6 @@ return array( 'user_active' => false, 'user_role' => 'nologin', - //'user_organization_id' => 0, //REMOVED AS IT BREAKS STORING LAST ORGANIZATION ); } } Modified: trunk/library/classes/Gems/User/OldStaffUserDefinition.php =================================================================== --- trunk/library/classes/Gems/User/OldStaffUserDefinition.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/User/OldStaffUserDefinition.php 2011-11-24 15:13:38 UTC (rev 281) @@ -174,18 +174,15 @@ * compatibility */ $select = new Zend_Db_Select($this->db); - $select->from('gems__staff', array('user_id'=>'gsf_id_user', - 'user_login'=>'gsf_login', - 'user_email'=>'gsf_email', - 'user_group'=>'gsf_id_primary_group', - 'user_locale'=>'gsf_iso_lang', - 'user_logout'=>'gsf_logout_on_survey')) + $select->from('gems__staff', array('user_id' => 'gsf_id_user', + 'user_login' => 'gsf_login', + 'user_email' => 'gsf_email', + 'user_group' => 'gsf_id_primary_group', + 'user_locale' => 'gsf_iso_lang', + 'user_logout' => 'gsf_logout_on_survey', + 'user_base_org_id' => 'gsf_id_organization')) ->columns(array('user_name'=>"(concat(coalesce(concat(`gems__staff`.`gsf_first_name`,_utf8' '),_utf8''),coalesce(concat(`gems__staff`.`gsf_surname_prefix`,_utf8' '),_utf8''),coalesce(`gems__staff`.`gsf_last_name`,_utf8'')))")) ->join('gems__groups', 'gsf_id_primary_group = ggp_id_group', array('user_role'=>'ggp_role')) - ->join('gems__organizations', 'gsf_id_organization = gor_id_organization', - array( - 'user_organization_id'=>'gor_id_organization', - 'user_organization_name'=>'gor_name')) ->where('ggp_group_active = 1') ->where('gor_active = 1') ->where('gsf_active = 1') Modified: trunk/library/classes/Gems/User/Organization.php =================================================================== --- trunk/library/classes/Gems/User/Organization.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/User/Organization.php 2011-11-24 15:13:38 UTC (rev 281) @@ -216,6 +216,16 @@ } /** + * Get the signature of the organization. + * + * @return string + */ + public function getSignature() + { + return $this->_organizationData['gor_signature']; + } + + /** * Get the style attribute. * * @return string @@ -225,6 +235,16 @@ return $this->_organizationData['gor_style']; } + /** + * Get the welcome message for the organization. + * + * @return string + */ + public function getWelcome() + { + return $this->_organizationData['gor_welcome']; + } + public function invalidateCache() { if ($this->cache) { $cacheId = $this->_getCacheId(); Modified: trunk/library/classes/Gems/User/ProjectUserDefinition.php =================================================================== --- trunk/library/classes/Gems/User/ProjectUserDefinition.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/User/ProjectUserDefinition.php 2011-11-24 15:13:38 UTC (rev 281) @@ -68,14 +68,13 @@ public function getUserData($login_name, $organization) { return array( - 'user_id' => 1, - 'user_login' => $login_name, - 'user_name' => $login_name, - 'user_group' => 800, - 'user_role' => 'master', - 'user_style' => 'gems', - 'user_organization_id' => $organization, - 'user_organization_name' => 'SUPER ADMIN', + 'user_id' => 1, + 'user_login' => $login_name, + 'user_name' => $login_name, + 'user_group' => 800, + 'user_role' => 'master', + 'user_style' => 'gems', + 'user_base_org_id' => $organization, 'user_allowed_ip_ranges' => $this->project->getSuperAdminIPRanges(), ); } Modified: trunk/library/classes/Gems/User/StaffUserDefinition.php =================================================================== --- trunk/library/classes/Gems/User/StaffUserDefinition.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/User/StaffUserDefinition.php 2011-11-24 15:13:38 UTC (rev 281) @@ -183,12 +183,13 @@ $select = new Zend_Db_Select($this->db); $select->from('gems__user_logins', array('user_login_id' => 'gul_id_user')) ->join('gems__staff', 'gul_login = gsf_login AND gul_id_organization = gsf_id_organization', array( - 'user_login' => 'gsf_login', - 'user_id' => 'gsf_id_user', - 'user_email'=>'gsf_email', - 'user_group'=>'gsf_id_primary_group', - 'user_locale'=>'gsf_iso_lang', - 'user_logout'=>'gsf_logout_on_survey')) + 'user_id' => 'gsf_id_user', + 'user_login' => 'gsf_login', + 'user_email' => 'gsf_email', + 'user_group' => 'gsf_id_primary_group', + 'user_locale' => 'gsf_iso_lang', + 'user_logout' => 'gsf_logout_on_survey', + 'user_base_org_id' => 'gsf_id_organization')) ->columns(array('user_name'=>"(concat(coalesce(concat(`gems__staff`.`gsf_first_name`,_utf8' '),_utf8''),coalesce(concat(`gems__staff`.`gsf_surname_prefix`,_utf8' '),_utf8''),coalesce(`gems__staff`.`gsf_last_name`,_utf8'')))")) ->join('gems__groups', 'gsf_id_primary_group = ggp_id_group', array('user_role'=>'ggp_role', 'user_allowed_ip_ranges' => 'ggp_allowed_ip_ranges')) ->join('gems__organizations', 'gul_id_organization = gor_id_organization', Modified: trunk/library/classes/Gems/User/User.php =================================================================== --- trunk/library/classes/Gems/User/User.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/User/User.php 2011-11-24 15:13:38 UTC (rev 281) @@ -94,6 +94,12 @@ protected $session; /** + * + * @var Zend_Translate + */ + protected $translate; + + /** * Required * * @var Gems_User_UserLoader @@ -328,16 +334,42 @@ } /** - * Returns the name of the user definition. + * Returns the original (not the current) organization id of this user. * - * @return string - * NOT NEEDED FOR THE MOMENT / - public function getDefinitionName() + * @return int + */ + public function getBaseOrganizationId() { - return $this->_getVar('__user_definition'); - } // */ + return $this->_getVar('user_base_org_id'); + } /** + * Returns the organization that is currently used by this user. + * + * @return Gems_User_Organization + */ + public function getCurrentOrganization() + { + return $this->userLoader->getOrganization($this->getCurrentOrganizationId()); + } + + /** + * Returns the organization id that is currently used by this user. + * + * @return int + */ + public function getCurrentOrganizationId() + { + $orgId = $this->_getVar('user_organization_id'); + + //If not set, read it from the cookie + if (is_null($orgId)) { + $orgId = Gems_Cookies::getOrganization(Zend_Controller_Front::getInstance()->getRequest()); + } + return $orgId; + } + + /** * Return true if this user has a password. * * @return boolean @@ -358,7 +390,7 @@ return array( 'userlogin' => $this->getLoginName(), 'password' => $password, - 'organization' => $this->getOrganizationId()); + 'organization' => $this->getCurrentOrganizationId()); } /** @@ -401,42 +433,6 @@ } /** - * - * @return Gems_User_Organization - */ - public function getOrganization() - { - return $this->userLoader->getOrganization($this->getOrganizationId()); - } - - /** - * - * @return int - */ - public function getOrganizationId() - { - $orgId = $this->_getVar('user_organization_id'); - - //If not set, read it from the cookie - if (is_null($orgId)) { - $orgId = Gems_Cookies::getOrganization(Zend_Controller_Front::getInstance()->getRequest()); - } - return $orgId; - } - - /** - * Gets the (optional) organization code. - * - * @return string - * NOT NEEDED FOR THE MOMENT / - public function getOrganizationCode() - { - $organizationId = $this->getOrganizationId(); - - return $this->userLoader->getOrganization($organizationId)->getCode(); - } // */ - - /** * Return a password reset key * * @return string @@ -618,7 +614,7 @@ if ($orgs) { // Not to forget: the users own organization - $orgs[] = $this->getOrganizationId(); + $orgs[] = $this->getBaseOrganizationId(); $sql .= "gor_id_organization IN ("; $sql .= implode(', ', $orgs); @@ -653,7 +649,7 @@ if ($this->canSetPassword()) { $checker = $this->userLoader->getPasswordChecker(); - $codes[] = $this->getOrganization()->getCode(); + $codes[] = $this->getCurrentOrganization()->getCode(); $codes[] = $this->getRoles(); $codes[] = $this->_getVar('__user_definition'); @@ -707,44 +703,47 @@ $organization = $this->userLoader->getOrganization($organizationId); } - $oldOrganizationId = $this->getOrganizationId(); + $oldOrganizationId = $this->getCurrentOrganizationId(); - if ($organizationId != $oldOrganizationId) { - $this->_setVar('user_organization_id', $organizationId); + if ($organizationId) { + if ($organizationId != $oldOrganizationId) { + $this->_setVar('user_organization_id', $organizationId); - // Depreciation warning: the settings will be removed in - // version 1.6 at the latest. - $this->_setVar('user_organization_name', $organization->getName()); - $this->_setVar('user_style', $organization->getStyle()); - // End depreciation warning + // Depreciation warning: the settings will be removed in + // version 1.6 at the latest. + $this->_setVar('user_organization_name', $organization->getName()); + $this->_setVar('user_style', $organization->getStyle()); + // End depreciation warning - if ($this->isCurrentUser()) { - // Now update the requestcache to change the oldOrgId to the new orgId - // Don't do it when the oldOrgId doesn't match - $requestCache = $this->session->requestCache; + if ($this->isCurrentUser()) { + // Now update the requestcache to change the oldOrgId to the new orgId + // Don't do it when the oldOrgId doesn't match + if ($requestCache = $this->session->requestCache) { - //Create the list of request cache keys that match an organization ID (to be extended) - $possibleOrgIds = array( - 'gr2o_id_organization', - 'gto_id_organization'); + //Create the list of request cache keys that match an organization ID (to be extended) + $possibleOrgIds = array( + 'gr2o_id_organization', + 'gto_id_organization'); - foreach ($requestCache as $key => $value) { - if (is_array($value)) { - foreach ($value as $paramKey => $paramValue) { - if (in_array($paramKey, $possibleOrgIds)) { - if ($paramValue == $oldOrganizationId) { - $requestCache[$key][$paramKey] = $organizationId; + foreach ($requestCache as $key => $value) { + if (is_array($value)) { + foreach ($value as $paramKey => $paramValue) { + if (in_array($paramKey, $possibleOrgIds)) { + if ($paramValue == $oldOrganizationId) { + $requestCache[$key][$paramKey] = $organizationId; + } + } } } } + $this->session->requestCache = $requestCache; } } - $this->session->requestCache = $requestCache; } - } - if (! Gems_Cookies::setOrganization($organizationId, $this->basepath->getBasePath())) { - throw new Exception($this->_('Cookies must be enabled for this site.')); + if (! Gems_Cookies::setOrganization($organizationId, $this->basepath->getBasePath())) { + throw new Exception($this->translate->_('Cookies must be enabled for this site.')); + } } return $this; Modified: trunk/library/classes/Gems/User/UserLoader.php =================================================================== --- trunk/library/classes/Gems/User/UserLoader.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/Gems/User/UserLoader.php 2011-11-24 15:13:38 UTC (rev 281) @@ -167,7 +167,7 @@ static $organizations = array(); if (null === $organizationId) { - $organizationId = intval(self::$currentUser->getOrganizationId()); + $organizationId = intval(self::$currentUser->getCurrentOrganizationId()); } if (! isset($organizations[$organizationId])) { @@ -209,7 +209,11 @@ $values['__user_definition'] = $defName; - return $this->_loadClass('User', true, array($values, $definition)); + $user = $this->_loadClass('User', true, array($values, $definition)); + + $user->setCurrentOrganization($organization); + + return $user; } /** Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/GemsEscort.php 2011-11-24 15:13:38 UTC (rev 281) @@ -376,7 +376,6 @@ * -- user_role * -- user_locale * -- user_organization_id - * -- user_organization_name * * Use $this->session to access afterwards * @@ -538,19 +537,21 @@ */ protected function _layoutContact(array $args = null) { - $menuItem = $this->menu->find(array('controller' => 'contact', 'action' => 'index')); + if ($this->menu instanceof Gems_Menu) { + $menuItem = $this->menu->find(array('controller' => 'contact', 'action' => 'index')); - if ($menuItem) { - $contactDiv = MUtil_Html::create()->div( - $args, - array('id' => 'contact')); // tooltip - $contactDiv->a($menuItem->toHRefAttribute(), $menuItem->get('label')); + if ($menuItem) { + $contactDiv = MUtil_Html::create()->div( + $args, + array('id' => 'contact')); // tooltip + $contactDiv->a($menuItem->toHRefAttribute(), $menuItem->get('label')); - $ul = $menuItem->toUl(); - $ul->class = 'dropdownContent tooltip'; - $contactDiv->append($ul); + $ul = $menuItem->toUl(); + $ul->class = 'dropdownContent tooltip'; + $contactDiv->append($ul); - return $contactDiv; + return $contactDiv; + } } } @@ -798,7 +799,8 @@ $user = $this->getLoader()->getCurrentUser(); if ($orgs = $user->getAllowedOrganizations()) { // Organization switcher - $orgSwitch = MUtil_Html::create('div', array('id' => 'organizations')); + $orgSwitch = MUtil_Html::create('div', array('id' => 'organizations')); + $currentId = $user->getCurrentOrganizationId(); $currentUri = base64_encode($this->view->url()); $url = $this->view->getHelper('url')->url(array('controller' => 'organization', 'action' => 'change-ui'), null, true); @@ -809,7 +811,7 @@ $select = $formDiv->select(array('name' => "org", 'onchange' => "javascript:this.form.submit();")); foreach ($orgs as $id => $org) { $selected = ''; - if ($id == $user->getOrganizationId()) { + if ($id == $currentId) { $selected = array('selected' => "selected"); } $select->option(array('value' => $id), $org, $selected); @@ -902,7 +904,8 @@ { $div = MUtil_Html::create()->div($args, array('id' => 'version')); $version = $this->loader->getVersions()->getVersion(); - if ($item = $this->menu->findFirst(array('controller'=>'project-information', 'action'=>'changelog'))->toHRefAttribute()) { + if (($this->menu instanceof Gems_Menu) && + ($item = $this->menu->findFirst(array('controller'=>'project-information', 'action'=>'changelog'))->toHRefAttribute())) { $link = MUtil_Html::create()->a($version, $item); } else { $link = $version; @@ -1073,7 +1076,7 @@ */ public function getCurrentOrganization() { - return $this->getLoader()->getCurrentUser()->getOrganizationId(); + return $this->getLoader()->getCurrentUser()->getCurrentOrganizationId(); } /** Modified: trunk/library/classes/MUtil/Controller/Action.php =================================================================== --- trunk/library/classes/MUtil/Controller/Action.php 2011-11-24 14:25:16 UTC (rev 280) +++ trunk/library/classes/MUtil/Controller/Action.php 2011-11-24 15:13:38 UTC (rev 281) @@ -4,7 +4,7 @@ /** * Copyright (c) 2011, Erasmus MC * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright @@ -15,7 +15,7 @@ * * Neither the name of Erasmus MC nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE @@ -71,7 +71,7 @@ * @var MUtil_Snippets_SnippetLoader */ protected $snippetLoader; - + /** * The current html/head/title for this page. * @@ -131,7 +131,7 @@ * @param array $urlOptions Url parts * @param boolean $reset Use default module, action and controller instead of current when not specified in $urlOptions * @param string $routeName - * @param boolean $encode + * @param boolean $encode */ protected function _reroute(array $urlOptions = array(), $reset = false, $routeName = null, $encode = true) { @@ -172,7 +172,7 @@ { $extraSource = MUtil_Ra::pairs(func_get_args(), 1); $snippet = $this->getSnippet($filename, $extraSource); - + if ($snippet->hasHtmlOutput()) { $this->html[] = $snippet; return $snippet; @@ -202,7 +202,7 @@ if ($snippet->hasHtmlOutput()) { $this->html[] = $snippet; $results[$filename] = $snippet; - + } elseif ($snippet->getRedirectRoute()) { $snippet->redirectRoute(); return false; @@ -263,12 +263,12 @@ } else { $extraSourceParameters = array(); } - + $loader = $this->getSnippetLoader(); - + return $loader->getSnippet($filename, $extraSourceParameters); } - + /** * Returns a source of values for snippets. * @@ -285,7 +285,7 @@ /** * Returns the current html/head/title for this page. - * + * * If the title is an array the seperator concatenates the parts. * * @param string $separator @@ -371,7 +371,7 @@ $this->_helper->viewRenderer->setScriptAction('html-view'); } } - + /** * Stub for overruling default snippet loader initiation. */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-12-07 16:58:26
|
Revision: 347 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=347&view=rev Author: matijsdejong Date: 2011-12-07 16:58:16 +0000 (Wed, 07 Dec 2011) Log Message: ----------- First changes for batch processing (#45) Modified Paths: -------------- trunk/library/classes/Gems/Default/SourceAction.php trunk/library/classes/MUtil/Html/Creator.php Added Paths: ----------- trunk/library/classes/MUtil/Html/ProgressPanel.js trunk/library/classes/MUtil/Html/ProgressPanel.php Modified: trunk/library/classes/Gems/Default/SourceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SourceAction.php 2011-12-07 14:06:31 UTC (rev 346) +++ trunk/library/classes/Gems/Default/SourceAction.php 2011-12-07 16:58:16 UTC (rev 347) @@ -243,6 +243,8 @@ $this->html->h3($this->_('Synchronize all sources of surveys')); $this->html->pInfo($this->_('Synchronization will update the status of all surveys imported into this project to the status at the sources.')); + // $progress = $this->html->progress('0%'); + if ($data) { $rdata = MUtil_Lazy::repeat($data); $table = $this->html->table($rdata, array('class' => 'browser')); Modified: trunk/library/classes/MUtil/Html/Creator.php =================================================================== --- trunk/library/classes/MUtil/Html/Creator.php 2011-12-07 14:06:31 UTC (rev 346) +++ trunk/library/classes/MUtil/Html/Creator.php 2011-12-07 16:58:16 UTC (rev 347) @@ -1,34 +1,34 @@ <?php - -/** - * Copyright (c) 2011, Erasmus MC - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Erasmus MC nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - + /** + * Copyright (c) 2011, Erasmus MC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Erasmus MC nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** * @author Matijs de Jong * @since 1.0 * @version 1.1 @@ -81,6 +81,8 @@ 'menu' => 'MUtil_Html_ListElement::menu', 'ol' => 'MUtil_Html_ListElement::ol', 'pagePanel' => 'MUtil_Html_PagePanel::pagePanel', + 'progress' => 'MUtil_Html_ProgressPanel::progress', + 'progressPanel' => 'MUtil_Html_ProgressPanel::progress', 'raw' => 'MUtil_Html_Raw::raw', 'seq' => 'MUtil_Html_Sequence::createSequence', 'sequence' => 'MUtil_Html_Sequence::createSequence', // A sequence can contain another sequence, so other function name used Added: trunk/library/classes/MUtil/Html/ProgressPanel.js =================================================================== --- trunk/library/classes/MUtil/Html/ProgressPanel.js (rev 0) +++ trunk/library/classes/MUtil/Html/ProgressPanel.js 2011-12-07 16:58:16 UTC (rev 347) @@ -0,0 +1,24 @@ + +function FUNCTION_PREFIX_Start() +{ + var iFrame = document.createElement('iframe'); + iFrame.setAttribute('style', 'position: absolute; left: -100px; top: -100px; width: 10px; height: 10px; overflow: hidden;'); + document.getElementsByTagName('body')[0].appendChild(iFrame); + iFrame.src = '{URL}'; +} + +function FUNCTION_PREFIX_Update(data) +{ + document.getElementById('pg-percent').style.width = data.percent + '%'; + + document.getElementById('pg-text-1').innerHTML = data.text; + document.getElementById('pg-text-2').innerHTML = data.text; +} + +function FUNCTION_PREFIX_Finish() +{ + document.getElementById('pg-percent').style.width = '100%'; + + document.getElementById('pg-text-1').innerHTML = 'Demo done'; + document.getElementById('pg-text-2').innerHTML = 'Demo done'; +} \ No newline at end of file Added: trunk/library/classes/MUtil/Html/ProgressPanel.php =================================================================== --- trunk/library/classes/MUtil/Html/ProgressPanel.php (rev 0) +++ trunk/library/classes/MUtil/Html/ProgressPanel.php 2011-12-07 16:58:16 UTC (rev 347) @@ -0,0 +1,102 @@ +<?php + +/** + * Copyright (c) 2011, Erasmus MC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Erasmus MC nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * @package MUtil + * @subpackage Html + * @author Matijs de Jong <mj...@ma...> + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @version $Id: Sample.php 203 2011-07-07 12:51:32Z matijs $ + */ + +/** + * + * + * @package MUtil + * @subpackage Html + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @since Class available since version 1.5 + */ +class MUtil_Html_ProgressPanel extends MUtil_Html_HtmlElement +{ + /** + * Usually no text is appended after an element, but for certain elements we choose + * to add a "\n" newline character instead, to keep the output readable in source + * view. + * + * @var string Content added after the element. + */ + protected $_appendString = "\n"; + + /** + * Default attributes. + * + * @var array The actual storage of the attributes. + */ + protected $_attribs = array( + 'class' => 'progress', + 'id' => 'progress_bar' + ); + + /** + * Usually no text is appended before an element, but for certain elements we choose + * to add a "\n" newline character instead, to keep the output readable in source + * view. + * + * @var string Content added before the element. + */ + protected $_prependString = "\n"; + + /** + * Creates a 'div' progress panel + * + * @param mixed $arg_array A MUtil_Ra::args data collection. + */ + public function __construct($arg_array = null) + { + $args = MUtil_Ra::args(func_get_args()); + + parent::__construct('div', $args); + } + + /** + * Creates a 'div' progress panel + * + * @param mixed $arg_array A MUtil_Ra::args data collection. + * @return self + */ + public static function progress($arg_array = null) + { + $args = func_get_args(); + return new self($args); + } + + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-12-16 15:03:14
|
Revision: 366 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=366&view=rev Author: mennodekker Date: 2011-12-16 15:03:03 +0000 (Fri, 16 Dec 2011) Log Message: ----------- Moved some stuff from ModelTabFormSnipperGeneric to ModelFormSnippetAbstract so normal and tabform can be changed by changing the base snippet Modified Paths: -------------- trunk/library/classes/Gems/Snippets/ModelTabFormSnippetGeneric.php trunk/library/classes/MUtil/Snippets/ModelFormSnippetAbstract.php Modified: trunk/library/classes/Gems/Snippets/ModelTabFormSnippetGeneric.php =================================================================== --- trunk/library/classes/Gems/Snippets/ModelTabFormSnippetGeneric.php 2011-12-16 12:37:11 UTC (rev 365) +++ trunk/library/classes/Gems/Snippets/ModelTabFormSnippetGeneric.php 2011-12-16 15:03:03 UTC (rev 366) @@ -55,69 +55,6 @@ protected $_form; /** - * Array of item names still to be added to the form - * - * @var array - */ - protected $_items; - - /** - * Add items to the bridge, and remove them from the items array - * - * @param MUtil_Model_FormBridge $bridge - * @param string $element1 - * - * @return void - */ - protected function addItems($bridge, $element1) - { - $args = func_get_args(); - if (count($args)<2) { - throw new Gems_Exception_Coding('Use at least 2 arguments, first the bridge and then one or more idividual items'); - } - - $bridge = array_shift($args); - $elements = $args; - - //Remove the elements from the _items variable - $this->_items = array_diff($this->_items, $elements); - - //And add them to the bridge - foreach($elements as $name) { - if ($label = $this->model->get($name, 'label')) { - $bridge->add($name); - } else { - $bridge->addHidden($name); - } - } - } - - /** - * Adds elements from the model to the bridge that creates the form. - * - * Overrule this function to add different elements to the browse table, without - * having to recode the core table building code. - * - * @param MUtil_Model_FormBridge $bridge - * @param MUtil_Model_ModelAbstract $model - * @param array $items - */ - protected function addFormElements(MUtil_Model_FormBridge $bridge, MUtil_Model_ModelAbstract $model, $items = null) - { - //Get all elements in the model if not already done - $this->initItems(); - - //Now add all remaining items to the last last tab (if any) - foreach($this->_items as $name) { - if ($label = $model->get($name, 'label')) { - $bridge->add($name); - } else { - $bridge->addHidden($name); - } - } - } - - /** * Perform some actions on the form, right before it is displayed but already populated * * Here we add the table display to the form. @@ -156,14 +93,4 @@ return $form; } - - /** - * Initialize the _items variable to hold all items from the model - */ - protected function initItems() - { - if (is_null($this->_items)) { - $this->_items = $this->model->getItemsOrdered(); - } - } } \ No newline at end of file Modified: trunk/library/classes/MUtil/Snippets/ModelFormSnippetAbstract.php =================================================================== --- trunk/library/classes/MUtil/Snippets/ModelFormSnippetAbstract.php 2011-12-16 12:37:11 UTC (rev 365) +++ trunk/library/classes/MUtil/Snippets/ModelFormSnippetAbstract.php 2011-12-16 15:03:03 UTC (rev 366) @@ -60,7 +60,14 @@ protected $_form; /** + * Array of item names still to be added to the form * + * @var array + */ + protected $_items; + + /** + * * @var Zend_Form_Element_Submit */ protected $_saveButton; @@ -149,8 +156,37 @@ */ protected function addFormElements(MUtil_Model_FormBridge $bridge, MUtil_Model_ModelAbstract $model) { - foreach($model->getItemsOrdered() as $name) { - if ($label = $model->get($name, 'label')) { + //Get all elements in the model if not already done + $this->initItems(); + + //And any remaining item + $this->addItems($bridge, $this->_items); + } + + /** + * Add items to the bridge, and remove them from the items array + * + * @param MUtil_Model_FormBridge $bridge + * @param string $element1 + * + * @return void + */ + protected function addItems(MUtil_Model_FormBridge $bridge, $element1) + { + $args = func_get_args(); + if (count($args)<2) { + throw new Gems_Exception_Coding('Use at least 2 arguments, first the bridge and then one or more idividual items'); + } + + $bridge = array_shift($args); + $elements = MUtil_Ra::flatten($args); + + //Remove the elements from the _items variable + $this->_items = array_diff($this->_items, $elements); + + //And add them to the bridge + foreach($elements as $name) { + if ($label = $this->model->get($name, 'label')) { $bridge->add($name); } else { $bridge->addHidden($name); @@ -323,6 +359,16 @@ } /** + * Initialize the _items variable to hold all items from the model + */ + protected function initItems() + { + if (is_null($this->_items)) { + $this->_items = $this->model->getItemsOrdered(); + } + } + + /** * Makes sure there is a form. */ protected function loadForm() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2011-12-30 12:11:51
|
Revision: 389 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=389&view=rev Author: matijsdejong Date: 2011-12-30 12:11:45 +0000 (Fri, 30 Dec 2011) Log Message: ----------- First working versions of the ProgressPanel.php Modified Paths: -------------- trunk/library/classes/Gems/Default/SourceAction.php trunk/library/classes/MUtil/Html/ProgressPanel.php Added Paths: ----------- trunk/library/classes/MUtil/Html/ProgressPanelPush.js Removed Paths: ------------- trunk/library/classes/MUtil/Html/ProgressPanel.js Modified: trunk/library/classes/Gems/Default/SourceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SourceAction.php 2011-12-22 17:07:21 UTC (rev 388) +++ trunk/library/classes/Gems/Default/SourceAction.php 2011-12-30 12:11:45 UTC (rev 389) @@ -245,8 +245,30 @@ $this->html->pInfo($this->_('Synchronization will update the status of all surveys imported into this project to the status at the sources.')); /* $progress = $this->html->progress('0%'); + // $progress = $this->html->progress(); if ($progress->run($this->getRequest())) { - MUtil_Echo::track('running'); + + // IIS 7: %windir%\System32\inetsrv\config\applicationHost.config + // ../handlers/add name="PHP_via_FastCGI" + // ../handlers/add name="CGI-exe" + // add attribute responseBufferLimit="1024" + + for ($i = 0; $i < 100; $i += 1) { + if ($i < 20) { + $text = 'Just beginning'; + } else if ($i < 50) { + $text = 'A bit done'; + } else if ($i < 80) { + $text = 'Getting closer'; + } else { + $text = 'Nearly done'; + } + // IIS? + echo str_repeat(' ',1024*3); + $progress->update($i, ' ' . $text); + sleep(15); + } + $progress->finish(); } // */ if ($data) { Deleted: trunk/library/classes/MUtil/Html/ProgressPanel.js =================================================================== --- trunk/library/classes/MUtil/Html/ProgressPanel.js 2011-12-22 17:07:21 UTC (rev 388) +++ trunk/library/classes/MUtil/Html/ProgressPanel.js 2011-12-30 12:11:45 UTC (rev 389) @@ -1,27 +0,0 @@ - -function FUNCTION_PREFIX_Start() -{ - var iFrame = document.createElement('iframe'); - iFrame.setAttribute('style', 'position: absolute; left: -100px; top: -100px; width: 10px; height: 10px; overflow: hidden;'); - document.getElementsByTagName('body')[0].appendChild(iFrame); - iFrame.src = '{URL}'; -} - -function FUNCTION_PREFIX_Update(data) -{ - main = document.getElementById('{ID}'); // .style.width = data.percent + '%'; - - inner = main.getElementsByTagName('{CHILD}')[0]; - inner.style.width = data.percent + '%'; - inner.innerHTML = data.text; -} - -function FUNCTION_PREFIX_Finish() -{ - document.getElementById('{id}').style.width = '100%'; - - document.getElementById('pg-text-1').innerHTML = 'Demo done'; - document.getElementById('pg-text-2').innerHTML = 'Demo done'; -} - -// FUNCTION_PREFIX_Start(); Modified: trunk/library/classes/MUtil/Html/ProgressPanel.php =================================================================== --- trunk/library/classes/MUtil/Html/ProgressPanel.php 2011-12-22 17:07:21 UTC (rev 388) +++ trunk/library/classes/MUtil/Html/ProgressPanel.php 2011-12-30 12:11:45 UTC (rev 389) @@ -78,7 +78,7 @@ * @var array The actual storage of the attributes. */ protected $_attribs = array( - 'class' => 'progress', + 'class' => 'ui-progressbar ui-widget ui-widget-content ui-corner-all', 'id' => 'progress_bar' ); @@ -104,12 +104,6 @@ protected $_functionPrefix; /** - * - * @var MUtil_Html_HtmlElement - */ - protected $_innerElement; - - /** * Usually no text is appended before an element, but for certain elements we choose * to add a "\n" newline character instead, to keep the output readable in source * view. @@ -119,6 +113,33 @@ protected $_prependString = "\n"; /** + * + * @var Zend_ProgressBar + */ + protected $_progressBar; + + /** + * + * @var Zend_ProgressBar_Adapter + */ + protected $_progressBarAdapter; + + /** + * Extra array with special types for subclasses. + * + * When an object of one of the key types is used, then use + * the class method defined as the value. + * + * @see $_specialTypesDefault + * + * @var array Of 'class or interfacename' => 'class method' of null + */ + protected $_specialTypes = array( + 'Zend_ProgressBar' => 'setProgressBar', + 'Zend_ProgressBar_Adapter' => 'setProgressBarAdapter', + ); + + /** * The name of the parameter used for progress panel signals * * @var string @@ -133,6 +154,13 @@ public $progressParameterRunValue = 'run'; /** + * Class name of inner element that displays text + * + * @var string + */ + public $progressTextClass = 'ui-progressbar-text'; + + /** * Creates a 'div' progress panel * * @param mixed $arg_array A MUtil_Ra::args data collection. @@ -145,6 +173,18 @@ } /** + * Update the progess panel + * + * @return MUtil_Html_ProgressPanel (continuation pattern) + */ + public function finish() + { + $bar = $this->getProgressBar(); + $bar->finish(); + + return $this; + } + /** * Returns the JavaScript object associated with this object. * * WARNING: calling this object sets it's position in the order the @@ -156,10 +196,11 @@ public function getCode() { if (! isset($this->_content[self::CODE])) { - $js = new MUtil_Html_Code_JavaScript(dirname(__FILE__) . '/ProgressPanel.js'); + $js = new MUtil_Html_Code_JavaScript(dirname(__FILE__) . '/ProgressPanelPush.js'); // $js->setInHeader(false); $js->setField('FUNCTION_PREFIX_', $this->getFunctionPrefix()); - $js->setField('{CHILD}', $this->_defaultChildTag); + $js->setField('{TEXT_TAG}', $this->_defaultChildTag); + $js->setField('{TEXT_CLASS}', $this->progressTextClass); $js->setField('{ID}', $this->getAttrib('id')); $this->_content[self::CODE] = $js; @@ -176,13 +217,38 @@ public function getFunctionPrefix() { if (! $this->_functionPrefix) { - $this->setFunctionPrefix(__CLASS__ . '_'); + $this->setFunctionPrefix(__CLASS__ . '_' . $this->getAttrib('id'). '_'); } return (string) $this->_functionPrefix; } /** + * + * @return Zend_ProgressBar + */ + public function getProgressBar() + { + if (! $this->_progressBar instanceof Zend_ProgressBar) { + $this->setProgressBar(new Zend_ProgressBar($this->getProgressBarAdapter(), 0, 100)); + } + return $this->_progressBar; + } + + /** + * + * @return Zend_ProgressBar_Adapter + */ + public function getProgressBarAdapter() + { + if (! $this->_progressBarAdapter instanceof Zend_ProgressBar_Adapter) { + $this->setProgressBarAdapter(new Zend_ProgressBar_Adapter_JsPush()); + } + + return $this->_progressBarAdapter; + } + + /** * Creates a 'div' progress panel * * @param mixed $arg_array A MUtil_Ra::args data collection. @@ -206,11 +272,30 @@ */ protected function renderElement(Zend_View_Abstract $view) { - $js = $this->getCode(); - if (! $js->hasField('{URL}')) { - $js->setField('{URL}', $view->url(array($this->progressParameterName => $this->progressParameterRunValue))); + ZendX_JQuery::enableView($view); + + if ($this->getProgressBarAdapter() instanceof Zend_ProgressBar_Adapter_JsPush) { + $js = $this->getCode(); + if (! $js->hasField('{URL}')) { + $js->setField('{URL}', $view->url(array($this->progressParameterName => $this->progressParameterRunValue))); + } } + if ($this->_lastChild) { + $this->_lastChild->class = $this->progressTextClass; + + // These style elements inline because they are REQUIRED to make the panel work. + // + // Making the child position absolute means it is positioned over the content that + // the JQuery progress widget displays (the bar itself) and so this solution allows + // the text to be displayed over the progress bar (when it has a relative position). + // + // The elements should be display neutral. + // + $this->_lastChild->style = 'left: 0; height: 100%; position: absolute; top: 0; width: 100%;'; + $this->style = 'position: relative;'; + } + return parent::renderElement($view); } @@ -239,4 +324,47 @@ $this->_functionPrefix = $prefix; return $this; } + + /** + * + * @param Zend_ProgressBar $progressBar + * @return MUtil_Html_ProgressPanel (continuation pattern) + */ + public function setProgressBar(Zend_ProgressBar $progressBar) + { + $this->_progressBar = $progressBar; + return $this; + } + + /** + * + * @param Zend_ProgressBar_Adapter_Interface $adapter + * @return MUtil_Html_ProgressPanel (continuation pattern) + */ + public function setProgressBarAdapter(Zend_ProgressBar_Adapter $adapter) + { + if ($adapter instanceof Zend_ProgressBar_Adapter_JsPush) { + $prefix = $this->getFunctionPrefix(); + $adapter->setUpdateMethodName($prefix . 'Update'); + $adapter->setFinishMethodName($prefix . 'Finish'); + } + + $this->_progressBarAdapter = $adapter; + return $this; + } + + /** + * Update the progess panel + * + * @param int $value + * @param string $text + * @return MUtil_Html_ProgressPanel (continuation pattern) + */ + public function update($value, $text = null) + { + $bar = $this->getProgressBar(); + $bar->update($value, $text); + + return $this; + } } Added: trunk/library/classes/MUtil/Html/ProgressPanelPush.js =================================================================== --- trunk/library/classes/MUtil/Html/ProgressPanelPush.js (rev 0) +++ trunk/library/classes/MUtil/Html/ProgressPanelPush.js 2011-12-30 12:11:45 UTC (rev 389) @@ -0,0 +1,46 @@ + +function FUNCTION_PREFIX_Start() +{ + var iFrame = document.createElement('iframe'); + iFrame.setAttribute('style', 'position: absolute; left: -100px; top: -100px; width: 10px; height: 10px; overflow: hidden;'); + // iFrame.setAttribute('style', 'position: absolute; left: 0px; top: 0px; width: 100px; height: 100px; overflow: hidden;'); + document.getElementsByTagName('body')[0].appendChild(iFrame); + iFrame.src = '{URL}'; +} + +function FUNCTION_PREFIX_Update(data) +{ + main = jQuery("#{ID}"); + main.progressbar( "option", "value", data.percent); + main.progressbar({ + value: data.percent + }); + + inner = main.find('.{TEXT_CLASS}'); + if (inner) { + inner.empty(); + inner.append(data.percent + '%'); + if (data.text) { + inner.append(data.text); + } + } +} + +function FUNCTION_PREFIX_Finish() +{ + main = jQuery("#{ID}"); + main.progressbar( "option", "value", 100); + + inner = main.find('{TEXT_TAG}.{TEXT_CLASS}'); + if (inner) { + inner.empty(); + inner.append('100% Done!'); + } +} + + +// FUNCTION_PREFIX_Start(); + +// jQuery().ready(FUNCTION_PREFIX_Update({percent: 20, text: 'Hi'})); +// jQuery().ready(FUNCTION_PREFIX_Update({percent: 20, text: ''})); +jQuery().ready(FUNCTION_PREFIX_Start()); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-01-02 10:17:48
|
Revision: 391 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=391&view=rev Author: mennodekker Date: 2012-01-02 10:17:42 +0000 (Mon, 02 Jan 2012) Log Message: ----------- Possibly incompatible fix: Fixed userloading for inactive users (i.e. userdata returns no row) Fix for delete in staffModel resulting in an error because not all key values where present and the joined table got an insert instead of an update Doc for code completion in Model Modified Paths: -------------- trunk/library/classes/Gems/Model.php trunk/library/classes/Gems/User/DbUserDefinitionAbstract.php trunk/library/classes/Gems/User/User.php trunk/library/classes/MUtil/Model/JoinModel.php Modified: trunk/library/classes/Gems/Model.php =================================================================== --- trunk/library/classes/Gems/Model.php 2011-12-30 12:12:18 UTC (rev 390) +++ trunk/library/classes/Gems/Model.php 2012-01-02 10:17:42 UTC (rev 391) @@ -171,6 +171,11 @@ return $model; } + /** + * Load the organization model + * + * @return Gems_Model_OrganizationModel + */ public function getOrganizationModel() { $model = $this->_loadClass('OrganizationModel', true); @@ -227,6 +232,11 @@ return $model; } + /** + * Load the staffmodel + * + * @return Gems_Model_StaffModel + */ public function getStaffModel() { $model = $this->_loadClass('StaffModel', true); Modified: trunk/library/classes/Gems/User/DbUserDefinitionAbstract.php =================================================================== --- trunk/library/classes/Gems/User/DbUserDefinitionAbstract.php 2011-12-30 12:12:18 UTC (rev 390) +++ trunk/library/classes/Gems/User/DbUserDefinitionAbstract.php 2012-01-02 10:17:42 UTC (rev 391) @@ -168,7 +168,20 @@ { $select = $this->getUserSelect($login_name, $organization); - return $this->db->fetchRow($select, array($login_name, $organization), Zend_Db::FETCH_ASSOC); + $result = $this->db->fetchRow($select, array($login_name, $organization), Zend_Db::FETCH_ASSOC); + + /* + * Handle the case that we have a login record, but no matching userdata (ie. user is inactive) + * if you want some kind of auto-register you should change this + */ + if ($result == false) { + $result = array( + 'user_active' => false, + 'user_role' => 'nologin', + ); + } + + return $result; } /** Modified: trunk/library/classes/Gems/User/User.php =================================================================== --- trunk/library/classes/Gems/User/User.php 2011-12-30 12:12:18 UTC (rev 390) +++ trunk/library/classes/Gems/User/User.php 2012-01-02 10:17:42 UTC (rev 391) @@ -222,6 +222,17 @@ } /** + * Helper method for the case a user tries to authenticate while he is inactive + * + * @param array $params + * @return boolean + */ + public function alwaysFalse($params) + { + return false; + } + + /** * Authenticate a users credentials using the submitted form * * @param array $formValues the array containing all formvalues from the login form @@ -229,17 +240,21 @@ */ public function authenticate($formValues) { - $auth = Gems_Auth::getInstance(); + $auth = Gems_Auth::getInstance(); - $formValues['allowed_ip_ranges'] = $this->getAllowedIPRanges(); - $formValues['organization'] = $this->getBaseOrganizationId(); + $formValues['allowed_ip_ranges'] = $this->getAllowedIPRanges(); + $formValues['organization'] = $this->getBaseOrganizationId(); - $adapter = $this->definition->getAuthAdapter($formValues); - $authResult = $auth->authenticate($adapter, $formValues); + if ($this->isActive()) { + $adapter = $this->definition->getAuthAdapter($formValues); + } else { + $adapter = new Gems_Auth_Adapter_Callback(array($this,'alwaysFalse'), $formValues['userlogin'], $formValues); + } - $this->_authResult = $authResult; + $authResult = $auth->authenticate($adapter, $formValues); + $this->_authResult = $authResult; - return $authResult; + return $authResult; } /** Modified: trunk/library/classes/MUtil/Model/JoinModel.php =================================================================== --- trunk/library/classes/MUtil/Model/JoinModel.php 2011-12-30 12:12:18 UTC (rev 390) +++ trunk/library/classes/MUtil/Model/JoinModel.php 2012-01-02 10:17:42 UTC (rev 391) @@ -175,8 +175,11 @@ $filter = $this->_checkFilterUsed($filter); if ($this->_deleteValues) { - // MUtil_Model::$verbose = true; - $changed = $this->save($this->_deleteValues + $filter, $filter, $saveTables); + // First get the old values so we can have all the key values + $oldValues = $this->loadFirst($filter); + + // Add the oldValues to the save + $changed = $this->save($this->_deleteValues + $oldValues, $filter, $saveTables); } else { $changed = 0; foreach ($saveTables as $table_name) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-01-05 11:47:27
|
Revision: 397 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=397&view=rev Author: mennodekker Date: 2012-01-05 11:47:16 +0000 (Thu, 05 Jan 2012) Log Message: ----------- Fixed error for the case that no registry key for MUtil_Model_FormBridge options is present and made the key configurable Modified Paths: -------------- trunk/library/classes/GemsEscort.php trunk/library/classes/MUtil/Model/FormBridge.php Modified: trunk/library/classes/GemsEscort.php =================================================================== --- trunk/library/classes/GemsEscort.php 2012-01-05 09:54:04 UTC (rev 396) +++ trunk/library/classes/GemsEscort.php 2012-01-05 11:47:16 UTC (rev 397) @@ -1011,7 +1011,7 @@ 'showOn' => 'button', ); - Zend_Registry::set('MUtil_Model_FormBridge', array('date' => $dateFormOptions)); + Zend_Registry::set(MUtil_Model_FormBridge::REGISTRY_KEY, array('date' => $dateFormOptions)); } protected function createProjectClass($className, $param1 = null, $param2 = null) Modified: trunk/library/classes/MUtil/Model/FormBridge.php =================================================================== --- trunk/library/classes/MUtil/Model/FormBridge.php 2012-01-05 09:54:04 UTC (rev 396) +++ trunk/library/classes/MUtil/Model/FormBridge.php 2012-01-05 11:47:16 UTC (rev 397) @@ -64,6 +64,11 @@ const TEXT_OPTIONS = 'text'; const TEXTAREA_OPTIONS = 'textarea'; + /** + * The key to use in the Zend_Registry to store global fixed options + */ + const REGISTRY_KEY = 'MUtil_Model_FormBridge'; + protected $form; protected $model; @@ -670,7 +675,11 @@ static $typeOptions; if (! $typeOptions) { - $typeOptions = Zend_Registry::get('MUtil_Model_FormBridge'); + if (Zend_Registry::isRegistered(self::REGISTRY_KEY)) { + $typeOptions = Zend_Registry::get(self::REGISTRY_KEY); + } else { + $typeOptions = array(); + } } if (substr($type, 0, 3) == 'add') { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-01-11 15:18:13
|
Revision: 404 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=404&view=rev Author: matijsdejong Date: 2012-01-11 15:18:06 +0000 (Wed, 11 Jan 2012) Log Message: ----------- Pushing progress on progress Modified Paths: -------------- trunk/library/classes/Gems/Default/SourceAction.php trunk/library/classes/MUtil/Html/Code/DynamicAbstract.php trunk/library/classes/MUtil/Html/ProgressPanel.php trunk/library/classes/MUtil/Html/ProgressPanelPush.js Added Paths: ----------- trunk/library/classes/MUtil/Html/ProgressPanelPull.js Modified: trunk/library/classes/Gems/Default/SourceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SourceAction.php 2012-01-06 14:09:20 UTC (rev 403) +++ trunk/library/classes/Gems/Default/SourceAction.php 2012-01-11 15:18:06 UTC (rev 404) @@ -253,7 +253,7 @@ // ../handlers/add name="CGI-exe" // add attribute responseBufferLimit="1024" - for ($i = 0; $i < 100; $i += 1) { + for ($i = 50; $i < 100; $i += 10) { if ($i < 20) { $text = 'Just beginning'; } else if ($i < 50) { @@ -264,9 +264,9 @@ $text = 'Nearly done'; } // IIS? - echo str_repeat(' ',1024*3); + // echo str_repeat(' ',1024*3); $progress->update($i, ' ' . $text); - sleep(15); + sleep(1); } $progress->finish(); } // */ Modified: trunk/library/classes/MUtil/Html/Code/DynamicAbstract.php =================================================================== --- trunk/library/classes/MUtil/Html/Code/DynamicAbstract.php 2012-01-06 14:09:20 UTC (rev 403) +++ trunk/library/classes/MUtil/Html/Code/DynamicAbstract.php 2012-01-11 15:18:06 UTC (rev 404) @@ -164,6 +164,26 @@ } /** + * Sets the default value for a field to search and replace in the content. + * + * Used to set the value only when it is empty. + * + * No markers are used. If you want to replace '{path}' with 'x', you + * must specificy the name '{path}', not 'path'. + * + * @param string $name Full name to replace. + * @param string $value The value placed. + * @return MUtil_Html_Link_LinkAbstract (continuation pattern) + */ + public function setDefault($name, $value) + { + if (! isset($this->_fields[$name])) { + $this->_fields[$name] = $value; + } + return $this; + } + + /** * Set a field to search and replace in the content. * * No markers are used. If you want to replace '{path}' with 'x', you Modified: trunk/library/classes/MUtil/Html/ProgressPanel.php =================================================================== --- trunk/library/classes/MUtil/Html/ProgressPanel.php 2012-01-06 14:09:20 UTC (rev 403) +++ trunk/library/classes/MUtil/Html/ProgressPanel.php 2012-01-11 15:18:06 UTC (rev 404) @@ -83,6 +83,13 @@ ); /** + * When true the progressbar should start immediately. When false the user has to perform an action. + * + * @var boolean + */ + protected $_autoStart = true; + + /** * When content must contain certain element types only the default child tag contains * the tagname of the element that is created to contain the content. * @@ -140,6 +147,13 @@ ); /** + * The mode to use for the panel: push or pull + * + * @var string + */ + public $method = 'Pull'; + + /** * The name of the parameter used for progress panel signals * * @var string @@ -196,12 +210,8 @@ public function getCode() { if (! isset($this->_content[self::CODE])) { - $js = new MUtil_Html_Code_JavaScript(dirname(__FILE__) . '/ProgressPanelPush.js'); - // $js->setInHeader(false); - $js->setField('FUNCTION_PREFIX_', $this->getFunctionPrefix()); - $js->setField('{TEXT_TAG}', $this->_defaultChildTag); - $js->setField('{TEXT_CLASS}', $this->progressTextClass); - $js->setField('{ID}', $this->getAttrib('id')); + $js = new MUtil_Html_Code_JavaScript(dirname(__FILE__) . '/ProgressPanel' . $this->method . '.js'); + $js->setInHeader(false); $this->_content[self::CODE] = $js; } @@ -242,7 +252,11 @@ public function getProgressBarAdapter() { if (! $this->_progressBarAdapter instanceof Zend_ProgressBar_Adapter) { - $this->setProgressBarAdapter(new Zend_ProgressBar_Adapter_JsPush()); + if ($this->method == 'Pull') { + $this->setProgressBarAdapter(new Zend_ProgressBar_Adapter_JsPull()); + } else { + $this->setProgressBarAdapter(new Zend_ProgressBar_Adapter_JsPush()); + } } return $this->_progressBarAdapter; @@ -274,11 +288,15 @@ { ZendX_JQuery::enableView($view); - if ($this->getProgressBarAdapter() instanceof Zend_ProgressBar_Adapter_JsPush) { + if ($this->getProgressBarAdapter() instanceof Zend_ProgressBar_Adapter) { $js = $this->getCode(); - if (! $js->hasField('{URL}')) { - $js->setField('{URL}', $view->url(array($this->progressParameterName => $this->progressParameterRunValue))); - } + + // Set the fields, in case they where not set earlier + $js->setDefault('__AUTOSTART__', $this->_autoStart ? 'true' : 'false'); + $js->setDefault('{ID}', $this->getAttrib('id')); + $js->setDefault('{TEXT_TAG}', $this->_defaultChildTag); + $js->setDefault('{TEXT_CLASS}', $this->progressTextClass); + $js->setDefault('{URL}', addcslashes($view->url(array($this->progressParameterName => $this->progressParameterRunValue)), "/")); } if ($this->_lastChild) { @@ -344,7 +362,11 @@ public function setProgressBarAdapter(Zend_ProgressBar_Adapter $adapter) { if ($adapter instanceof Zend_ProgressBar_Adapter_JsPush) { + $js = $this->getCode(); $prefix = $this->getFunctionPrefix(); + + // Set the fields, in case they where not set earlier + $js->setDefault('FUNCTION_PREFIX_', $prefix); $adapter->setUpdateMethodName($prefix . 'Update'); $adapter->setFinishMethodName($prefix . 'Finish'); } Added: trunk/library/classes/MUtil/Html/ProgressPanelPull.js =================================================================== --- trunk/library/classes/MUtil/Html/ProgressPanelPull.js (rev 0) +++ trunk/library/classes/MUtil/Html/ProgressPanelPull.js 2012-01-11 15:18:06 UTC (rev 404) @@ -0,0 +1,86 @@ + + +// Creating the widget +jQuery.widget("ui.pullProgressPanel", { + + // default options + options: { + autoStart: false, + // target: the element whose content is replaced + timeout: 2000 + // url: the request url + }, + + _init: function() { + if (this.options.autoStart) { + this.start(); + } + }, + + complete: function (request, status) { + this.request = null; + + // Check for changes + // - if the input field was changed since the last request + // filter() will search on the new value + // - if the input field has not changed, then no new request + // is made. + // this.start(); + }, + + error: function (request, status) { + console.log(status); + /* if (request.status === 401) { + location.href = location.href; + } // */ + }, + + start: function() { + if (this.request == null) { + if (this.options.url) { + var self = this; + this.request = jQuery.ajax({ + url: this.options.url, + type: "GET", + dataType: "json", + // data: postData, + error: function(request, status, error) {self.error(request, status);}, + complete: function(request, status) {self.complete(request, status);}, + success: function(data, status, request) {self.success(data, status, request);} + }); + + } + } + }, + + success: function (data, status, request) { + // console.log(stringdata); + // data = jQuery.parseJSON(stringdata); + console.log(data); + + text = data.percent + '%'; + if (data.text) { + text = text + data.text; + } + + jQuery(this.options.target).html(text); + }, + + request: null +}); + +jQuery(document).ready(function() { + jQuery("#{ID}").pullProgressPanel({"url":"{URL}","autoStart":__AUTOSTART__,"target":"#{ID} {TEXT_TAG}.{TEXT_CLASS}"}); +}); + +function FUNCTION_PREFIX_Finish() +{ + main = jQuery("#{ID}"); + main.progressbar( "option", "value", 100); + + inner = main.find('{TEXT_TAG}.{TEXT_CLASS}'); + if (inner) { + inner.empty(); + inner.append('100% Done!'); + } +} Modified: trunk/library/classes/MUtil/Html/ProgressPanelPush.js =================================================================== --- trunk/library/classes/MUtil/Html/ProgressPanelPush.js 2012-01-06 14:09:20 UTC (rev 403) +++ trunk/library/classes/MUtil/Html/ProgressPanelPush.js 2012-01-11 15:18:06 UTC (rev 404) @@ -16,13 +16,13 @@ value: data.percent }); - inner = main.find('.{TEXT_CLASS}'); + inner = main.find('{TEXT_TAG}.{TEXT_CLASS}'); if (inner) { - inner.empty(); - inner.append(data.percent + '%'); + text = data.percent + '%'; if (data.text) { - inner.append(data.text); + text = text + data.text; } + inner.html(text); } } @@ -39,8 +39,8 @@ } -// FUNCTION_PREFIX_Start(); - -// jQuery().ready(FUNCTION_PREFIX_Update({percent: 20, text: 'Hi'})); -// jQuery().ready(FUNCTION_PREFIX_Update({percent: 20, text: ''})); -jQuery().ready(FUNCTION_PREFIX_Start()); +if (__AUTOSTART__) { + // jQuery().ready(FUNCTION_PREFIX_Update({percent: 20, text: 'Hi'})); + // jQuery().ready(FUNCTION_PREFIX_Update({percent: 20, text: ''})); + jQuery().ready(FUNCTION_PREFIX_Start()); +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-01-12 17:30:39
|
Revision: 407 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=407&view=rev Author: matijsdejong Date: 2012-01-12 17:30:32 +0000 (Thu, 12 Jan 2012) Log Message: ----------- Added concept of scalar array to MUtil_Ra Moved to special Batch class Modified Paths: -------------- trunk/library/classes/Gems/Default/SourceAction.php trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php trunk/library/classes/Gems/Tracker/TrackerInterface.php trunk/library/classes/Gems/Tracker.php trunk/library/classes/MUtil/Html/HtmlException.php trunk/library/classes/MUtil/Ra.php Added Paths: ----------- trunk/library/classes/Gems/Tracker/Batch/ trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php trunk/library/classes/Gems/Tracker/Batch/SynchronizeSourceBatch.php trunk/library/classes/MUtil/Batch/ trunk/library/classes/MUtil/Batch/BatchAbstract.php trunk/library/classes/MUtil/Batch/BatchException.php trunk/library/classes/MUtil/Queue/ trunk/library/classes/MUtil/Queue/Adapter/ trunk/library/classes/MUtil/Queue/Adapter/DbPrefixed.php Modified: trunk/library/classes/Gems/Default/SourceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SourceAction.php 2012-01-12 12:00:47 UTC (rev 406) +++ trunk/library/classes/Gems/Default/SourceAction.php 2012-01-12 17:30:32 UTC (rev 407) @@ -244,7 +244,25 @@ $this->html->h3($this->_('Synchronize all sources of surveys')); $this->html->pInfo($this->_('Synchronization will update the status of all surveys imported into this project to the status at the sources.')); /* + $batch = new Gems_Tracker_Batch_SynchronizeSourceBatch(); + // $batch->method = 'Push'; + if (! $batch->isLoaded()) { + foreach ($data as $row) { + $batch->addSource($row['gso_id_source'], $row['gso_source_name']); + } + } + if ($batch->run($this->getRequest())) { + if ($batch->isReady()) { + $this->addMessage($batch->getMessages()); + $this->afterSaveRoute($this->getRequest()); + } + } else { + $this->html[] = $batch->getPanel(); + } + // */ + /* $progress = $this->html->progress('0%'); + $progress->method = 'Push'; // $progress = $this->html->progress(); if ($progress->run($this->getRequest())) { @@ -253,7 +271,7 @@ // ../handlers/add name="CGI-exe" // add attribute responseBufferLimit="1024" - for ($i = 50; $i < 100; $i += 10) { + for ($i = 50; $i < 100; $i += 1) { if ($i < 20) { $text = 'Just beginning'; } else if ($i < 50) { Modified: trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php 2012-01-12 12:00:47 UTC (rev 406) +++ trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php 2012-01-12 17:30:32 UTC (rev 407) @@ -268,6 +268,26 @@ $surveyId = $this->_getParam(MUtil_Model::REQUEST_ID); $where = $this->db->quoteInto('gto_id_survey = ?', $surveyId); + /* + $batch = $this->loader->getTracker()->recalculateTokensBatch($this->loader->getCurrentUser()->getUserId(), $where); + + if ($batch->hasStarted($this->getRequest())) { + // TODO + } else { + $this->html->h3( + sprintf($this->_('Checking survey results for the %s survey.'), + $this->db->fetchOne("SELECT gsu_survey_name FROM gems__surveys WHERE gsu_id_survey = ?", $surveyId))); + + if ($batch->isLoaded()) { + $this->html->pInfo(sprintf($this->_('Running check for %s tokens...'), $batch->count())); + $this->html->append($batch->getPanel()); + } else { + $this->html->pInfo($this->_('No tokens to check.')); + } + } + // */ + + //* $this->addMessage(sprintf($this->_( 'Checking survey results for the %s survey.'), $this->db->fetchOne("SELECT gsu_survey_name FROM gems__surveys WHERE gsu_id_survey = ?", $surveyId))); @@ -275,6 +295,8 @@ $this->addMessage($this->loader->getTracker()->recalculateTokens($this->session->user_id, $where)); $this->afterSaveRoute($this->getRequest()); + + // */ } public function checkAllAction() Property changes on: trunk/library/classes/Gems/Tracker/Batch ___________________________________________________________________ Added: bugtraq:url + http://survey.erasmusmc.nl/support/mantis/view.php?id=%BUGID% Added: bugtraq:logregex + #(\d+) Added: trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php =================================================================== --- trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php (rev 0) +++ trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php 2012-01-12 17:30:32 UTC (rev 407) @@ -0,0 +1,122 @@ +<?php + +/** + * Copyright (c) 2011, Erasmus MC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Erasmus MC nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * @package Gems + * @subpackage Tracker + * @author Matijs de Jong <mj...@ma...> + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @version $Id$ + */ + +/** + * + * + * @package Gems + * @subpackage Tracker + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @since Class available since version 1.5 + */ +class Gems_Tracker_Batch_ProcessTokensBatch extends MUtil_Batch_BatchAbstract +{ + /** + * + * @var Gems_Tracker + */ + public $tracker; + + public function __construct($where, Gems_Tracker $tracker) + { + parent::__construct(__CLASS__ . '::' . $where); + + $this->tracker = $tracker; + } + + public function addToken($tokenData, $userId) + { + if (is_array($tokenData)) { + if (!isset($tokenData['gto_id_token'])) { + throw new Gems_Exception_Coding('$tokenData array should atleast have a key "gto_id_token" containing the requested token'); + } + $tokenId = $tokenData['gto_id_token']; + } else { + $tokenId = $tokenData; + } + + MUtil_Echo::track($tokenData); + $this->addStep('checkTokenCompletion', 'tokchk-' . $tokenId, $tokenData); + } + + protected function checkTrackTokens($respTrackData, $userId) + { + $respTrack = $this->tracker->getRespondentTrack($respTrackData); + + if ($result = $respTrack->checkTrackTokens($userId)) { + $this->addToCounter('tokenDateCauses'); + $this->addToCounter('tokenDateChanges', $result); + } + } + + protected function checkTokenCompletion($tokenData, $userId) + { + $this->addToCounter('checkedTokens'); + $token = $this->tracker->getToken($tokenData); + + if ($result = $token->checkTokenCompletion($userId)) { + if ($result & Gems_Tracker_Token::COMPLETION_DATACHANGE) { + $this->addToCounter('resultDataChanges'); + } + if ($result & Gems_Tracker_Token::COMPLETION_EVENTCHANGE) { + $this->addToCounter('surveyCompletionChanges'); + } + } + + if ($token->isCompleted()) { + $this->addStep('processTokenCompletion', 'tokproc-' . $token->getTokenId(), $tokenData, $userId); + } + } + + protected function processTokenCompletion($tokenData, $userId) + { + $token = $this->tracker->getToken($tokenData); + + if ($token->isCompleted()) { + $respTrack = $token->getRespondentTrack(); + + if ($result = $respTrack->handleRoundCompletion($token, $userId)) { + $this->addToCounter('roundCompletionCauses'); + $this->addToCounter('roundCompletionChanges', $result); + } + + $trackId = $respTrack->getRespondentTrackId(); + $this->addStep('checkTrackTokens', 'chktrck-' . $trackId, $trackId, $userid); + } + } +} Added: trunk/library/classes/Gems/Tracker/Batch/SynchronizeSourceBatch.php =================================================================== --- trunk/library/classes/Gems/Tracker/Batch/SynchronizeSourceBatch.php (rev 0) +++ trunk/library/classes/Gems/Tracker/Batch/SynchronizeSourceBatch.php 2012-01-12 17:30:32 UTC (rev 407) @@ -0,0 +1,61 @@ +<?php + +/** + * Copyright (c) 2011, Erasmus MC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Erasmus MC nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * @package Gems + * @subpackage Tracker + * @author Matijs de Jong <mj...@ma...> + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @version $Id$ + */ + +/** + * + * + * @package Gems + * @subpackage Tracker + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @since Class available since version 1.5 + */ +class Gems_Tracker_Batch_SynchronizeSourceBatch extends MUtil_Batch_BatchAbstract +{ + /** + * Construct as standard batch + */ + public function __construct() + { + parent::__construct(__CLASS__); + } + + public function addSource($sourceId, $sourceName) + { + + } +} Modified: trunk/library/classes/Gems/Tracker/TrackerInterface.php =================================================================== --- trunk/library/classes/Gems/Tracker/TrackerInterface.php 2012-01-12 12:00:47 UTC (rev 406) +++ trunk/library/classes/Gems/Tracker/TrackerInterface.php 2012-01-12 17:30:32 UTC (rev 407) @@ -54,7 +54,7 @@ * extension) and TokenValidator. * * Other functions are general utility functions, e.g. checkTrackRounds(), createToken(), - * preocessCompletedTokens() and recalculateTokens(). + * processCompletedTokens() and recalculateTokens(). * * @package Gems * @subpackage Tracker Modified: trunk/library/classes/Gems/Tracker.php =================================================================== --- trunk/library/classes/Gems/Tracker.php 2012-01-12 12:00:47 UTC (rev 406) +++ trunk/library/classes/Gems/Tracker.php 2012-01-12 17:30:32 UTC (rev 407) @@ -48,7 +48,7 @@ * extension) and TokenValidator. * * Other functions are general utility functions, e.g. checkTrackRounds(), createToken(), - * preocessCompletedTokens() and recalculateTokens(). + * processCompletedTokens() and recalculateTokens(). * * @package Gems * @subpackage Tracker @@ -822,6 +822,36 @@ } /** + * Checks the token table to see if there are any answered surveys to be processed + * + * If the survey was started (and the token was forwarded to limesurvey) we need to check + * if is was completed. If so, we might want to check the track the survey is in to enable + * or disable future rounds + * + * Does not reflect changes to tracks or rounds. + * + * @param Gems_Tracker_Token_TokenSelect Select statements selecting tokens + * @param int $userId Id of the user who takes the action (for logging) + * @return Gems_Tracker_Batch_ProcessTokensBatch A batch to process the changes + */ + protected function processTokensBatch(Gems_Tracker_Token_TokenSelect $tokenSelect, $userId) + { + $where = implode(' ', $tokenSelect->getSelect()->getPart(Zend_Db_Select::WHERE)); + + $batch = new Gems_Tracker_Batch_ProcessTokensBatch($where, $this); + + if (! $batch->isLoaded()) { + $tokenRows = $tokenSelect->fetchAll(); + + foreach ($tokenRows as $tokenData) { + $batch->addToken($tokenData, $userId); + } + } + + return $batch; + } + + /** * Recalculates all token dates, timing and results * and outputs text messages. * @@ -849,4 +879,31 @@ return $changes->getMessages($this->translate); } + + /** + * Recalculates all token dates, timing and results + * and outputs text messages. + * + * Does not reflect changes to tracks or rounds. + * + * @param Zend_Translate $t + * @param int $userId Id of the user who takes the action (for logging) + * @param string $cond + * @return Gems_Tracker_Batch_ProcessTokensBatch A batch to process the changes + */ + public function recalculateTokensBatch($userId = null, $cond = null) + { + $userId = $this->_checkUserId($userId); + $tokenSelect = $this->getTokenSelect(); + $tokenSelect->andReceptionCodes(); + if ($cond) { + $tokenSelect->forWhere($cond); + } + //Only select surveys that are active in the source (so we can recalculate inactive in Gems) + $tokenSelect->andSurveys(); + $tokenSelect->forWhere('gsu_surveyor_active = 1'); + + self::$verbose = true; + return $this->processTokensBatch($tokenSelect, $userId); + } } Property changes on: trunk/library/classes/MUtil/Batch ___________________________________________________________________ Added: bugtraq:url + http://survey.erasmusmc.nl/support/mantis/view.php?id=%BUGID% Added: bugtraq:logregex + #(\d+) Added: trunk/library/classes/MUtil/Batch/BatchAbstract.php =================================================================== --- trunk/library/classes/MUtil/Batch/BatchAbstract.php (rev 0) +++ trunk/library/classes/MUtil/Batch/BatchAbstract.php 2012-01-12 17:30:32 UTC (rev 407) @@ -0,0 +1,178 @@ +<?php + +/** + * Copyright (c) 2011, Erasmus MC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Erasmus MC nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * @package MUtil + * @subpackage Batch + * @author Matijs de Jong <mj...@ma...> + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @version $Id$ + */ + +/** + * + * + * @package MUtil + * @subpackage Batch + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @since Class available since version 1.5 + */ +abstract class MUtil_Batch_BatchAbstract extends MUtil_Registry_TargetAbstract implements Countable +{ + const PULL = 'Pull'; + const PUSH = 'Push'; + + /** + * + * @var Zend_Session_Namespace + */ + private $_session; + + /** + * + * @param string $name The name of this batch, defaults to classname + */ + public function __construct($name = null) + { + if (null === $name) { + $name = get_class($this); + } + + $this->_initSession($name); + } + + private function _initSession($name) + { + $this->_session = new Zend_Session_Namespace($name); + + if (! isset($this->_session->commands)) { + $this->_session->commands = array(); + $this->_session->counters = array(); + $this->_session->count = 0; + $this->_session->processed = 0; + } + } + + /** + * Add an execution step to the command stack. + * + * @param string $method Name of a method of this object + * @param mixed $id A unique id to prevent double adding of something to do + * @param mixed $param1 Scalar or array with scalars, as many parameters as needed allowed + * @return MUtil_Batch_BatchAbstract + */ + protected function addStep($method, $id, $param1 = null) + { + $params = array_slice(func_get_args(), 2); + + if (! method_exists($this, $method)) { + throw new MUtil_Batch_BatchException("Invalid batch method: '$method'."); + } + if (! MUtil_Ra::isScalar($params)) { + throw new MUtil_Batch_BatchException("Non scalar batch parameter for method: '$method'."); + } + + $command['method'] = $method; + $command['parameters'] = $params; + + $this->_session->commands[$id] = $command; + + return $this; + } + + protected function addToCounter($name, $add = 1) + { + if (! isset($this->session->counters[$name])) { + $this->session->counters[$name] = 0; + } + $this->session->counters[$name] += $add; + + return $this->session->counters[$name]; + } + + /** + * Count the number of commands + * + * @return int The custom count as an integer. + */ + public function count() + { + return count($this->_session->commands); + } + + public function getPanel() + { + return new MUtil_Html_ProgressPanel('0%'); + } + + public function hasStarted(Zend_Controller_Request_Abstract $request) + { + return false; + } + + /** + * Return true after commands all have been ran and there was at least one command to run. + * + * @return boolean + */ + public function isFinished() + { + return (0 == $this->_session->count()) && ($this->_session->processed > 0); + } + + /** + * Return true when at least one command has been loaded. + * + * @return boolean + */ + public function isLoaded() + { + return $this->count() || $this->_session->processed; + } + + public function runAll() + { + while ($this->step()); + + return $this->_session->processed; + } + + public function step() + { + if (isset($this->_session->commands) && $this->_session->commands) { + $command = array_shift($this->_session->commands); + $this->_session->processed++; + + call_user_func_array(array($this, $command['method']), $command['parameters']); + } + + return count($this->_session->commands) > 0; + } +} Added: trunk/library/classes/MUtil/Batch/BatchException.php =================================================================== --- trunk/library/classes/MUtil/Batch/BatchException.php (rev 0) +++ trunk/library/classes/MUtil/Batch/BatchException.php 2012-01-12 17:30:32 UTC (rev 407) @@ -0,0 +1,48 @@ +<?php + +/** + * Copyright (c) 2011, Erasmus MC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Erasmus MC nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * @package MUtil + * @subpackage Batch + * @author Matijs de Jong <mj...@ma...> + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @version $Id$ + */ + +/** + * + * + * @package MUtil + * @subpackage Batch + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @since Class available since version 1.5 + */ +class MUtil_Batch_BatchException extends Zend_Exception +{ } Modified: trunk/library/classes/MUtil/Html/HtmlException.php =================================================================== --- trunk/library/classes/MUtil/Html/HtmlException.php 2012-01-12 12:00:47 UTC (rev 406) +++ trunk/library/classes/MUtil/Html/HtmlException.php 2012-01-12 17:30:32 UTC (rev 407) @@ -1,40 +1,49 @@ <?php - -/** - * Copyright (c) 2011, Erasmus MC - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Erasmus MC nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - /** - * @author Matijs de Jong - * @since 1.0 - * @version 1.1 - * @package MUtil + * Copyright (c) 2011, Erasmus MC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Erasmus MC nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * @package MUtil * @subpackage Html + * @author Matijs de Jong <mj...@ma...> + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @version $Id$ */ -class MUtil_Html_HtmlException extends Exception +/** + * + * + * @package MUtil + * @subpackage Html + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @since Class available since version 1.0 + */ + +class MUtil_Html_HtmlException extends Zend_Exception { } \ No newline at end of file Property changes on: trunk/library/classes/MUtil/Queue ___________________________________________________________________ Added: bugtraq:url + http://survey.erasmusmc.nl/support/mantis/view.php?id=%BUGID% Added: bugtraq:logregex + #(\d+) Property changes on: trunk/library/classes/MUtil/Queue/Adapter ___________________________________________________________________ Added: bugtraq:url + http://survey.erasmusmc.nl/support/mantis/view.php?id=%BUGID% Added: bugtraq:logregex + #(\d+) Added: trunk/library/classes/MUtil/Queue/Adapter/DbPrefixed.php =================================================================== --- trunk/library/classes/MUtil/Queue/Adapter/DbPrefixed.php (rev 0) +++ trunk/library/classes/MUtil/Queue/Adapter/DbPrefixed.php 2012-01-12 17:30:32 UTC (rev 407) @@ -0,0 +1,67 @@ +<?php + +/** + * Copyright (c) 2011, Erasmus MC + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Erasmus MC nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * + * @package MUtil + * @subpackage Queue + * @author Matijs de Jong <mj...@ma...> + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @version $Id: mjong$ + */ + +/** + * + * + * @package MUtil + * @subpackage Queue + * @copyright Copyright (c) 2011 Erasmus MC + * @license New BSD License + * @since Class available since version 1.5 + */ +class MUtil_Queue_Adapter_DbPrefixed extends Zend_Queue_Adapter_Db +{ + /** + * Constructor + * + * @param array|Zend_Config $options + * @param Zend_Queue|null $queue + * @return void + */ + public function __construct($options, Zend_Queue $queue = null) + { + parent::__construct($options, $queue); + + if (isset($this->_options['prefix'])) { + $prefix = $this->_options['prefix']; + + $this->_queueTable->setOptions(array(Zend_Db_Table_Abstract::NAME => $prefix . $this->_queueTable->info(Zend_Db_Table_Abstract::NAME))); + $this->_messageTable->setOptions(array(Zend_Db_Table_Abstract::NAME => $prefix . $this->_messageTable->info(Zend_Db_Table_Abstract::NAME))); + } + } +} Modified: trunk/library/classes/MUtil/Ra.php =================================================================== --- trunk/library/classes/MUtil/Ra.php 2012-01-12 12:00:47 UTC (rev 406) +++ trunk/library/classes/MUtil/Ra.php 2012-01-12 17:30:32 UTC (rev 407) @@ -404,6 +404,12 @@ return self::$_toArrayConverter; } + /** + * Returns true if the $object either is an array or can be converted to an array. + * + * @param mixed $object + * @return boolean + */ public static function is($object) { if (is_array($object)) { @@ -414,6 +420,33 @@ } /** + * Test whether the value is scalar or an array containing + * scalars or scalar arrays. + * + * @param mixed $value + * @return boolean + */ + public static function isScalar($value) + { + if (null === $value) { + return true; + + } + + if (is_array($value)) { + foreach($value as $sub_value) { + if (! self::isScalar($sub_value)) { + return false; + } + } + return true; + + } + + return is_scalar($value); + } + + /** * A function that transforms an array in the form key1, value1, key2, value2 into array(key1 => value1, key2 => value2). * * When the $args array contains only a single sub array, then this value is assumed to be the return value. This allows This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-01-19 17:17:51
|
Revision: 412 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=412&view=rev Author: matijsdejong Date: 2012-01-19 17:17:39 +0000 (Thu, 19 Jan 2012) Log Message: ----------- Batch processing works (#35) and is implemented for SurveyMaintenanceAction.php checks. Modified Paths: -------------- trunk/library/classes/Gems/Default/SourceAction.php trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php trunk/library/classes/Gems/Tracker/TrackerInterface.php trunk/library/classes/Gems/Tracker.php trunk/library/classes/MUtil/Batch/BatchAbstract.php trunk/library/classes/MUtil/Batch/BatchPull.js trunk/library/classes/MUtil/Batch/BatchPush.js trunk/library/classes/MUtil/Batch/WaitBatch.php trunk/library/classes/MUtil/ProgressBar/Adapter/JsPush.php Modified: trunk/library/classes/Gems/Default/SourceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SourceAction.php 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/Gems/Default/SourceAction.php 2012-01-19 17:17:39 UTC (rev 412) @@ -246,77 +246,34 @@ /* $batch = new MUtil_Batch_WaitBatch(); - $batch->method = MUtil_Batch_BatchAbstract::PUSH; - if ($batch->isLoaded()) { - if ($batch->isFinished()) { - if (! $batch->showReport($this->getRequest())) { - $batch->reset(); - } - } else { - if ($batch->hasStarted($this->getRequest())) { - $batch->runAll(); - exit; - } - } - } else { - $batch->addWaits(4, 2); - $batch->addWaitsLater(15, 1); - $batch->addWaits(1, 1); - $batch->addWaitsLater(1, 2); - $batch->addWaits(4); - } - if ($batch->showReport($this->getRequest())) { - $this->addMessage($batch->getReport()); - $batch->reset(); - $this->html->pInfo()->actionLink(array($batch->progressParameterName => null), $this->_('Restart')); - } else { - $this->html->append($batch->getPanel($this->view)); - } - // */ - /* - // $batch = new Gems_Tracker_Batch_SynchronizeSourceBatch(); - // $batch->method = 'Push'; - if (! $batch->isLoaded()) { - foreach ($data as $row) { - $batch->addSource($row['gso_id_source'], $row['gso_source_name']); - } - } + // $batch->setMethodPush(5); + // $batch->autoStart = true; + // $batch->minimalStepDurationMs = 2000; if ($batch->run($this->getRequest())) { - if ($batch->isReady()) { - $this->addMessage($batch->getMessages()); - $this->afterSaveRoute($this->getRequest()); - } + exit; } else { - $this->html[] = $batch->getPanel(); - } - // */ - /* - $progress = $this->html->progress('0%'); - $progress->method = 'Push'; - // $progress = $this->html->progress(); - if ($progress->run($this->getRequest())) { - - // IIS 7: %windir%\System32\inetsrv\config\applicationHost.config - // ../handlers/add name="PHP_via_FastCGI" - // ../handlers/add name="CGI-exe" - // add attribute responseBufferLimit="1024" - - for ($i = 50; $i < 100; $i += 1) { - if ($i < 20) { - $text = 'Just beginning'; - } else if ($i < 50) { - $text = 'A bit done'; - } else if ($i < 80) { - $text = 'Getting closer'; + if ($batch->isFinished()) { + $this->addMessage($batch->getMessages(true)); + $this->html->pInfo($batch->getRestartButton($this->_('Prepare restart'), array('class' => 'actionlink'))); + } else { + // Populate the batch (from scratch). + $batch->reset(); + if (true) { + $batch->addWaitsMs(400, 20); + $batch->addWaits(2, 1, 'Har har'); + $batch->addWaitsMs(20, 50); } else { - $text = 'Nearly done'; + $batch->addWaits(4, 2); + $batch->addWaits(2, 1); + $batch->addWaitsLater(15, 1); + $batch->addWait(4, 'That took some time!'); + $batch->addWait(4, 'So we see the message. :)'); + $batch->addWaitsLater(1, 2); + $batch->addWaits(4); } - // IIS? - // echo str_repeat(' ',1024*3); - $progress->update($i, ' ' . $text); - sleep(1); + $this->html->pInfo($batch->getStartButton($this->_('Start synchronization'))); + $this->html->append($batch->getPanel($this->view, '0%')); } - $progress->finish(); } // */ if ($data) { Modified: trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php 2012-01-19 17:17:39 UTC (rev 412) @@ -268,42 +268,52 @@ $surveyId = $this->_getParam(MUtil_Model::REQUEST_ID); $where = $this->db->quoteInto('gto_id_survey = ?', $surveyId); - /* $batch = $this->loader->getTracker()->recalculateTokensBatch($this->loader->getCurrentUser()->getUserId(), $where); - if ($batch->hasStarted($this->getRequest())) { - // TODO + if ($batch->run($this->getRequest())) { + exit; } else { $this->html->h3( sprintf($this->_('Checking survey results for the %s survey.'), $this->db->fetchOne("SELECT gsu_survey_name FROM gems__surveys WHERE gsu_id_survey = ?", $surveyId))); - if ($batch->isLoaded()) { - $this->html->pInfo(sprintf($this->_('Running check for %s tokens...'), $batch->count())); - $this->html->append($batch->getPanel()); + if ($batch->isFinished()) { + $this->addMessage($batch->getMessages(true)); + $this->html->pInfo($batch->getRestartButton($this->_('Prepare recheck'), array('class' => 'actionlink'))); } else { - $this->html->pInfo($this->_('No tokens to check.')); + if ($batch->count()) { + // Batch is loaded by Tracker + $this->html->pInfo($batch->getStartButton(sprintf($this->_('Check %s tokens'), $batch->count()))); + $this->html->append($batch->getPanel($this->view, '0%')); + } else { + $this->html->pInfo($this->_('No tokens to check.')); + } } } - // */ - - //* - $this->addMessage(sprintf($this->_( - 'Checking survey results for the %s survey.'), - $this->db->fetchOne("SELECT gsu_survey_name FROM gems__surveys WHERE gsu_id_survey = ?", $surveyId))); - - $this->addMessage($this->loader->getTracker()->recalculateTokens($this->session->user_id, $where)); - - $this->afterSaveRoute($this->getRequest()); - - // */ } public function checkAllAction() { - $this->addMessage($this->loader->getTracker()->recalculateTokens($this->session->user_id)); + $batch = $this->loader->getTracker()->recalculateTokensBatch($this->loader->getCurrentUser()->getUserId()); - $this->afterSaveRoute($this->getRequest()); + if ($batch->run($this->getRequest())) { + exit; + } else { + $this->html->h3($this->_('Checking survey results for all surveys.')); + + if ($batch->isFinished()) { + $this->addMessage($batch->getMessages(true)); + $this->html->pInfo($batch->getRestartButton($this->_('Prepare recheck'), array('class' => 'actionlink'))); + } else { + if ($batch->count()) { + // Batch is loaded by Tracker + $this->html->pInfo($batch->getStartButton(sprintf($this->_('Check %s tokens'), $batch->count()))); + $this->html->append($batch->getPanel($this->view, '0%')); + } else { + $this->html->pInfo($this->_('No tokens to check.')); + } + } + } } /** Modified: trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php =================================================================== --- trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php 2012-01-19 17:17:39 UTC (rev 412) @@ -50,15 +50,14 @@ * * @var Gems_Tracker */ - public $tracker; + protected $tracker; - public function __construct($where, Gems_Tracker $tracker) - { - parent::__construct(__CLASS__ . '::' . $where); + /** + * + * @var Zend_Translate + */ + protected $translate; - $this->tracker = $tracker; - } - public function addToken($tokenData, $userId) { if (is_array($tokenData)) { @@ -71,7 +70,7 @@ } // MUtil_Echo::track($tokenData); - $this->setStep('checkTokenCompletion', 'tokchk-' . $tokenId, $tokenData); + $this->setStep('checkTokenCompletion', 'tokchk-' . $tokenId, $tokenData, $userId); return $this; } @@ -105,6 +104,68 @@ } } + public function getCounterMessages() + { + if ($this->getCounter('checkedRespondentTracks')) { + $messages[] = sprintf($this->translate->_('Checked %d tracks.'), $this->getCounter('checkedRespondentTracks')); + } + if ($this->getCounter('checkedTokens') || (! $this->getCounter('checkedRespondentTracks'))) { + $messages[] = sprintf($this->translate->_('Checked %d tokens.'), $this->getCounter('checkedTokens')); + } + + if ($this->hasChanged()) { + if ($this->getCounter('surveyCompletionChanges')) { + $messages[] = sprintf($this->translate->_('Answers changed by survey completion event for %d tokens.'), $this->getCounter('surveyCompletionChanges')); + } + if ($this->getCounter('resultDataChanges')) { + $messages[] = sprintf($this->translate->_('Results and timing changed for %d tokens.'), $this->getCounter('resultDataChanges')); + } + if ($this->getCounter('roundCompletionChanges')) { + $messages[] = sprintf($this->translate->_('%d token round completion events caused changed to %d tokens.'), $this->getCounter('roundCompletionCauses'), $this->getCounter('roundCompletionChanges')); + } + if ($this->getCounter('tokenDateChanges')) { + $messages[] = sprintf($this->translate->_('%2$d token date changes in %1$d tracks.'), $this->getCounter('tokenDateCauses'), $this->getCounter('tokenDateChanges')); + } + if ($this->getCounter('roundChangeUpdates')) { + $messages[] = sprintf($this->translate->_('Round changes propagated to %d tokens.'), $this->getCounter('roundChangeUpdates')); + } + if ($this->getCounter('deletedTokens')) { + $messages[] = sprintf($this->translate->_('%d tokens deleted by round changes.'), $this->getCounter('deletedTokens')); + } + if ($this->getCounter('createdTokens')) { + $messages[] = sprintf($this->translate->_('%d tokens created to by round changes.'), $this->getCounter('createdTokens')); + } + } else { + $messages[] = $this->translate->_('No tokens were changed.'); + } + + return $messages; + } + + /** + * String of messages from the batch + * + * Do not forget to reset() the batch if you're done with it after + * displaying the report. + * + * @param boolean $reset When true the batch is reset afterwards + * @return array + */ + public function getMessages($reset = false) + { + return array_merge($this->getCounterMessages(), parent::getMessages($reset)); + } + + public function hasChanged() + { + return $this->getCounter('resultDataChanges') || + $this->getCounter('surveyCompletionChanges') || + $this->getCounter('roundCompletionChanges') || + $this->getCounter('tokenDateCauses') || + $this->getCounter('roundChangeUpdates') || + $this->getCounter('createdTokens'); + } + protected function processTokenCompletion($tokenData, $userId) { $token = $this->tracker->getToken($tokenData); @@ -118,7 +179,7 @@ } $trackId = $respTrack->getRespondentTrackId(); - $this->setStep('checkTrackTokens', 'chktrck-' . $trackId, $trackId, $userid); + $this->setStep('checkTrackTokens', 'chktrck-' . $trackId, $trackId, $userId); } } } Modified: trunk/library/classes/Gems/Tracker/TrackerInterface.php =================================================================== --- trunk/library/classes/Gems/Tracker/TrackerInterface.php 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/Gems/Tracker/TrackerInterface.php 2012-01-19 17:17:39 UTC (rev 412) @@ -288,4 +288,17 @@ * @return array of translated messages */ public function recalculateTokens($userId = null, $cond = null); + + /** + * Recalculates all token dates, timing and results + * and outputs text messages. + * + * Does not reflect changes to tracks or rounds. + * + * @param Zend_Translate $t + * @param int $userId Id of the user who takes the action (for logging) + * @param string $cond + * @return Gems_Tracker_Batch_ProcessTokensBatch A batch to process the changes + */ + public function recalculateTokensBatch($userId = null, $cond = null); } Modified: trunk/library/classes/Gems/Tracker.php =================================================================== --- trunk/library/classes/Gems/Tracker.php 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/Gems/Tracker.php 2012-01-19 17:17:39 UTC (rev 412) @@ -838,7 +838,7 @@ { $where = implode(' ', $tokenSelect->getSelect()->getPart(Zend_Db_Select::WHERE)); - $batch = new Gems_Tracker_Batch_ProcessTokensBatch($where, $this); + $batch = $this->_loadClass('Batch_ProcessTokensBatch', true); //, array($where, $this)); if (! $batch->isLoaded()) { $tokenRows = $tokenSelect->fetchAll(); Modified: trunk/library/classes/MUtil/Batch/BatchAbstract.php =================================================================== --- trunk/library/classes/MUtil/Batch/BatchAbstract.php 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/MUtil/Batch/BatchAbstract.php 2012-01-19 17:17:39 UTC (rev 412) @@ -46,11 +46,15 @@ * Each step in the sequence consists of a method name of the child object * and any number of scalar variables and array's containing scalar variables. * + * See MUtil_Batch_WaitBatch for example usage. + * * A nice future extension would be to separate the storage engine used so we * could use e.g. Zend_Queue as an alternative for storing the command stack. * However, as this package needs more state info than available in Zend_Queue * we would need an extra extension for that. * + * @see MUtil_Batch_WaitBatch + * * @package MUtil * @subpackage Batch * @copyright Copyright (c) 2012 Erasmus MC @@ -94,17 +98,40 @@ * * @var boolean */ - public $autoStart = true; + public $autoStart = false; /** - * The mode to use for the panel: push or pull + * The number of bytes to pad during push communication in Kilobytes. * + * This is needed as many servers need extra output passing to avoid buffering. + * + * Also this allows you to keep the server buffer high while using this JsPush. + * + * @var int + */ + public $extraPushPaddingKb = 0; + + /** + * The mode to use for the panel: PUSH or PULL + * * @var string */ - public $method = self::PULL; + protected $method = self::PULL; /** + * The minimal time used between send progress reports. * + * This enables quicker processing as multiple steps can be taken in a single + * run(), without the run taking too long to answer. + * + * Set to 0 to report back on each step. + * + * @var int + */ + public $minimalStepDurationMs = 1000; + + /** + * * @var Zend_ProgressBar */ protected $progressBar; @@ -230,66 +257,108 @@ */ protected function addToCounter($name, $add = 1) { - if (! isset($this->session->counters[$name])) { - $this->session->counters[$name] = 0; + if (! isset($this->_session->counters[$name])) { + $this->_session->counters[$name] = 0; } - $this->session->counters[$name] += $add; + $this->_session->counters[$name] += $add; - return $this->session->counters[$name]; + return $this->_session->counters[$name]; } - /** - * Count the number of commands + /** + * The number of commands in this batch (both processed + * and unprocessed). * - * @return int The custom count as an integer. - */ - public function count() + * @return int + */ + public function count() { - return count($this->_session->commands); + return count($this->_session->commands) + $this->_session->processed; } /** - * Returns the prefix used for the function names to avoid naming clashes. + * Return the value of a named counter * + * @param string $name + * @return integer + */ + public function getCounter($name) + { + MUtil_Echo::track($this->_session->counters); + if (isset($this->_session->counters[$name])) { + return $this->_session->counters[$name]; + } + + return 0; + } + + /** + * Returns the prefix used for the function names for the PUSH method to avoid naming clashes. + * + * Set automatically to get_class($this) . '_' $this->_id . '_', use different name + * in case of name clashes. + * + * @see setFunctionPrefix() + * * @return string */ - public function getFunctionPrefix() + protected function getFunctionPrefix() { if (! $this->_functionPrefix) { - $this->setFunctionPrefix(__CLASS__ . '_' . $this->_id . '_'); + $this->setFunctionPrefix(get_class($this) . '_' . $this->_id . '_'); } return (string) $this->_functionPrefix; } /** - * Return + * String of messages from the batch + * + * Do not forget to reset() the batch if you're done with it after + * displaying the report. + * + * @param boolean $reset When true the batch is reset afterwards + * @return array + */ + public function getMessages($reset = false) + { + $messages = $this->_session->messages; + + if ($reset) { + $this->reset(); + } + + return $messages; + } + + /** + * Return a progress panel object, set up to be used by + * this batch. + * + * @param Zend_View_Abstract $view + * @param mixed $arg_array MUtil_Ra::args() arguments to populate progress bar with * @return MUtil_Html_ProgressPanel */ - public function getPanel(Zend_View_Abstract $view) + public function getPanel(Zend_View_Abstract $view, $arg_array = null) { + $args = func_get_args(); + ZendX_JQuery::enableView($view); - if ($this->isFinished()) { - $content = '100%'; - } else { - $content = '100%'; - } + $urlFinish = $view->url(array($this->progressParameterName => $this->progressParameterReportValue)); + $urlRun = $view->url(array($this->progressParameterName => $this->progressParameterRunValue)); - $panel = new MUtil_Html_ProgressPanel('0%'); - + $panel = new MUtil_Html_ProgressPanel($args); $panel->id = $this->_id; - $panel->method = $this->method; $js = new MUtil_Html_Code_JavaScript(dirname(__FILE__) . '/Batch' . $this->method . '.js'); $js->setInHeader(false); // Set the fields, in case they where not set earlier $js->setDefault('__AUTOSTART__', $this->autoStart ? 'true' : 'false'); - $js->setDefault('{ID}', $this->_id); - $js->setDefault('{TEXT_TAG}', $panel->getDefaultChildTag()); - $js->setDefault('{TEXT_CLASS}', $panel->progressTextClass); - $js->setDefault('{URL_FINISH}', addcslashes($view->url(array($this->progressParameterName => $this->progressParameterReportValue)), "/")); - $js->setDefault('{URL_START}', addcslashes($view->url(array($this->progressParameterName => $this->progressParameterRunValue)), "/")); + $js->setDefault('{PANEL_ID}', '#' . $this->_id); + $js->setDefault('{TEXT_ID}', $panel->getDefaultChildTag() . '.' . $panel->progressTextClass); + $js->setDefault('{URL_FINISH}', addcslashes($urlFinish, "/")); + $js->setDefault('{URL_START_RUN}', addcslashes($urlRun, "/")); $js->setDefault('FUNCTION_PREFIX_', $this->getFunctionPrefix()); $panel->append($js); @@ -298,61 +367,111 @@ } /** + * The Zend ProgressBar handles the communication through + * an adapter interface. * * @return Zend_ProgressBar */ public function getProgressBar() { if (! $this->progressBar instanceof Zend_ProgressBar) { - $this->setProgressBar(new Zend_ProgressBar($this->getProgressBarAdapter(), 0, 100)); + $this->setProgressBar(new Zend_ProgressBar($this->getProgressBarAdapter(), 0, 100, $this->_session->getNamespace() . '_pb')); } return $this->progressBar; } /** + * The communication adapter for the ProgressBar. * * @return Zend_ProgressBar_Adapter */ public function getProgressBarAdapter() { - if (! $this->progressBarAdapter instanceof Zend_ProgressBar_Adapter) { - if ($this->method == self::PULL) { + // Does the current adapter accord with the method? + if ($this->progressBarAdapter instanceof Zend_ProgressBar_Adapter) { + if ($this->isPull()) { + if (! $this->progressBarAdapter instanceof Zend_ProgressBar_Adapter_JsPull) { + $this->progressBarAdapter = null; + } + } else { + if (! $this->progressBarAdapter instanceof Zend_ProgressBar_Adapter_JsPush) { + $this->progressBarAdapter = null; + } + } + } else { + $this->progressBarAdapter = null; + } + + // Create when needed + if ($this->progressBarAdapter === null) { + if ($this->isPull()) { $this->setProgressBarAdapter(new Zend_ProgressBar_Adapter_JsPull()); } else { $this->setProgressBarAdapter(new MUtil_ProgressBar_Adapter_JsPush()); - $this->progressBarAdapter->extraPaddingKb = 3; } } + // Check for extra padding + if ($this->progressBarAdapter instanceof MUtil_ProgressBar_Adapter_JsPush) { + $this->progressBarAdapter->extraPaddingKb = $this->extraPushPaddingKb; + } + return $this->progressBarAdapter; } - public function getReport() + /** + * Returns a button that can be clicked to restart the progress bar. + * + * @param mixed $arg_array MUtil_Ra::args() arguments to populate link with + * @return MUtil_Html_HtmlElement + */ + public function getRestartButton($args_array = 'Restart') { - $messages = $this->_session->messages; + $args = MUtil_Ra::args(func_get_args()); + $args['onclick'] = new MUtil_Html_OnClickArrayAttribute( + new MUtil_Html_Raw('if (! this.disabled) {location.href = "'), + new MUtil_Html_HrefArrayAttribute(array($this->progressParameterName => null)), + new MUtil_Html_Raw('";} this.disabled = true; event.cancelBubble=true;')); - return $messages; + return new MUtil_Html_HtmlElement('button', $args); } /** - * Returns true when the parameters passed mean the program has started. + * Returns a link that can be clicked to restart the progress bar. * - * @param Zend_Controller_Request_Abstract $request - * @return boolean + * @param mixed $arg_array MUtil_Ra::args() arguments to populate link with + * @return MUtil_Html_AElement */ - public function hasStarted(Zend_Controller_Request_Abstract $request) + public function getRestartLink($args_array = 'Restart') { - return $request->getParam($this->progressParameterName) === $this->progressParameterRunValue; + $args = MUtil_Ra::args(func_get_args()); + $args['href'] = array($this->progressParameterName => null); + + return new MUtil_Html_AElement($args); } /** - * Return true after commands all have been ran and there was at least one command to run. + * Returns a button that can be clicked to start the progress bar. * + * @param mixed $arg_array MUtil_Ra::args() arguments to populate link with + * @return MUtil_Html_HtmlElement + */ + public function getStartButton($args_array = 'Start') + { + $args = MUtil_Ra::args(func_get_args()); + $args['onclick'] = 'if (! this.disabled) {' . $this->getFunctionPrefix() . 'Start();} this.disabled = true; event.cancelBubble=true;'; + + return new MUtil_Html_HtmlElement('button', $args); + } + + /** + * Return true after commands all have been ran. + * * @return boolean */ public function isFinished() { - return (0 == $this->count()) && ($this->_session->processed > 0); + return $this->_session->finished; } /** @@ -362,18 +481,102 @@ */ public function isLoaded() { - return $this->count() || $this->_session->processed; + return $this->_session->commands || $this->_session->processed; } + /** + * Does the batch use the PULL method for communication. + * + * @return boolean + */ + public function isPull() + { + return $this->method === self::PULL; + } + + /** + * Does the batch use the PUSH method for communication. + * + * @return boolean + */ + public function isPush() + { + return $this->method === self::PUSH; + } + + /** + * Reset and empty the session storage + * + * @return MUtil_Batch_BatchAbstract (continuation pattern) + */ public function reset() { $this->_session->commands = array(); $this->_session->counters = array(); $this->_session->count = 0; + $this->_session->finished = false; $this->_session->messages = array(); $this->_session->processed = 0; + + return $this; } + /** + * Run as much code as possible, but do report back. + * + * Returns true if any output was communicated, i.e. the "normal" + * page should not be displayed. + * + * @param Zend_Controller_Request_Abstract $request + * @return boolean + */ + public function run(Zend_Controller_Request_Abstract $request) + { + // Is there something to run? + if ($this->isFinished() || (! $this->isLoaded())) { + return false; + } + + // Check for run url + if ($request->getParam($this->progressParameterName) === $this->progressParameterRunValue) { + $bar = $this->getProgressBar(); + + $isPull = $this->isPull(); + $reportRun = microtime(true) + ($this->minimalStepDurationMs / 1000); + // error_log('Rep: ' . $reportRun); + while ($this->step()) { + // error_log('Cur: ' . microtime(true) . ' report is '. (microtime(true) > $reportRun ? 'true' : 'false')); + if (microtime(true) > $reportRun) { + // Communicate progress + $percent = round($this->_session->processed / (count($this->_session->commands) + $this->_session->processed) * 100, 2); + + $bar->update($percent, end($this->_session->messages)); + + // INFO: When using PULL $bar->update() should exit the program, + // but just let us make sure. + if ($isPull) { + return true; + } + } + } + if (! $this->_session->commands) { + $this->_session->finished = true; + $bar->finish(); + } + + // There is progressBar output + return true; + } else { + // No ProgressBar output + return false; + } + } + + /** + * Run the whole batch at once, without communicating with a progress bar. + * + * @return int Number of steps taken + */ public function runAll() { while ($this->step()); @@ -382,9 +585,9 @@ } /** - * Name prefix for functions. + * Name prefix for PUSH functions. * - * Set automatically to __CLASS___, use different name + * Set automatically to get_class($this) . '_' $this->_id . '_', use different name * in case of name clashes. * * @param string $prefix @@ -411,7 +614,81 @@ } /** + * Sets the communication method for progress reporting. * + * @param string $method One of the constants of this object + * @return MUtil_Batch_BatchAbstract (continuation pattern) + */ + public function setMethod($method) + { + switch ($method) { + case self::PULL: + case self::PUSH: + $this->method = $method; + return $this; + + default: + throw new MUtil_Batch_BatchException("Invalid batch usage method '$method'."); + } + } + + /** + * Set the communication method used by this batch to PULL. + * + * This is the most stable method as it works independently of + * server settings. Therefore it is the default method. + * + * @return MUtil_Batch_BatchAbstract (continuation pattern) + */ + public function setMethodPull() + { + $this->setMethod(self::PULL); + + return $this; + } + + /** + * Set the communication method used by this batch to PUSH. + * + * I.e. the start page opens an iFrame, the url of the iFrame calls the + * batch with the RUN parameter and the process returns JavaScript tags + * that handle the progress reporting. + * + * This is a very fast and resource inexpensive method for batch processing + * but it is only suitable for short running processes as servers tend to + * cut off http calls that take more than some fixed period of time to run - + * even when those processes keep returning data. + * + * Another problem with this method is buffering, i.e. the tendency of servers + * to wait sending data back until a process has been completed or enough data + * has been send. + * + * E.g. on IIS 7 you have to adjust the file %windir%\System32\inetsrv\config\applicationHost.config + * and add the attribute responseBufferLimit="1024" twice, both to + * ../handlers/add name="PHP_via_FastCGI" and to ../handlers/add name="CGI-exe". + * + * Still the above works only partially, IIS tends to wait longer before sending the + * first batch of data. The trick is to add extra spaces to the output until the + * threshold is reached. This is done by specifying the $extraPaddingKb parameter. + * Just increase it until it works. + * + * @param int $extraPaddingKb + * @return MUtil_Batch_BatchAbstract (continuation pattern) + */ + public function setMethodPush($extraPaddingKb = null) + { + $this->setMethod(self::PUSH); + if ((null !== $extraPaddingKb) && is_numeric($extraPaddingKb)) { + $this->extraPushPaddingKb = $extraPaddingKb; + } + + return $this; + } + + /** + * The Zend ProgressBar handles the communication through + * an adapter interface. + * * @param Zend_ProgressBar $progressBar * @return MUtil_Html_ProgressPanel (continuation pattern) */ @@ -422,6 +699,7 @@ } /** + * The communication adapter for the ProgressBar. * * @param Zend_ProgressBar_Adapter_Interface $adapter * @return MUtil_Html_ProgressPanel (continuation pattern) @@ -458,40 +736,20 @@ } /** - * Returns true when the parameters passed mean the program has started. + * Progress a single step on the command stack * - * @param Zend_Controller_Request_Abstract $request * @return boolean */ - public function showReport(Zend_Controller_Request_Abstract $request) + protected function step() { - return $request->getParam($this->progressParameterName) === $this->progressParameterReportValue; - } - - /** - * Workhorse function that does all the real work. - * - * @return int - */ - public function step() - { - $bar = $this->getProgressBar(); - if (isset($this->_session->commands) && $this->_session->commands) { $command = array_shift($this->_session->commands); $this->_session->processed++; call_user_func_array(array($this, $command['method']), $command['parameters']); - - $percent = round($this->_session->processed / ($this->count() + $this->_session->processed) * 100, 2); - - $bar->update($percent, end($this->_session->messages)); return true; } else { - $bar->finish(); - return false; } - return count($this->_session->commands) > 0; } } Modified: trunk/library/classes/MUtil/Batch/BatchPull.js =================================================================== --- trunk/library/classes/MUtil/Batch/BatchPull.js 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/MUtil/Batch/BatchPull.js 2012-01-19 17:17:39 UTC (rev 412) @@ -5,82 +5,101 @@ // default options options: { - autoStart: false, - // target: the element whose content is replaced - timeout: 2000 - // url: the request url + // finishUrl: the request url + // panelId: text id:, + // runUrl: the request url + // targetId: search for the element whose content is replaced + timeout: 60000 }, _init: function() { - if (this.options.autoStart) { - this.start(); + this.progressTarget = jQuery(this.options.panelId); + if (this.progressTarget.length) { + this.textTarget = this.progressTarget.find(this.options.targetId); + // this.textTarget = this.find(this.options.targetId); + + if (this.textTarget.length) { + this.start(); + } else { + alert('Did not find the text element: "' + this.options.targetId + '" in element id: "' + this.options.panelId + '".'); + } + } else { + alert('Did not find the panel id: "' + this.options.panelId + '".'); } }, complete: function (request, status) { this.request = null; - - // Check for changes - // - if the input field was changed since the last request - // filter() will search on the new value - // - if the input field has not changed, then no new request - // is made. - // this.start(); }, - error: function (request, status) { - console.log(status); - /* if (request.status === 401) { - location.href = location.href; - } // */ + error: function (request, status, error) { + alert('Communication error: ' + status); }, + progressTarget: null, + start: function() { if (this.request == null) { - if (this.options.url) { + if (this.options.runUrl) { var self = this; this.request = jQuery.ajax({ - url: this.options.url, + url: this.options.runUrl, type: "GET", dataType: "json", // data: postData, - error: function(request, status, error) {self.error(request, status);}, + error: function(request, status, error) {self.error(request, status, error);}, complete: function(request, status) {self.complete(request, status);}, success: function(data, status, request) {self.success(data, status, request);} }); - + } else { + alert("No runUrl specified."); } } }, success: function (data, status, request) { - // console.log(stringdata); - // data = jQuery.parseJSON(stringdata); - console.log(data); + // console.log(data); + if (data.finished) { + data.percent = 100; + data.text = false; + } + // For some reason the next two lines are both needed for the code to work + this.progressTarget.progressbar("option", "value", data.percent); + this.progressTarget.progressbar({value: data.percent}); + text = data.percent + '%'; if (data.text) { - text = text + data.text; + text = text + ' ' + data.text; } - jQuery(this.options.target).html(text); + this.textTarget.html(text); + + if (data.finished) { + if (this.options.finishUrl.length > 0) { + location.href = this.options.finishUrl; + } + } else { + this.request = null; + this.start(); + } }, + textTarget: null, + request: null }); -jQuery(document).ready(function() { - jQuery("#{ID}").pullProgressPanel({"url":"{URL_START}","autoStart":__AUTOSTART__,"target":"#{ID} {TEXT_TAG}.{TEXT_CLASS}"}); -}); - -function FUNCTION_PREFIX_Finish() +function FUNCTION_PREFIX_Start() { - main = jQuery("#{ID}"); - main.progressbar( "option", "value", 100); + jQuery("{PANEL_ID}").pullProgressPanel({ + "finishUrl": "{URL_FINISH}", + "panelId": "{PANEL_ID}", + "runUrl": "{URL_START_RUN}", + "targetId": "{TEXT_ID}" + }); +} - inner = main.find('{TEXT_TAG}.{TEXT_CLASS}'); - if (inner) { - inner.empty(); - inner.append('100% Done!'); - } +if (__AUTOSTART__) { + jQuery().ready(FUNCTION_PREFIX_Start()); } Modified: trunk/library/classes/MUtil/Batch/BatchPush.js =================================================================== --- trunk/library/classes/MUtil/Batch/BatchPush.js 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/MUtil/Batch/BatchPush.js 2012-01-19 17:17:39 UTC (rev 412) @@ -3,18 +3,18 @@ { var iFrame = document.createElement('iframe'); iFrame.setAttribute('style', 'position: absolute; left: -100px; top: -100px; width: 10px; height: 10px; overflow: hidden;'); - // iFrame.setAttribute('style', 'position: absolute; left: 0px; top: 0px; width: 100px; height: 100px; overflow: hidden;'); document.getElementsByTagName('body')[0].appendChild(iFrame); - iFrame.src = '{URL_START}'; + iFrame.src = '{URL_START_RUN}'; } function FUNCTION_PREFIX_Update(data) { - main = jQuery("#{ID}"); - main.progressbar( "option", "value", data.percent); + main = jQuery("{PANEL_ID}"); + // For some reason the next two lines are both needed for the code to work + main.progressbar("option", "value", data.percent); main.progressbar({value: data.percent}); - inner = main.find('{TEXT_TAG}.{TEXT_CLASS}'); + inner = main.find('{TEXT_ID}'); if (inner) { text = data.percent + '%'; if (data.text) { @@ -26,10 +26,12 @@ function FUNCTION_PREFIX_Finish() { - main = jQuery("#{ID}"); - main.progressbar( "option", "value", 100); + main = jQuery("{PANEL_ID}"); + // For some reason the next two lines are both needed for the code to work + main.progressbar("option", "value", 100); + main.progressbar({value: 100}); - inner = main.find('{TEXT_TAG}.{TEXT_CLASS}'); + inner = main.find('{TEXT_ID}'); if (inner) { inner.empty(); inner.append('100% Done!'); @@ -41,7 +43,6 @@ } } - if (__AUTOSTART__) { jQuery().ready(FUNCTION_PREFIX_Start()); } \ No newline at end of file Modified: trunk/library/classes/MUtil/Batch/WaitBatch.php =================================================================== --- trunk/library/classes/MUtil/Batch/WaitBatch.php 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/MUtil/Batch/WaitBatch.php 2012-01-19 17:17:39 UTC (rev 412) @@ -36,8 +36,65 @@ */ /** + * This a an example / test implementation of MUtil_Batch_BatchAbstract. * + * It does nothing but wait, but allows you to test the workings of the + * batch processing in general and the use of a progress panel in general. * + * PULL usage example ($this->view must be a Zend_View) with a nice start button: + * <code> + * $batch = new MUtil_Batch_WaitBatch(); + * if ($batch->run($this->getRequest())) { + * exit; + * } else { + * $html = new MUtil_Html_Sequence(); + * if ($batch->isFinished()) { + * $html->ol($batch->getMessages(true)); + * $html->a(array($batch->progressParameterName => null), 'Restart'); + * } else { + * // Populate the batch (from scratch). + * $batch->reset(); + * $batch->addWaits(4, 2); + * $batch->addWaits(2, 1); + * $batch->addWaitsLater(15, 1); + * $batch->addWait(4, 'That took some time!'); + * $batch->addWait(4, 'So we see the message. :)'); + * $batch->addWaitsLater(1, 2); + * $batch->addWaits(4); + * + * $html->append($batch->getPanel($this->view, $batch->getStartButton('Nice start'))); + * } + * echo $html->render($this->view); + * } + * </code> + * + * PUSH usage example that starts automatically: + * <code> + * $batch = new MUtil_Batch_WaitBatch(); + * $batch->setMethodPush(5); + * $batch->autoStart = true; + * $batch->minimalStepDurationMs = 200; + * + * if ($batch->run($this->getRequest())) { + * exit; + * } else { + * $html = new MUtil_Html_Sequence(); + * if ($batch->isFinished()) { + * $html->ul($batch->getMessages(true)); + * $html->a(array($batch->progressParameterName => null), 'Restart'); + * } else { + * // Populate the batch (from scratch). + * $batch->reset(); + * $batch->addWaitsMs(400, 20); + * $batch->addWaits(2, 1, 'Har har'); + * $batch->addWaitsMs(20, 50); + * + * $html->append($batch->getPanel($this->view)); + * } + * echo $html->render($this->view); + * } + * </code> + * * @package MUtil * @subpackage Batch * @copyright Copyright (c) 2011 Erasmus MC @@ -46,37 +103,156 @@ */ class MUtil_Batch_WaitBatch extends MUtil_Batch_BatchAbstract { - public function addWait($seconds = 1) + /** + * The minimal time used between send progress reports. + * + * This enables quicker processing as multiple steps can be taken in a single + * run(), without the run taking too long to answer. + * + * Set to 0 to report back on each step. + * + * @var int + */ + public $minimalStepDurationMs = 100; + + /** + * Add one second wait command to the command stack. + * + * @param int $seconds + * @param text $message Optional, otherwise the message is the time of wait + * @return MUtil_Batch_WaitBatch (continuation pattern) + */ + public function addWait($seconds = 1, $message = null) { - $this->addStep('waitFor', $seconds); + $this->addStep('waitFor', $seconds, $message); return $this; } - public function addWaits($times, $seconds = 1) + /** + * Add one microsecond wait command to the command stack. + * + * @param int $microsSeconds + * @param text $message Optional, otherwise the message is the time of wait + * @return MUtil_Batch_WaitBatch (continuation pattern) + */ + public function addWaitMs($microsSeconds = 100, $message = null) { + $this->addStep('waitForMs', $microsSeconds, $message); + + return $this; + } + + /** + * Add multiple second wait commands to the command stack. + * + * @param int $times + * @param int $seconds + * @param text $message Optional, otherwise the message is the time of wait + * @return MUtil_Batch_WaitBatch (continuation pattern) + */ + public function addWaits($times, $seconds = 1, $message = null) + { for ($i = 0; $i < $times; $i++) { - $this->addStep('waitFor', $seconds); + $this->addStep('waitFor', $seconds, $message); } return $this; } - public function addWaitsLater($times, $seconds = 1) + /** + * Add multiple microsecond wait commands to the command stack. + * + * @param int $times + * @param int $microsSeconds + * @param text $message Optional, otherwise the message is the time of wait + * @return MUtil_Batch_WaitBatch (continuation pattern) + */ + public function addWaitsMs($times, $microsSeconds = 100, $message = null) { - $this->addStep('addWaits', $times, $seconds); + for ($i = 0; $i < $times; $i++) { + $this->addStep('waitForMs', $microsSeconds, $message); + } return $this; } - public function waitFor($seconds) + /** + * Testing purposes only, this code adds wait commands to the + * command stack during running. + * + * The result is that you may see the percentage done actually + * decrease instead of increase. + * + * @param int $times + * @param int $seconds + * @param text $message Optional, otherwise the message is the time of wait + * @return MUtil_Batch_WaitBatch (continuation pattern) + */ + public function addWaitsLater($times, $seconds = 1, $message = null) { + $this->addStep('addWaits', $times, $seconds, $message); + + return $this; + } + + /** + * Testing purposes only, this code adds wait commands to the + * command stack during running. + * + * The result is that you may see the percentage done actually + * decrease instead of increase. + * + * @param int $times + * @param int $microsSeconds + * @param text $message Optional, otherwise the message is the time of wait + * @return MUtil_Batch_WaitBatch (continuation pattern) + */ + public function addWaitsMsLater($times, $microsSeconds = 100, $message = null) + { + $this->addStep('addWaitsMs', $times, $microsSeconds, $message); + + return $this; + } + + /** + * A step method that just waits for a number of seconds. + * + * @param int $seconds + * @param string $message + */ + protected function waitFor($seconds, $message) + { sleep($seconds); - if ($seconds == 1) { - $this->addMessage("Waited for 1 second."); - } else { - $this->addMessage(sprintf("Waited for %d seconds.", $seconds)); + if (! $message) { + if ($seconds == 1) { + $message = "Waited for 1 second."; + } else { + $message = sprintf("Waited for %d seconds.", $seconds); + } } + $this->addMessage($message); } + + /** + * A step method that just waits for a number of microseconds. + * + * @param int $microsSeconds + * @param string $message + */ + protected function waitForMs($microsSeconds, $message) + { + usleep($microsSeconds); + + if (! $message) { + if ($microsSeconds == 1) { + $message = "Waited for 1 micro second."; + } else { + $message = sprintf("Waited for %.3f seconds.", $microsSeconds / 1000); + } + } + + $this->addMessage($message); + } } Modified: trunk/library/classes/MUtil/ProgressBar/Adapter/JsPush.php =================================================================== --- trunk/library/classes/MUtil/ProgressBar/Adapter/JsPush.php 2012-01-18 15:47:17 UTC (rev 411) +++ trunk/library/classes/MUtil/ProgressBar/Adapter/JsPush.php 2012-01-19 17:17:39 UTC (rev 412) @@ -47,7 +47,7 @@ class MUtil_ProgressBar_Adapter_JsPush extends Zend_ProgressBar_Adapter_JsPush { /** - * The number of bytes to padd in Kilobytes + * The number of bytes to pad in Kilobytes * * This is needed as many servers need extra output passing to avoid buffering. * This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-01-20 17:06:15
|
Revision: 413 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=413&view=rev Author: matijsdejong Date: 2012-01-20 17:06:04 +0000 (Fri, 20 Jan 2012) Log Message: ----------- Applied progressBar (#45) for all source checks. Modified Paths: -------------- trunk/library/classes/Gems/Default/SourceAction.php trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php trunk/library/classes/Gems/Tracker/TrackerInterface.php trunk/library/classes/Gems/Tracker.php trunk/library/classes/MUtil/Batch/BatchAbstract.php Modified: trunk/library/classes/Gems/Default/SourceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SourceAction.php 2012-01-19 17:17:39 UTC (rev 412) +++ trunk/library/classes/Gems/Default/SourceAction.php 2012-01-20 17:06:04 UTC (rev 413) @@ -107,20 +107,52 @@ $sourceId = $this->getSourceId(); $where = $this->db->quoteInto('gto_id_survey IN (SELECT gsu_id_survey FROM gems__surveys WHERE gsu_id_source = ?)', $sourceId); - $this->addMessage(sprintf($this->_( - 'Checking survey results for %s source.'), + $batch = $this->loader->getTracker()->recalculateTokensBatch('sourceCheck' . $sourceId, $this->loader->getCurrentUser()->getUserId(), $where); + + if ($batch->run($this->getRequest())) { + exit; + } else { + $this->html->h3( + sprintf($this->_('Checking survey results for %s source.'), $this->db->fetchOne("SELECT gso_source_name FROM gems__sources WHERE gso_id_source = ?", $sourceId))); - $this->addMessage($this->loader->getTracker()->recalculateTokens($this->session->user_id, $where)); - - $this->afterSaveRoute($this->getRequest()); + if ($batch->isFinished()) { + $this->addMessage($batch->getMessages(true)); + $this->html->pInfo($batch->getRestartButton($this->_('Prepare recheck'), array('class' => 'actionlink'))); + } else { + if ($batch->count()) { + // Batch is loaded by Tracker + $this->html->pInfo($batch->getStartButton(sprintf($this->_('Check %s tokens'), $batch->count()))); + $this->html->append($batch->getPanel($this->view, '0%')); + } else { + $this->html->pInfo($this->_('No tokens to check.')); + } + } + } } public function checkAllAction() { - $this->addMessage($this->loader->getTracker()->recalculateTokens($this->session->user_id)); + $batch = $this->loader->getTracker()->recalculateTokensBatch('surveyCheckAll', $this->loader->getCurrentUser()->getUserId()); - $this->afterSaveRoute($this->getRequest()); + if ($batch->run($this->getRequest())) { + exit; + } else { + $this->html->h3($this->_('Checking survey results for all sources.')); + + if ($batch->isFinished()) { + $this->addMessage($batch->getMessages(true)); + $this->html->pInfo($batch->getRestartButton($this->_('Prepare recheck'), array('class' => 'actionlink'))); + } else { + if ($batch->count()) { + // Batch is loaded by Tracker + $this->html->pInfo($batch->getStartButton(sprintf($this->_('Check %s tokens'), $batch->count()))); + $this->html->append($batch->getPanel($this->view, '0%')); + } else { + $this->html->pInfo($this->_('No tokens to check.')); + } + } + } } /** @@ -258,18 +290,19 @@ } else { // Populate the batch (from scratch). $batch->reset(); - if (true) { + if (! true) { $batch->addWaitsMs(400, 20); $batch->addWaits(2, 1, 'Har har'); $batch->addWaitsMs(20, 50); } else { - $batch->addWaits(4, 2); - $batch->addWaits(2, 1); - $batch->addWaitsLater(15, 1); - $batch->addWait(4, 'That took some time!'); - $batch->addWait(4, 'So we see the message. :)'); - $batch->addWaitsLater(1, 2); - $batch->addWaits(4); + $batch->addWaits(1440, 10); + //$batch->addWaits(4, 2); + //$batch->addWaits(2, 1); + //$batch->addWaitsLater(15, 1); + //$batch->addWait(4, 'That took some time!'); + //$batch->addWait(4, 'So we see the message. :)'); + //$batch->addWaitsLater(1, 2); + //$batch->addWaits(4); } $this->html->pInfo($batch->getStartButton($this->_('Start synchronization'))); $this->html->append($batch->getPanel($this->view, '0%')); Modified: trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php 2012-01-19 17:17:39 UTC (rev 412) +++ trunk/library/classes/Gems/Default/SurveyMaintenanceAction.php 2012-01-20 17:06:04 UTC (rev 413) @@ -268,7 +268,7 @@ $surveyId = $this->_getParam(MUtil_Model::REQUEST_ID); $where = $this->db->quoteInto('gto_id_survey = ?', $surveyId); - $batch = $this->loader->getTracker()->recalculateTokensBatch($this->loader->getCurrentUser()->getUserId(), $where); + $batch = $this->loader->getTracker()->recalculateTokensBatch('surveyCheck' . $surveyId, $this->loader->getCurrentUser()->getUserId(), $where); if ($batch->run($this->getRequest())) { exit; @@ -294,7 +294,7 @@ public function checkAllAction() { - $batch = $this->loader->getTracker()->recalculateTokensBatch($this->loader->getCurrentUser()->getUserId()); + $batch = $this->loader->getTracker()->recalculateTokensBatch('surveyCheckAll', $this->loader->getCurrentUser()->getUserId()); if ($batch->run($this->getRequest())) { exit; Modified: trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php =================================================================== --- trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php 2012-01-19 17:17:39 UTC (rev 412) +++ trunk/library/classes/Gems/Tracker/Batch/ProcessTokensBatch.php 2012-01-20 17:06:04 UTC (rev 413) @@ -134,7 +134,7 @@ } if ($this->getCounter('createdTokens')) { $messages[] = sprintf($this->translate->_('%d tokens created to by round changes.'), $this->getCounter('createdTokens')); - } + } } else { $messages[] = $this->translate->_('No tokens were changed.'); } Modified: trunk/library/classes/Gems/Tracker/TrackerInterface.php =================================================================== --- trunk/library/classes/Gems/Tracker/TrackerInterface.php 2012-01-19 17:17:39 UTC (rev 412) +++ trunk/library/classes/Gems/Tracker/TrackerInterface.php 2012-01-20 17:06:04 UTC (rev 413) @@ -295,10 +295,10 @@ * * Does not reflect changes to tracks or rounds. * - * @param Zend_Translate $t + * @param string $batch_id A unique identifier for the current batch * @param int $userId Id of the user who takes the action (for logging) * @param string $cond * @return Gems_Tracker_Batch_ProcessTokensBatch A batch to process the changes */ - public function recalculateTokensBatch($userId = null, $cond = null); + public function recalculateTokensBatch($batch_id, $userId = null, $cond = null); } Modified: trunk/library/classes/Gems/Tracker.php =================================================================== --- trunk/library/classes/Gems/Tracker.php 2012-01-19 17:17:39 UTC (rev 412) +++ trunk/library/classes/Gems/Tracker.php 2012-01-20 17:06:04 UTC (rev 413) @@ -830,15 +830,16 @@ * * Does not reflect changes to tracks or rounds. * + * @param string $batch_id A unique identifier for the current batch * @param Gems_Tracker_Token_TokenSelect Select statements selecting tokens * @param int $userId Id of the user who takes the action (for logging) * @return Gems_Tracker_Batch_ProcessTokensBatch A batch to process the changes */ - protected function processTokensBatch(Gems_Tracker_Token_TokenSelect $tokenSelect, $userId) + protected function processTokensBatch($batch_id, Gems_Tracker_Token_TokenSelect $tokenSelect, $userId) { $where = implode(' ', $tokenSelect->getSelect()->getPart(Zend_Db_Select::WHERE)); - $batch = $this->_loadClass('Batch_ProcessTokensBatch', true); //, array($where, $this)); + $batch = $this->_loadClass('Batch_ProcessTokensBatch', true, array($batch_id)); if (! $batch->isLoaded()) { $tokenRows = $tokenSelect->fetchAll(); @@ -886,12 +887,12 @@ * * Does not reflect changes to tracks or rounds. * - * @param Zend_Translate $t - * @param int $userId Id of the user who takes the action (for logging) + * @param string $batch_id A unique identifier for the current batch + * @param int $userId Id of the user who takes the action (for logging) * @param string $cond * @return Gems_Tracker_Batch_ProcessTokensBatch A batch to process the changes */ - public function recalculateTokensBatch($userId = null, $cond = null) + public function recalculateTokensBatch($batch_id, $userId = null, $cond = null) { $userId = $this->_checkUserId($userId); $tokenSelect = $this->getTokenSelect(); @@ -904,6 +905,6 @@ $tokenSelect->forWhere('gsu_surveyor_active = 1'); self::$verbose = true; - return $this->processTokensBatch($tokenSelect, $userId); + return $this->processTokensBatch($batch_id, $tokenSelect, $userId); } } Modified: trunk/library/classes/MUtil/Batch/BatchAbstract.php =================================================================== --- trunk/library/classes/MUtil/Batch/BatchAbstract.php 2012-01-19 17:17:39 UTC (rev 412) +++ trunk/library/classes/MUtil/Batch/BatchAbstract.php 2012-01-20 17:06:04 UTC (rev 413) @@ -420,6 +420,16 @@ } /** + * Get the current progress percentage + * + * @return float + */ + public function getProgressPercentage() + { + return round($this->_session->processed / (count($this->_session->commands) + $this->_session->processed) * 100, 2); + } + + /** * Returns a button that can be clicked to restart the progress bar. * * @param mixed $arg_array MUtil_Ra::args() arguments to populate link with @@ -548,10 +558,8 @@ // error_log('Cur: ' . microtime(true) . ' report is '. (microtime(true) > $reportRun ? 'true' : 'false')); if (microtime(true) > $reportRun) { // Communicate progress - $percent = round($this->_session->processed / (count($this->_session->commands) + $this->_session->processed) * 100, 2); + $bar->update($this->getProgressPercentage(), end($this->_session->messages)); - $bar->update($percent, end($this->_session->messages)); - // INFO: When using PULL $bar->update() should exit the program, // but just let us make sure. if ($isPull) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-01-26 11:47:48
|
Revision: 424 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=424&view=rev Author: mennodekker Date: 2012-01-26 11:47:39 +0000 (Thu, 26 Jan 2012) Log Message: ----------- Fix for too many options present in UserDefinition config fields (organisation edit) BE CAREFUL: might cause trouble with options not explicitly allowed in the formbridge. use MUtil_Model::verbose = true to see what is stripped Modified Paths: -------------- trunk/library/classes/Gems/User/RadiusUserDefinition.php trunk/library/classes/MUtil/Model/FormBridge.php Modified: trunk/library/classes/Gems/User/RadiusUserDefinition.php =================================================================== --- trunk/library/classes/Gems/User/RadiusUserDefinition.php 2012-01-26 08:47:09 UTC (rev 423) +++ trunk/library/classes/Gems/User/RadiusUserDefinition.php 2012-01-26 11:47:39 UTC (rev 424) @@ -76,6 +76,7 @@ $bridge->getTab('access'); foreach ($model->getItemNames() as $name) { if ($label = $model->get($name, 'label')) { + //We supply all options from the model as the bridge doesn't know about this model $element = $bridge->add($name, $model->get($name)); } else { $element = $bridge->addHidden($name); Modified: trunk/library/classes/MUtil/Model/FormBridge.php =================================================================== --- trunk/library/classes/MUtil/Model/FormBridge.php 2012-01-26 08:47:09 UTC (rev 423) +++ trunk/library/classes/MUtil/Model/FormBridge.php 2012-01-26 11:47:39 UTC (rev 424) @@ -82,7 +82,7 @@ // First list html attributes, then Zend attributes, lastly own attributes private $_allowedOptions = array( - self::AUTO_OPTIONS => array('elementClass'), + self::AUTO_OPTIONS => array('elementClass', 'multiOptions'), self::CHECK_OPTIONS => array('checkedValue', 'uncheckedValue'), self::DATE_OPTIONS => array('dateFormat', 'storageFormat'), self::DISPLAY_OPTIONS => array('accesskey', 'autoInsertNotEmptyValidator', 'class', 'disabled', 'description', 'escape', 'label', 'onclick', 'readonly', 'required', 'tabindex'), @@ -90,7 +90,7 @@ self::FILE_OPTIONS => array('accept', 'count', 'destination', 'valueDisabled'), self::GROUP_OPTIONS => array('elements', 'legend', 'separator'), self::JQUERY_OPTIONS => array('jQueryParams'), - self::MULTI_OPTIONS => array('disable', 'multiOptions', 'onchange', 'separator', 'size'), + self::MULTI_OPTIONS => array('disable', 'multiOptions', 'onchange', 'separator', 'size', 'disableTranslator'), self::PASSWORD_OPTIONS => array('repeatLabel'), self::TAB_OPTIONS => array('value'), self::TEXT_OPTIONS => array('maxlength', 'minlength', 'onchange', 'onfocus', 'onselect', 'size'), @@ -159,17 +159,20 @@ return isset($stringlength) ? $stringlength : null; } + /** + * Returns the options from the allowedoptions array, using the supplied options first and trying + * to find the missing ones in the model. + * + * @param string $name + * @param array $options + * @param array $allowedOptionKeys_array + * @return array + */ private function _mergeOptions($name, array $options, $allowedOptionKeys_array) { - //If not explicitly set, use the form value for translatorDisabled, since we - //create the element outside the form scope and later add it - if (!isset($options['disableTranslator'])) { - $options['disableTranslator'] = $this->form->translatorIsDisabled(); - } - $args = func_get_args(); $allowedOptionsKeys = MUtil_Ra::args($args, 2); - + $allowedOptions = array(); foreach ($allowedOptionsKeys as $allowedOptionsKey) { if (is_array($allowedOptionsKey)) { @@ -183,6 +186,12 @@ } } + //If not explicitly set, use the form value for translatorDisabled, since we + //create the element outside the form scope and later add it + if (!isset($options['disableTranslator']) && array_search('disableTranslator', $allowedOptions) !== false) { + $options['disableTranslator'] = $this->form->translatorIsDisabled(); + } + // Move options to model. if (isset($options['validator'])) { $this->model->set($name, 'validators[]', $options['validator']); @@ -192,6 +201,16 @@ if ($allowedOptions) { // Remove options already filled. Using simple array addition // might trigger a lot of lazy calculations that are not needed. + + //First strip the options that are not allowed + if (MUtil_Model::$verbose) { + $strippedKeys = array_keys(array_diff_key($options, array_flip($allowedOptions))); + if (!empty($strippedKeys)) { + MUtil_Echo::r($strippedKeys, 'stripped from options for ' . $name); + } + } + $options = array_intersect_key($options, array_flip($allowedOptions)); + foreach ($allowedOptions as $key => $option) { if (array_key_exists($option, $options)) { unset($allowedOptions[$key]); @@ -201,7 +220,7 @@ if ($allowedOptions) { // MUtil_Echo::r($allowedOptions); $result = $this->model->get($name, $allowedOptions); - return $result + $options; + return (array) $result + (array) $options; } } @@ -224,8 +243,7 @@ $options = func_get_args(); $options = MUtil_Ra::pairs($options, 1); - $options = $this->_mergeOptions($name, $options, - self::AUTO_OPTIONS, self::CHECK_OPTIONS, self::DISPLAY_OPTIONS, self::GROUP_OPTIONS, self::MULTI_OPTIONS, self::TAB_OPTIONS, self::TEXT_OPTIONS, self::TEXTAREA_OPTIONS); + $options = $this->_mergeOptions($name, $options, self::AUTO_OPTIONS); if (isset($options['elementClass'])) { $method = 'add' . $options['elementClass']; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-01-26 13:45:53
|
Revision: 425 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=425&view=rev Author: mennodekker Date: 2012-01-26 13:45:44 +0000 (Thu, 26 Jan 2012) Log Message: ----------- Added missing option 'value' to the allowedoptions, fixing empty Html elements Added a description to the allowed ip ranges in groep edit Modified Paths: -------------- trunk/library/classes/Gems/Default/GroupAction.php trunk/library/classes/MUtil/Model/FormBridge.php Modified: trunk/library/classes/Gems/Default/GroupAction.php =================================================================== --- trunk/library/classes/Gems/Default/GroupAction.php 2012-01-26 11:47:39 UTC (rev 424) +++ trunk/library/classes/Gems/Default/GroupAction.php 2012-01-26 13:45:44 UTC (rev 425) @@ -93,7 +93,10 @@ $model->set('ggp_staff_members', 'label', $this->_('Staff'), 'multiOptions', $yesNo); $model->set('ggp_respondent_members', 'label', $this->_('Respondents'), 'multiOptions', $yesNo); - $model->set('ggp_allowed_ip_ranges', 'label', $this->_('Allowed IP Ranges')); + $model->set('ggp_allowed_ip_ranges', + 'label', $this->_('Allowed IP Ranges'), + 'description', $this->_('Separate with | example: 10.0.0.0-10.0.0.255 (subnet masks are not supported)') + ); Gems_Model::setChangeFieldsByPrefix($model, 'ggp'); Modified: trunk/library/classes/MUtil/Model/FormBridge.php =================================================================== --- trunk/library/classes/MUtil/Model/FormBridge.php 2012-01-26 11:47:39 UTC (rev 424) +++ trunk/library/classes/MUtil/Model/FormBridge.php 2012-01-26 13:45:44 UTC (rev 425) @@ -85,7 +85,7 @@ self::AUTO_OPTIONS => array('elementClass', 'multiOptions'), self::CHECK_OPTIONS => array('checkedValue', 'uncheckedValue'), self::DATE_OPTIONS => array('dateFormat', 'storageFormat'), - self::DISPLAY_OPTIONS => array('accesskey', 'autoInsertNotEmptyValidator', 'class', 'disabled', 'description', 'escape', 'label', 'onclick', 'readonly', 'required', 'tabindex'), + self::DISPLAY_OPTIONS => array('accesskey', 'autoInsertNotEmptyValidator', 'class', 'disabled', 'description', 'escape', 'label', 'onclick', 'readonly', 'required', 'tabindex', 'value'), self::EXHIBIT_OPTIONS => array('formatFunction'), self::FILE_OPTIONS => array('accept', 'count', 'destination', 'valueDisabled'), self::GROUP_OPTIONS => array('elements', 'legend', 'separator'), This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-02-15 15:03:41
|
Revision: 484 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=484&view=rev Author: matijsdejong Date: 2012-02-15 15:03:30 +0000 (Wed, 15 Feb 2012) Log Message: ----------- Versions updated Modified Paths: -------------- trunk/library/classes/Gems/Versions.php trunk/library/classes/MUtil/Version.php Modified: trunk/library/classes/Gems/Versions.php =================================================================== --- trunk/library/classes/Gems/Versions.php 2012-02-15 14:58:41 UTC (rev 483) +++ trunk/library/classes/Gems/Versions.php 2012-02-15 15:03:30 UTC (rev 484) @@ -43,12 +43,12 @@ { public final function getBuild() { - return 44; + return 45; } public final function getGemsVersion() { - return '1.5.1'; + return '1.5.2'; } public function getProjectVersion() Modified: trunk/library/classes/MUtil/Version.php =================================================================== --- trunk/library/classes/MUtil/Version.php 2012-02-15 14:58:41 UTC (rev 483) +++ trunk/library/classes/MUtil/Version.php 2012-02-15 15:03:30 UTC (rev 484) @@ -34,7 +34,7 @@ { const MAJOR = 1; const MINOR = 0; - const BUILD = 31; + const BUILD = 32; public static function get() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <gem...@li...> - 2012-02-16 14:34:28
|
Revision: 496 http://gemstracker.svn.sourceforge.net/gemstracker/?rev=496&view=rev Author: matijsdejong Date: 2012-02-16 14:34:19 +0000 (Thu, 16 Feb 2012) Log Message: ----------- Removed batched variables as we no longer use them (no longer using $updateTokens). Synchronize all sources now works Modified Paths: -------------- trunk/library/classes/Gems/Default/SourceAction.php trunk/library/classes/Gems/Tracker/Batch/SynchronizeSourcesBatch.php trunk/library/classes/Gems/Tracker/Source/LimeSurvey1m9Database.php trunk/library/classes/Gems/Tracker/Source/SourceAbstract.php trunk/library/classes/Gems/Tracker/Source/SourceInterface.php trunk/library/classes/Gems/Tracker/TrackerInterface.php trunk/library/classes/Gems/Tracker.php trunk/library/classes/MUtil/Batch/BatchAbstract.php Modified: trunk/library/classes/Gems/Default/SourceAction.php =================================================================== --- trunk/library/classes/Gems/Default/SourceAction.php 2012-02-16 13:45:27 UTC (rev 495) +++ trunk/library/classes/Gems/Default/SourceAction.php 2012-02-16 14:34:19 UTC (rev 496) @@ -253,7 +253,7 @@ { $sourceId = $this->getSourceId(); - $batch = $this->loader->getTracker()->synchronizeSourcesBatch($sourceId, $this->loader->getCurrentUser()->getUserId(), false); + $batch = $this->loader->getTracker()->synchronizeSourcesBatch($sourceId, $this->loader->getCurrentUser()->getUserId()); if ($batch->run($this->getRequest())) { exit; @@ -275,45 +275,39 @@ } } } - /* - $source = $this->getSourceById(); - - if ($messages = $source->synchronizeSurveys($this->loader->getCurrentUser()->getUserId())) { - $this->addMessage($messages); - } else { - $this->addMessage($this->_('No changes.')); - } - - $this->afterSaveRoute($this->getRequest()); - // */ } + /** + * Synchronize survey status for the surveys in all sources + */ public function synchronizeAllAction() { - $model = $this->getModel(); - $data = $model->load(null, $this->sortKey); + //* + $batch = $this->loader->getTracker()->synchronizeSourcesBatch(null, $this->loader->getCurrentUser()->getUserId()); - if ($this->_getParam('confirmed')) { - foreach ($data as $row) { - $source = $this->getSourceById($row['gso_id_source']); + if ($batch->run($this->getRequest())) { + exit; + } else { + $this->html->h3($this->_('Synchronize all sources.')); - $this->addMessage(sprintf($this->_('Synchronization of source %s:'), $row['gso_source_name'])); - if ($messages = $source->synchronizeSurveys($this->loader->getCurrentUser()->getUserId())) { - $this->addMessage($messages); + if ($batch->isFinished()) { + $this->addMessage($batch->getMessages(true)); + $this->html->pInfo($batch->getRestartButton($this->_('Prepare recheck'), array('class' => 'actionlink'))); + } else { + if ($batch->count()) { + // Batch is loaded by Tracker + $this->html->pInfo($batch->getStartButton(sprintf($this->plural('Check %s source', 'Check %s sources', $batch->getSourceCounter()), $batch->getSourceCounter()))); + $this->html->append($batch->getPanel($this->view, $batch->getProgressPercentage() . '%')); } else { - $this->addMessage($this->_('No changes.')); + $this->html->pInfo($this->_('No sources to check.')); } } + } // */ - $this->afterSaveRoute($this->getRequest()); - } - - $this->html->h3($this->_('Synchronize all sources of surveys')); - $this->html->pInfo($this->_('Synchronization will update the status of all surveys imported into this project to the status at the sources.')); - /* $batch = new MUtil_Batch_WaitBatch(); - // $batch->setMethodPush(5); + $batch->setMethodPush(5); + $batch->progressParameterName = 'waitprogress'; // $batch->autoStart = true; // $batch->minimalStepDurationMs = 2000; if ($batch->run($this->getRequest())) { @@ -325,7 +319,7 @@ } else { // Populate the batch (from scratch). $batch->reset(); - if (! true) { + if (true) { $batch->addWaitsMs(400, 20); $batch->addWaits(2, 1, 'Har har'); $batch->addWaitsMs(20, 50); @@ -344,18 +338,6 @@ } } // */ - if ($data) { - $rdata = MUtil_Lazy::repeat($data); - $table = $this->html->table($rdata, array('class' => 'browser')); - $table->th($this->getTopicTitle()); - $table->td()->a(array('action' => 'show', MUtil_Model::REQUEST_ID => $rdata->gso_id_source), $rdata->gso_source_name); - - $this->html->h4($this->_('Are you sure you want to synchronize all survey sources?')); - $this->html->actionLink(array('confirmed' => 1), $this->_('Yes')); - $this->html->actionLink(array('action' => 'index'), $this->_('No')); - } else { - $this->html->pInfo(sprintf($this->_('No %s found'), $this->getTopic(0))); - } $this->html->actionLink(array('action' => 'index'), $this->_('Cancel')); } } Modified: trunk/library/classes/Gems/Tracker/Batch/SynchronizeSourcesBatch.php =================================================================== --- trunk/library/classes/Gems/Tracker/Batch/SynchronizeSourcesBatch.php 2012-02-16 13:45:27 UTC (rev 495) +++ trunk/library/classes/Gems/Tracker/Batch/SynchronizeSourcesBatch.php 2012-02-16 14:34:19 UTC (rev 496) @@ -72,8 +72,9 @@ public function addSource($sourceData, $userId) { $this->_currentSource = $this->tracker->getSource($sourceData); - $this->_currentSource->addSynchronizeSurveyCommands($this, $userId, $this->getTokenUpdate()); + $this->_currentSource->addSynchronizeSurveyCommands($this, $userId); $this->_currentSource = null; + $this->addToSourceCounter(); } /** @@ -92,6 +93,17 @@ } /** + * Add one to the number of sources checked + * + * @param int $add + * @return int + */ + public function addToSourceCounter($add = 1) + { + return $this->addToCounter('sources', $add); + } + + /** * Add one to the number of surveys checked * * @param int $add @@ -113,46 +125,44 @@ */ public function getMessages($reset = false) { - $scounter = $this->getSurveyCounter(); + $cSources = $this->getSourceCounter(); + $cSurveys = $this->getSurveyCounter(); + $messages = parent::getMessages($reset); if (! $messages) { $messages[] = $this->translate->_('No surveys were changed.'); } - array_unshift($messages, sprintf($this->translate->_('%d surveys checked.'), $scounter)); + array_unshift($messages, sprintf($this->translate->_('%d surveys checked.'), $cSurveys)); + if ($cSources > 1) { + array_unshift($messages, sprintf($this->translate->_('%d sources checked.'), $cSources)); + } return $messages; } + /** - * Get the number of surveys checked + * Get the number of sources checked * * @return int */ - public function getSurveyCounter() + public function getSourceCounter() { - return $this->getCounter('surveys'); + return $this->getCounter('sources'); } /** - * Is tokenUpdate on or off. + * Get the number of surveys checked * - * @return boolean + * @return int */ - public function getTokenUpdate() + public function getSurveyCounter() { - return $this->getVar('tokenUpdate'); + return $this->getCounter('surveys'); } /** - * Set tokenUpdate on or off. - */ - public function setTokenUpdate($value = true) - { - $this->setVar('tokenUpdate', $value); - } - - /** * The basic steps * * @param int $sourceId Modified: trunk/library/classes/Gems/Tracker/Source/LimeSurvey1m9Database.php =================================================================== --- trunk/library/classes/Gems/Tracker/Source/LimeSurvey1m9Database.php 2012-02-16 13:45:27 UTC (rev 495) +++ trunk/library/classes/Gems/Tracker/Source/LimeSurvey1m9Database.php 2012-02-16 14:34:19 UTC (rev 496) @@ -300,9 +300,8 @@ * * @param Gems_Tracker_Batch_SynchronizeSourcesBatch $batch * @param int $userId Id of the user who takes the action (for logging) - * @param bool $updateTokens Wether the tokens should be updated or not, default is true */ - public function addSynchronizeSurveyCommands(Gems_Tracker_Batch_SynchronizeSourcesBatch $batch, $userId, $updateTokens = true) + public function addSynchronizeSurveyCommands(Gems_Tracker_Batch_SynchronizeSourcesBatch $batch, $userId) { // Surveys in LS $lsDb = $this->getSourceDatabase(); @@ -317,15 +316,15 @@ foreach ($gemsSurveys as $surveyId => $sourceSurveyId) { if (isset($lsSurveys[$sourceSurveyId])) { - $batch->addSourceFunction('checkSurvey', $sourceSurveyId, $surveyId, $userId, $updateTokens); + $batch->addSourceFunction('checkSurvey', $sourceSurveyId, $surveyId, $userId); } else { - $batch->addSourceFunction('checkSurvey', null, $surveyId, $userId, $updateTokens); + $batch->addSourceFunction('checkSurvey', null, $surveyId, $userId); } $batch->addToSurveyCounter(); } foreach (array_diff($lsSurveys, $gemsSurveys) as $sourceSurveyId) { - $batch->addSourceFunction('checkSurvey', $sourceSurveyId, null, $userId, $updateTokens); + $batch->addSourceFunction('checkSurvey', $sourceSurveyId, null, $userId); $batch->addToSurveyCounter(); } } @@ -362,9 +361,8 @@ * @param int $sourceSurveyId * @param int $surveyId * @param int $userId - * @param boolean $updateTokens */ - public function checkSurvey($sourceSurveyId, $surveyId, $userId, $updateTokens) + public function checkSurvey($sourceSurveyId, $surveyId, $userId) { $messages = array(); $survey = $this->tracker->getSurvey($surveyId); Modified: trunk/library/classes/Gems/Tracker/Source/SourceAbstract.php =================================================================== --- trunk/library/classes/Gems/Tracker/Source/SourceAbstract.php 2012-02-16 13:45:27 UTC (rev 495) +++ trunk/library/classes/Gems/Tracker/Source/SourceAbstract.php 2012-02-16 14:34:19 UTC (rev 496) @@ -227,11 +227,13 @@ * * @param Gems_Tracker_Batch_SynchronizeSourcesBatch $batch * @param int $userId Id of the user who takes the action (for logging) - * @param bool $updateTokens Wether the tokens should be updated or not, default is true */ - public function addSynchronizeSurveyCommands(Gems_Tracker_Batch_SynchronizeSourcesBatch $batch, $userId, $updateTokens = true) + public function addSynchronizeSurveyCommands(Gems_Tracker_Batch_SynchronizeSourcesBatch $batch, $userId) { - // Do nothing is default + // Do nothing or add the old method is the default + if (method_exists($this, 'synchronizeSurveys')) { + $batch->addSourceFunction('synchronizeSurveys', $userId); + } } /** Modified: trunk/library/classes/Gems/Tracker/Source/SourceInterface.php =================================================================== --- trunk/library/classes/Gems/Tracker/Source/SourceInterface.php 2012-02-16 13:45:27 UTC (rev 495) +++ trunk/library/classes/Gems/Tracker/Source/SourceInterface.php 2012-02-16 14:34:19 UTC (rev 496) @@ -59,9 +59,8 @@ * * @param Gems_Tracker_Batch_SynchronizeSourcesBatch $batch * @param int $userId Id of the user who takes the action (for logging) - * @param bool $updateTokens Wether the tokens should be updated or not, default is true */ - public function addSynchronizeSurveyCommands(Gems_Tracker_Batch_SynchronizeSourcesBatch $batch, $userId, $updateTokens = true); + public function addSynchronizeSurveyCommands(Gems_Tracker_Batch_SynchronizeSourcesBatch $batch, $userId); /** * Inserts the token in the source (if needed) and sets those attributes the source wants to set. Modified: trunk/library/classes/Gems/Tracker/TrackerInterface.php =================================================================== --- trunk/library/classes/Gems/Tracker/TrackerInterface.php 2012-02-16 13:45:27 UTC (rev 495) +++ trunk/library/classes/Gems/Tracker/TrackerInterface.php 2012-02-16 14:34:19 UTC (rev 496) @@ -285,11 +285,10 @@ * * @param int $sourceId A source identifier * @param int $userId Id of the user who takes the action (for logging) - * @param boolean $updateTokens When true each individual token must be synchronized as well * @return Gems_Tracker_Batch_SynchronizeSourcesBatch A batch to process the synchronization */ - public function synchronizeSourcesBatch($sourceId = null, $userId = null, $updateTokens = false); - + public function synchronizeSourcesBatch($sourceId = null, $userId = null); + /** * Recalculates all token dates, timing and results * and outputs text messages. Modified: trunk/library/classes/Gems/Tracker.php =================================================================== --- trunk/library/classes/Gems/Tracker.php 2012-02-16 13:45:27 UTC (rev 495) +++ trunk/library/classes/Gems/Tracker.php 2012-02-16 14:34:19 UTC (rev 496) @@ -862,19 +862,13 @@ * * @param int $sourceId A source identifier * @param int $userId Id of the user who takes the action (for logging) - * @param boolean $updateTokens When true each individual token must be synchronized as well * @return Gems_Tracker_Batch_SynchronizeSourcesBatch A batch to process the synchronization */ - public function synchronizeSourcesBatch($sourceId = null, $userId = null, $updateTokens = false) + public function synchronizeSourcesBatch($sourceId = null, $userId = null) { $batch_id = 'source_synch' . ($sourceId ? '_' . $sourceId : ''); $batch = $this->_loadClass('Batch_SynchronizeSourcesBatch', true, array($batch_id)); - if ($updateTokens != $batch->getTokenUpdate()) { - $batch->reset(); - } - $batch->setTokenUpdate($updateTokens); - if (! $batch->isLoaded()) { if ($sourceId) { $sources = array($sourceId); Modified: trunk/library/classes/MUtil/Batch/BatchAbstract.php =================================================================== --- trunk/library/classes/MUtil/Batch/BatchAbstract.php 2012-02-16 13:45:27 UTC (rev 495) +++ trunk/library/classes/MUtil/Batch/BatchAbstract.php 2012-02-16 14:34:19 UTC (rev 496) @@ -203,7 +203,7 @@ $command['parameters'] = $params; // MUtil_Echo::track($command); - + return $command; } @@ -477,30 +477,6 @@ } /** - * Batch duration variable storage for the process - * - * @param string $name Name - * @return mixed The scalar value, if any - */ - protected function getVar($name) - { - if (isset($this->_session->vars[$name])) { - return $this->_session->vars[$name]; - } - } - - /** - * Batch duration variable storage for the process - * - * @param string $name Name - * @return boolean - */ - protected function hasVar($name) - { - return array_key_exists($name, $this->_session->vars); - } - - /** * Return true after commands all have been ran. * * @return boolean @@ -553,7 +529,6 @@ $this->_session->finished = false; $this->_session->messages = array(); $this->_session->processed = 0; - $this->_session->vars = array(); return $this; } @@ -771,21 +746,6 @@ } /** - * Batch duration variable storage for the process - * - * @param string $name Name - * @param mixed $value Scalar value - */ - protected function setVar($name, $value) - { - if (! MUtil_Ra::isScalar($value)) { - throw new MUtil_Batch_BatchException("Non scalar batch value named '$name'."); - } - - $this->_session->vars[$name] = $value; - } - - /** * Progress a single step on the command stack * * @return boolean @@ -810,14 +770,4 @@ return false; } } - - /** - * Batch duration variable storage for the process - * - * @param string $name Name - */ - protected function unsetVar($name) - { - unset($this->_session->vars[$name]); - } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |