Example #1
0
 /**
  * @param string $entityType
  * @param object $entity
  * @param array $arguments
  * @return object
  * @throws \Exception
  */
 public function execute($entityType, $entity, $arguments = [])
 {
     $entityMetadata = $this->metadataPool->getMetadata($entityType);
     $linkField = $entityMetadata->getLinkField();
     $connection = $entityMetadata->getEntityConnection();
     $oldStores = $this->resourcePage->lookupStoreIds((int) $entity->getId());
     $newStores = (array) $entity->getStores();
     if (empty($newStores)) {
         $newStores = (array) $entity->getStoreId();
     }
     $table = $this->resourcePage->getTable('cms_page_store');
     $delete = array_diff($oldStores, $newStores);
     if ($delete) {
         $where = [$linkField . ' = ?' => (int) $entity->getData($linkField), 'store_id IN (?)' => $delete];
         $connection->delete($table, $where);
     }
     $insert = array_diff($newStores, $oldStores);
     if ($insert) {
         $data = [];
         foreach ($insert as $storeId) {
             $data[] = [$linkField => (int) $entity->getData($linkField), 'store_id' => (int) $storeId];
         }
         $connection->insertMultiple($table, $data);
     }
     return $entity;
 }
Example #2
0
 /**
  * Setup an Event
  *
  * Phalcon event to make sure client sends a valid message
  * @return FALSE|void
  */
 public function handleEvent()
 {
     $this->attach('micro', function ($event, $app) {
         if ($event->getType() == 'beforeExecuteRoute') {
             $data = $this->msg->getData();
             ksort($data);
             // Need to refactor this
             $message = $this->msg->getTime() . $this->msg->getId() . implode($data);
             $serverHash = hash_hmac('sha256', $message, $this->privateKey);
             $clientHash = $this->msg->getHash();
             $allowed = $clientHash === $serverHash ?: false;
             $method = strtolower($app->router->getMatchedRoute()->getHttpMethods());
             $unAuthenticated = $app->getUnauthenticated();
             if (isset($unAuthenticated[$method])) {
                 $unAuthenticated = array_flip($unAuthenticated[$method]);
                 if (isset($unAuthenticated[$app->router->getMatchedRoute()->getPattern()])) {
                     $allowed = true;
                 }
             }
             if (!$allowed) {
                 $app->response->setStatusCode(401, "Unauthorized");
                 $app->response->setContent("Access denied");
                 $app->response->send();
                 return false;
             }
         }
     });
 }
 /**
  * Test the ipc getData method
  */
 function test_getData()
 {
     $id = $this->last_insert_id;
     $type = 'text/x-vcard';
     //$type = 'text/xml';
     $version = '3.0';
     return $this->ipc->getData($id, $type, $version);
 }
 /**
  * Returns status changer name
  * @param object $entry
  * @return
  */
 public function getChangerName($entry)
 {
     try {
         if ($entry->getData('custom_field_4')) {
             // Changed by customer
             $ticketId = $entry->getData('custom_field_1');
             return '[C] ' . Mage::getModel('helpdeskultimate/ticket')->load($ticketId)->getCustomer()->getName();
         } else {
             $departmentId = $entry->getData('custom_field_3');
             return '[D] ' . Mage::getModel('helpdeskultimate/department')->load($departmentId)->getName();
         }
     } catch (Exception $e) {
         return $this->__('Unknown department/customer');
     }
 }
 /**
  * Fetches statistics array for $phase form the output object.
  *
  * @param int $phase
  * @return void
  */
 protected function getStatArray($phase)
 {
     if ($this->output === null) {
         return;
     }
     return $this->output->getData($phase);
 }
Example #6
0
 /**
  * @covers  Molajo\Resource\Proxy::setNamespace
  * @covers  Molajo\Resource\Proxy::exists
  * @covers  Molajo\Resource\Proxy::get
  * @covers  Molajo\Resource\Proxy::getCollection
  * @covers  Molajo\Resource\Proxy\Scheme::__construct
  * @covers  Molajo\Resource\Proxy\Scheme::setScheme
  * @covers  Molajo\Resource\Proxy\Scheme::getScheme
  * @covers  Molajo\Resource\Proxy\Scheme::setAdapterNamespaces
  * @covers  Molajo\Resource\Proxy\Scheme::saveNamespaceArray
  * @covers  Molajo\Resource\Proxy\Scheme::locateScheme
  * @covers  Molajo\Resource\Proxy\Scheme::getUriScheme
  * @covers  Molajo\Resource\Proxy\Scheme::removeUriScheme
  *
  * @return  $this
  * @since   1.0.0
  */
 public function testSetNamespaces()
 {
     $this->setNs();
     $expected_ns = array();
     $row = new stdClass();
     $row->namespace_prefix = 'Molajo\\A\\';
     $row->base_directory = 'Source/A/';
     $row->prepend = true;
     $expected_ns[] = $row;
     $row = new stdClass();
     $row->namespace_prefix = 'Molajo\\B\\';
     $row->base_directory = 'Source/B/';
     $row->prepend = true;
     $expected_ns[] = $row;
     $row = new stdClass();
     $row->namespace_prefix = 'Molajo\\C\\';
     $row->base_directory = 'Source/C/';
     $row->prepend = true;
     $expected_ns[] = $row;
     $row = new stdClass();
     $row->namespace_prefix = 'Molajo\\Plugins\\';
     $row->base_directory = 'Source/Plugins/';
     $row->prepend = true;
     $expected_ns[] = $row;
     $actual_ns = $this->proxy_instance->getData('namespace_array');
     $this->assertEquals($expected_ns, $actual_ns);
     return $this;
 }
Example #7
0
 /**
  * @param object $command Pheanstalk_Command
  * @return object Pheanstalk_Response
  * @throws Pheanstalk_Exception_ClientException
  */
 public function dispatchCommand($command)
 {
     $socket = $this->_getSocket();
     $to_send = $command->getCommandLine() . self::CRLF;
     if ($command->hasData()) {
         $to_send .= $command->getData() . self::CRLF;
     }
     $socket->write($to_send);
     $responseLine = $socket->getLine();
     $responseName = preg_replace('#^(\\S+).*$#s', '$1', $responseLine);
     if (isset(self::$_errorResponses[$responseName])) {
         $exception = sprintf('Pheanstalk_Exception_Server%sException', self::$_errorResponses[$responseName]);
         throw new $exception(sprintf("%s in response to '%s'", $responseName, $command));
     }
     if (in_array($responseName, self::$_dataResponses)) {
         $dataLength = preg_replace('#^.*\\b(\\d+)$#', '$1', $responseLine);
         $data = $socket->read($dataLength);
         $crlf = $socket->read(self::CRLF_LENGTH);
         if ($crlf !== self::CRLF) {
             throw new Pheanstalk_Exception_ClientException(sprintf('Expected %u bytes of CRLF after %u bytes of data', self::CRLF_LENGTH, $dataLength));
         }
     } else {
         $data = null;
     }
     return $command->getResponseParser()->parseResponse($responseLine, $data);
 }
Example #8
0
 /**
  * @covers Cart\Api::getData
  */
 public function testGetData()
 {
     $result = (array) json_decode($this->object->getData());
     /** Check success answer */
     $this->assertTrue($result['success']);
     $this->assertFalse($result['errors']);
     $this->assertCount(2, $result['data']);
     $this->object->removeAll();
 }
Example #9
0
 /**
  * Save data to database.
  *
  * @return object Entity
  */
 public function save()
 {
     foreach ($this->object->getData() as $field => $value) {
         if (array_key_exists($field, $this->data)) {
             $this->object->set($field, $this->data[$field]);
         }
     }
     $this->object->save();
     return $this->object;
 }
Example #10
0
 /**
  * Attach a handler to the session validator chain
  * 
  * @param  string $topic 
  * @param  string|object|Closure $context 
  * @param  null|string $handler 
  * @return Zend\Stdlib\SignalHandler
  */
 public function connect($topic, $context, $handler = null)
 {
     if ($context instanceof Validator) {
         $data = $context->getData();
         $name = $context->getName();
         $this->getStorage()->setMetadata('_VALID', array($name => $data));
     }
     $handle = parent::connect($topic, $context, $handler);
     return $handle;
 }
Example #11
0
 /**
  * Get the model state properties
  *
  * This function overloads the KObject::get() function and only acts on state
  * properties
  *
  * If no property name is given then the function will return an associative
  * array of all properties.
  *
  * If the property does not exist and a  default value is specified this is
  * returned, otherwise the function return NULL.
  *
  * @param   string  The name of the property
  * @param   mixed   The default value
  * @return  mixed   The value of the property, an associative array or NULL
  */
 public function get($property = null, $default = null)
 {
     $result = $default;
     if (is_null($property)) {
         $result = $this->_state->getData();
     } else {
         if (isset($this->_state->{$property})) {
             $result = $this->_state->{$property};
         }
     }
     return $result;
 }
 /**
  * @covers  Molajo\Resource\Proxy::setNamespace
  * @covers  Molajo\Resource\Proxy::exists
  * @covers  Molajo\Resource\Proxy::get
  * @covers  Molajo\Resource\Proxy::getCollection
  * @covers  Molajo\Resource\Proxy\Scheme::__construct
  * @covers  Molajo\Resource\Proxy\Scheme::setScheme
  * @covers  Molajo\Resource\Proxy\Scheme::getScheme
  * @covers  Molajo\Resource\Proxy\Scheme::setAdapterNamespaces
  * @covers  Molajo\Resource\Proxy\Scheme::saveNamespaceArray
  * @covers  Molajo\Resource\Proxy\Scheme::locateScheme
  * @covers  Molajo\Resource\Proxy\Scheme::getUriScheme
  * @covers  Molajo\Resource\Proxy\Scheme::removeUriScheme
  * @covers  Molajo\Resource\Adapter\NamespaceHandler::setNamespace
  * @covers  Molajo\Resource\Adapter\NamespaceHandler::exists
  * @covers  Molajo\Resource\Adapter\NamespaceHandler::get
  * @covers  Molajo\Resource\Adapter\NamespaceHandler::getCollection
  * @covers  Molajo\Resource\Adapter\NamespaceHandler::locateResourceNamespace
  * @covers  Molajo\Resource\Adapter\SetNamespace::setNamespaceExists
  * @covers  Molajo\Resource\Adapter\SetNamespace::appendNamespace
  * @covers  Molajo\Resource\Adapter\SetNamespace::prependNamespace
  * @covers  Molajo\Resource\Adapter\HandleNamespacePrefixes::searchNamespacePrefixes
  * @covers  Molajo\Resource\Adapter\HandleNamespacePrefixes::searchNamespacePrefix
  * @covers  Molajo\Resource\Adapter\HandleNamespacePrefixes::searchNamespacePrefixDirectory
  * @covers  Molajo\Resource\Adapter\HandleNamespacePrefixes::searchNamespacePrepareNamespacePath
  * @covers  Molajo\Resource\Adapter\HandleNamespacePrefixes::searchNamespaceFilename
  * @covers  Molajo\Resource\Adapter\HandleNamespacePrefixes::searchNamespacePrefixFileExtensions
  * @covers  Molajo\Resource\Adapter\HandleResourceMap::searchResourceMap
  * @covers  Molajo\Resource\Adapter\HandleResourceMap::searchResourceMapInstance
  * @covers  Molajo\Resource\Adapter\HandleResourceMap::setResourceMapPaths
  * @covers  Molajo\Resource\Adapter\HandleResourceMap::searchResourceMapPaths
  * @covers  Molajo\Resource\Adapter\HandleResourceMap::searchResourceMapFileExtensions
  * @covers  Molajo\Resource\Adapter\Base::__construct
  * @covers  Molajo\Resource\Adapter\Base::initialiseCacheVariables
  * @covers  Molajo\Resource\Adapter\Base::setScheme
  * @covers  Molajo\Resource\Adapter\Base::setResourceNamespace
  * @covers  Molajo\Resource\Adapter\Cache::getConfigurationCache
  * @covers  Molajo\Resource\Adapter\Cache::setConfigurationCache
  * @covers  Molajo\Resource\Adapter\Cache::deleteConfigurationCache
  * @covers  Molajo\Resource\Adapter\Cache::useConfigurationCache
  * @covers  Molajo\Resource\Adapter\Cache::getCache
  * @covers  Molajo\Resource\Adapter\Cache::setCache
  * @covers  Molajo\Resource\Adapter\Cache::deleteCache
  * @covers  Molajo\Resource\Adapter\Cache::clearCache
  *
  * @return  $this
  * @since   1.0.0
  */
 public function testSetNSAfter()
 {
     $this->setAdapter();
     $this->setNs();
     $expected_ns = array();
     $expected_ns['Molajo\\A\\'] = array('Source/A/');
     $expected_ns['Molajo\\B\\'] = array('Source/B/');
     $expected_ns['Molajo\\C\\'] = array('Source/C/');
     $expected_ns['Molajo\\Plugins\\'] = array('Source/Plugins/');
     $this->assertEquals($expected_ns, $this->adapter_instance->getData('namespace_prefixes'));
     return $this;
 }
 /**
  * Setup an Event
  *
  * Phalcon event to make sure client sends a valid message
  * @return FALSE|void
  */
 public function handleEvent()
 {
     $this->attach('micro', function ($event, $app) {
         if ($event->getType() == 'beforeExecuteRoute') {
             $iRequestTime = $this->_msg->getTime();
             $msgData = is_array($this->_msg->getData()) ? http_build_query($this->_msg->getData(), '', '&') : $this->_msg->getData();
             $data = $iRequestTime . $this->_msg->getId() . $msgData;
             $serverHash = hash_hmac('sha256', $data, $this->_privateKey);
             $clientHash = $this->_msg->getHash();
             // security checks, deny access by default
             $allowed = false;
             if ($clientHash === $serverHash) {
                 // 1st security level - check hashes
                 if (time() - $iRequestTime <= $this->_maxRequestDelay) {
                     // 2nd security level - ensure request time hasn't expired
                     $allowed = true;
                     // gain access, everyting ok
                 }
             }
             if (!$allowed) {
                 // already authorized skip this part
                 // last try - login without auth for open calls
                 $method = strtolower($app->router->getMatchedRoute()->getHttpMethods());
                 $unAuthenticated = $app->getUnauthenticated();
                 if (isset($unAuthenticated[$method])) {
                     $unAuthenticated = array_flip($unAuthenticated[$method]);
                     if (isset($unAuthenticated[$app->router->getMatchedRoute()->getPattern()])) {
                         return true;
                         // gain access to open call
                     }
                 }
                 // still not authorized, get out of here
                 $app->response->setStatusCode(401, "Unauthorized");
                 $app->response->setContent("Access denied");
                 $app->response->send();
                 return false;
             }
         }
     });
 }
Example #14
0
 /**
  * addPa2ImageToTemplate function.
  *
  * @access public
  * @param  object $objTemplate
  * @param  array  $arrMergeData (default: array())
  * @return object
  */
 public function addPa2ImageToTemplate($objTemplate, $arrMergeData = array())
 {
     if (isset($this->uuid) && is_array($arrMergeData)) {
         $objFile = $this->getPa2Image();
         if ($objFile !== null && is_file(TL_ROOT . '/' . $objFile->path)) {
             $arrData = $objTemplate->getData();
             $arrData['singleSRC'] = $objFile->path;
             if (count($arrMergeData) > 0) {
                 $arrData = array_merge($arrData, $arrMergeData);
             }
             $this->addImageToTemplate($objTemplate, $arrData);
         }
     }
     return $objTemplate;
 }
 public function analyzePage()
 {
     $data = $this->dataProvider->getData(true);
     foreach ($data as $rowBean) {
         assert('$rowBean->id != null');
         $columnMessages = array();
         $shouldSkipRow = false;
         foreach ($this->sanitizableColumnNames as $columnName) {
             $attributeIndexOrDerivedType = $this->mappingData[$columnName]['attributeIndexOrDerivedType'];
             $penultimateModelClassName = ImportUtil::getPenultimateModelClassNameByImportRules($this->importRules);
             $attributeImportRules = AttributeImportRulesFactory::makeByImportRulesTypeAndAttributeIndexOrDerivedType($this->importRules->getType(), $attributeIndexOrDerivedType, $penultimateModelClassName);
             $modelClassName = $attributeImportRules->getModelClassName();
             $attributeName = static::resolveAttributeNameByRules($attributeImportRules);
             if (null != ($attributeValueSanitizerUtilTypes = $attributeImportRules->getSanitizerUtilTypesInProcessingOrder())) {
                 assert('is_array($attributeValueSanitizerUtilTypes)');
                 foreach ($attributeValueSanitizerUtilTypes as $attributeValueSanitizerUtilType) {
                     $sanitizer = ImportSanitizerUtilFactory::make($attributeValueSanitizerUtilType, $modelClassName, $attributeName, $columnName, $this->mappingData[$columnName], null, $penultimateModelClassName, $attributeIndexOrDerivedType);
                     $sanitizer->analyzeByRow($rowBean);
                     if ($sanitizer->getShouldSkipRow()) {
                         $shouldSkipRow = true;
                     }
                     foreach ($sanitizer->getAnalysisMessages() as $message) {
                         $columnMessages[$columnName][] = $message;
                     }
                     $classToEvaluate = new ReflectionClass($sanitizer);
                     if ($classToEvaluate->implementsInterface('ImportSanitizerHasCustomFieldValuesInterface')) {
                         $missingCustomFieldValues = $sanitizer->getMissingCustomFieldValues();
                         $this->getCustomFieldsInstructionData()->addMissingValuesByColumnName($missingCustomFieldValues, $columnName);
                     }
                 }
             }
         }
         if (!empty($columnMessages)) {
             $rowBean->serializedAnalysisMessages = serialize($columnMessages);
             if ($shouldSkipRow) {
                 $rowBean->analysisStatus = static::STATUS_SKIP;
             } else {
                 $rowBean->analysisStatus = static::STATUS_WARN;
             }
         } else {
             $rowBean->serializedAnalysisMessages = null;
             $rowBean->analysisStatus = static::STATUS_CLEAN;
         }
         ZurmoRedBean::store($rowBean);
     }
 }
Example #16
0
 /**
  * Get address data by address object
  * @param object $address
  * @return Varien_Object
  */
 public function getAddressData($address)
 {
     if (!$address) {
         return array();
     }
     $data = $address->getData();
     foreach ($data as $key => $value) {
         if (is_object($value)) {
             unset($data[$key]);
         }
     }
     $data['country_name'] = Mage::app()->getLocale()->getCountryTranslation($data['country_id']);
     $data['formated'] = $address->getFormated(true);
     $data = new Varien_Object($data);
     Mage::dispatchEvent('ves_pdfpro_data_prepare_after', array('source' => $data, 'model' => $address, 'type' => 'address'));
     return $data;
 }
 /**
  * Validates a phone number.
  *
  * @param  string $attribute
  * @param  mixed  $value
  * @param  array  $parameters
  * @param  object $validator
  * @return bool
  * @throws \Propaganistas\LaravelPhone\Exceptions\InvalidParameterException
  * @throws \Propaganistas\LaravelPhone\Exceptions\NoValidCountryFoundException
  */
 public function validatePhone($attribute, $value, array $parameters, $validator)
 {
     $this->data = array_dot($validator->getData());
     $this->assignParameters($parameters);
     $this->checkCountries($attribute);
     // If autodetecting, let's first try without a country.
     // Otherwise use provided countries as default.
     if ($this->autodetect || $this->lenient && empty($this->countries)) {
         array_unshift($this->countries, null);
     }
     foreach ($this->countries as $country) {
         if ($this->isValidNumber($value, $country)) {
             return true;
         }
     }
     // All specified country validations have failed.
     return false;
 }
 /**
  * @param object $object
  * @param string $field
  *
  * @return string
  */
 public function getStoreViewValue($object, $field)
 {
     $storeId = $object->getStoreId();
     if ($storeId === null) {
         $storeId = Mage::app()->getStore()->getId();
     }
     $serializedValue = $object->getData($field);
     $arr = $this->unserialize($serializedValue);
     $defaultValue = null;
     if (isset($arr[0])) {
         $defaultValue = $arr[0];
     }
     if (isset($arr[$storeId])) {
         $localizedValue = $arr[$storeId];
     } else {
         $localizedValue = $defaultValue;
     }
     return $localizedValue;
 }
Example #19
0
/**
 * Update last modified field on related entity when a comment is added
 * @global object $adb
 * @global object $current_user
 * @param object $entity 
 * @author Pablo Veintimilla <*****@*****.**>
 */
function UpdateLastModified($entity)
{
    global $adb, $current_user;
    $data = $entity->getData();
    $relatedTo = explode('x', $data['related_to']);
    $relatedToId = $relatedTo[1];
    $relatedToModule = cf_getModuleName($relatedTo[0]);
    if (!$relatedToModule) {
        return false;
    }
    //Update last modification
    $today_now = date('y-m-d h:i:s');
    $today_now = getvaliddbinsertdatetimevalue($today_now);
    $entityUpdate = crmentity::getinstance($relatedToModule);
    $entityUpdate->retrieve_entity_info($relatedToId, $relatedToModule);
    $entityUpdate->column_fields["modifiedtime"] = $today_now;
    $entityUpdate->id = $relatedToId;
    $entityUpdate->mode = "edit";
    $entityUpdate->save($relatedToModule);
    //Update tracker
    $id = $adb->getUniqueId('vtiger_modtracker_basic');
    $adb->pquery('INSERT INTO vtiger_modtracker_basic(id, crmid, module, whodid, changedon, status)
                  VALUES(?,?,?,?,?,?)', array($id, $relatedToId, $relatedToModule, $current_user->id, date('Y-m-d H:i:s', time()), ModTracker::$UPDATED));
}
Example #20
0
 /**
  * Construct an entity object
  *
  * @param ClassMetadata $class
  * @param object $document
  */
 public function hydrateEntity(ClassMetadata $class, $document)
 {
     // TODO: add support for different result set types from different clients
     // perhaps by wrapping documents in a layer of abstraction
     $data = $document->getData();
     $fields = array_merge($document->hasFields() ? $document->getFields() : array(), array('_version' => $document->getVersion()));
     foreach ($fields as $name => $value) {
         if (isset($class->parameters[$name])) {
             $data[$name] = $value;
         } else {
             foreach ($class->parameters as $param => $mapping) {
                 if ($mapping->name == $name) {
                     $data[$param] = $value;
                     break;
                 }
             }
         }
     }
     $data[$class->getIdentifier()] = $document->getId();
     if (method_exists($document, 'getScore')) {
         $data['score'] = $document->getScore();
     }
     $entity = $this->sm->getSerializer()->deserialize($class->className, json_encode($data));
     if ($this->evm->hasListeners(Events::postLoad)) {
         $this->evm->dispatchEvent(Events::postLoad, new Event\LifecycleEventArgs($entity, $this->sm));
     }
     return $entity;
 }
 /**
  * <p> Method to load the Map view as configured in routes.xml </p>
  * <p> Set the modules for the route to the page object </p>
  * @param object $rq <p>
  * The current HttpRequest.
  * </p>
  * @return void
  */
 public function executeLoadCurrentTasksView($rq)
 {
     $modules = $this->app()->router()->selectedRoute()->phpModules();
     $sessionProject = \Applications\PMTool\Helpers\ProjectHelper::GetCurrentSessionProject($this->app()->user());
     $sessionTask = \Applications\PMTool\Helpers\TaskHelper::GetCurrentSessionTask($this->app()->user());
     //Check if a project needs to be selected in order to display this page
     if (!$sessionProject) {
         $this->Redirect(\Library\Enums\ResourceKeys\UrlKeys::ProjectsSelectProject . "?onSuccess=" . \Library\Enums\ResourceKeys\UrlKeys::MapTaskLocations);
     }
     //Next check if a task is selected
     if (!$sessionTask) {
         $this->Redirect(\Library\Enums\ResourceKeys\UrlKeys::TaskSelectTask . "?onSuccess=" . \Library\Enums\ResourceKeys\UrlKeys::MapTaskLocations);
     }
     //Fetch tooltip data from xml and pass to view as an array
     $tooltip_array = \Applications\PMTool\Helpers\PopUpHelper::getTooltipMsgForAttribute('{"targetcontroller":"map", "targetaction": "taskLocations", "targetattr": ["question-map-h3", "map-info-ruler", "map-info-shape", "map-info-add"]}', $this->app->name());
     $this->page->addVar(\Applications\PMTool\Resources\Enums\ViewVariables\Popup::tooltip_message, $tooltip_array);
     $alert_msg = \Applications\PMTool\Helpers\PopUpHelper::getConfirmBoxMsg('{"targetcontroller":"map", "targetaction": "loadMaps", "operation": ["addUniqueCheck","checkCoordinates"]}', $this->app->name());
     $this->page->addVar(\Applications\PMTool\Resources\Enums\ViewVariables\Popup::confirm_message, $alert_msg);
     //add view vars for breadcrumb
     $this->page->addVar(\Applications\PMTool\Resources\Enums\ViewVariablesKeys::currentTask, $sessionTask[\Library\Enums\SessionKeys::TaskObj]);
     $this->page->addVar(\Applications\PMTool\Resources\Enums\ViewVariablesKeys::currentProject, $sessionProject[\Library\Enums\SessionKeys::ProjectObject]);
     $this->page->addVar(\Applications\PMTool\Resources\Enums\ViewVariablesKeys::form_modules, $modules);
     $this->page->addVar(\Applications\PMTool\Resources\Enums\ViewVariables\Map::default_active_control, $rq->getData('active') ?: 'pan');
 }
Example #22
0
 /**
  * @param object $entity
  */
 protected function handleEntity($entity)
 {
     /** @var RFMMetricCategory $entity */
     if ($entity instanceof $this->categoryClass) {
         $channel = $entity->getChannel();
         $this->channelsToRecalculate[spl_object_hash($channel)] = $channel;
     }
     /** @var Channel $entity */
     if ($entity instanceof $this->channelClass) {
         $data = $entity->getData();
         if (empty($data[RFMAwareInterface::RFM_REQUIRE_DROP_KEY])) {
             return;
         }
         unset($data[RFMAwareInterface::RFM_REQUIRE_DROP_KEY]);
         $entity->setData($data);
         $this->channelsToDrop[spl_object_hash($entity)] = $entity;
     }
 }
 /**
  * Test the ipc getData method
  */
 function test_getData()
 {
     $id = $this->last_insert_id;
     $type = 'x-phpgroupware/notes';
     return $this->ipc->getData($id, $type);
 }
 /**
  * Save the form controls data to the database
  *
  * @param object $form Jelix jForm object
  * @return Boolean True if the has been saved
  */
 public function saveFormDataToDb($form)
 {
     // Set the form from request
     //$form->initFromRequest();
     // Optionnaly query for the feature
     $cnx = jDb::getConnection($this->layerId);
     $layerName = $this->layerName;
     $capabilities = $this->project->getEditionLayers()->{$layerName}->capabilities;
     // Update or Insert
     $updateAction = false;
     $insertAction = false;
     if ($this->featureId) {
         $updateAction = true;
     } else {
         $insertAction = true;
     }
     // Get list of fields which are not primary keys
     $fields = array();
     foreach ($this->dataFields as $fieldName => $prop) {
         // For update : And get only fields corresponding to edition capabilities
         if (!$prop->primary and (strtolower($capabilities->modifyAttribute) == 'true' and $fieldName != $this->geometryColumn or strtolower($capabilities->modifyGeometry) == 'true' and $fieldName == $this->geometryColumn or $insertAction)) {
             $fields[] = $fieldName;
         }
     }
     if (count($fields) == 0) {
         jLog::log('Not enough capabilities for this layer ! SQL cannot be constructed: no fields available !', 'error');
         $form->setErrorOn($this->geometryColumn, 'An error has been raised when saving the form: Not enough capabilities for this layer !');
         jMessage::clearAll();
         jMessage::add(jLocale::get('view~edition.link.error.sql'), 'error');
         return false;
     }
     // Loop though the fields and filter the form posted values
     $update = array();
     $insert = array();
     $refs = array();
     foreach ($fields as $ref) {
         // Get and filter the posted data foreach form control
         $value = $form->getData($ref);
         if (is_array($value)) {
             $value = '{' . implode(',', $value) . '}';
         }
         switch ($this->formControls[$ref]->fieldDataType) {
             case 'geometry':
                 $value = "ST_GeomFromText('" . filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES) . "', " . $this->srid . ")";
                 $rs = $cnx->query('SELECT GeometryType(' . $value . ') as geomtype');
                 $rs = $rs->fetch();
                 if (!preg_match('/' . $this->geometryType . '/', strtolower($rs->geomtype))) {
                     if (preg_match('/' . str_replace('multi', '', $this->geometryType) . '/', strtolower($rs->geomtype))) {
                         $value = 'ST_Multi(' . $value . ')';
                     } else {
                         $form->setErrorOn($this->geometryColumn, "The geometry type doen't match!");
                         return false;
                     }
                 }
                 break;
             case 'date':
             case 'datetime':
                 $value = filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
                 if (!$value) {
                     $value = 'NULL';
                 } else {
                     $value = $cnx->quote($value);
                 }
                 break;
             case 'integer':
                 $value = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
                 if (!$value) {
                     $value = 'NULL';
                 }
                 break;
             case 'float':
                 $value = (double) $value;
                 if (!$value) {
                     $value = 'NULL';
                 }
                 break;
             default:
                 $value = $cnx->quote(filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES));
                 break;
         }
         if ($form->hasUpload() && array_key_exists($ref, $form->getUploads())) {
             $value = $form->getData($ref);
             $choiceValue = $form->getData($ref . '_choice');
             $hiddenValue = $form->getData($ref . '_hidden');
             $repPath = $this->repository->getPath();
             if ($choiceValue == 'update') {
                 $refPath = realpath($repPath . '/media') . '/upload/' . $this->project->getKey() . '/' . $this->tableName . '/' . $ref;
                 $form->saveFile($ref, $refPath);
                 $value = 'media' . '/upload/' . $this->project->getKey() . '/' . $this->tableName . '/' . $ref . '/' . $value;
                 if ($hiddenValue && file_exists(realPath($repPath) . '/' . $hiddenValue)) {
                     unlink(realPath($repPath) . '/' . $hiddenValue);
                 }
             } else {
                 if ($choiceValue == 'delete') {
                     if ($hiddenValue && file_exists(realPath($repPath) . '/' . $hiddenValue)) {
                         unlink(realPath($repPath) . '/' . $hiddenValue);
                     }
                     $value = 'NULL';
                 } else {
                     $value = $hiddenValue;
                 }
             }
             if (!$value) {
                 $value = 'NULL';
             } else {
                 if ($value != 'NULL') {
                     $value = $cnx->quote(filter_var($value, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES));
                 }
             }
         }
         // Build the SQL insert and update query
         $insert[] = $value;
         $refs[] = '"' . $ref . '"';
         $update[] = '"' . $ref . '"=' . $value;
     }
     $sql = '';
     // update
     if ($updateAction) {
         if (ctype_digit($this->featureId)) {
             $featureId = array($this->featureId);
         }
         // featureId is set
         // SQL for updating on line in the edition table
         $sql = " UPDATE " . $this->table . " SET ";
         $sql .= implode(', ', $update);
         $v = '';
         $i = 0;
         $sql .= ' WHERE';
         foreach ($this->primaryKeys as $key) {
             $sql .= "{$v} {$key} = " . $featureId[$i];
             $i++;
             $v = " AND ";
         }
         // Add login filter if needed
         if (!$this->loginFilteredOveride) {
             $this->filterDataByLogin($this->layerName);
             if (is_array($this->loginFilteredLayers)) {
                 $sql .= ' AND ' . $this->loginFilteredLayers['where'];
             }
         }
     }
     // insert
     if ($insertAction) {
         // SQL for insertion into the edition this->table
         function dquote($n)
         {
             return '"' . $n . '"';
         }
         $dfields = array_map("dquote", $fields);
         $sql = " INSERT INTO " . $this->table . " (";
         $sql .= implode(', ', $refs);
         $sql .= " ) VALUES (";
         $sql .= implode(', ', $insert);
         $sql .= " );";
     }
     try {
         $rs = $cnx->query($sql);
         //~ jLog::log($sql);
     } catch (Exception $e) {
         $form->setErrorOn($this->geometryColumn, 'An error has been raised when saving the form');
         jLog::log("SQL = " . $sql);
         jLog::log("An error has been raised when saving form data edition to db : " . $e->getMessage(), 'error');
         return false;
     }
     return true;
 }
Example #25
0
	/**
	 * Determine what to do when the previous action is called.
	 * 
	 * Retrieves the previous step class, finds the record for that
	 * class in the DB, and sets the current step to that step found.
	 * Finally, it redirects to that step.
	 * 
	 * @param array $data The request data returned from the form
	 * @param object $form The form that the action was called on
	 */
	public function prev($data, $form) {
		// Get the previous step class
		$prevStepClass = $this->getCurrentStep()->getPreviousStep();

		if(!$prevStepClass && !$this->getCurrentStep()->canGoBack()) {
			Director::redirectBack();
			return false;
		}

		// Save the form data for the current step
		$this->save($form->getData());
		
		// Get the previous step of the class instance returned from $currentStep->getPreviousStep()
		$prevStep = DataObject::get_one($prevStepClass, "SessionID = {$this->session->ID}");
		
		// Set the current step as the previous step
		$this->setCurrentStep($prevStep);
		
		// Redirect to the previous step
		Director::redirect($prevStep->Link());
		return;
	}
 /**
  * Formats content to be inserted like quote
  * @param object $message
  * @return
  */
 public function getQuoteContent($message)
 {
     $cnt = $message->getData('content');
     if ($this->isDepartmentAuthor($message)) {
         $_instance = 'html';
     } else {
         $_instance = 'text';
     }
     $cnt = Mage::getModel('helpdeskultimate/data_parser')->getInstance($_instance)->setText($cnt)->convertToQuoteAsText()->getText();
     return $cnt;
 }
Example #27
0
 /**
  * Use to update a table
  *
  * @param object $table {@link SmartDbTable} that will be updated
  *
  * @see SmartDbTable
  *
  * @return bool true if success, false if an error occured
  */
 function updateTable($table)
 {
     global $xoopsDB;
     $ret = true;
     // if table has a structure, create the table
     if ($table->getStructure()) {
         $ret = $table->createTable() && $ret;
     }
     // if table is flag for drop, drop it
     if ($table->_flagForDrop) {
         $ret = $table->dropTable() && $ret;
     }
     // if table has data, insert it
     if ($table->getData()) {
         $ret = $table->addData() && $ret;
     }
     // if table has new fields to be added, add them
     if ($table->getNewFields()) {
         $ret = $table->addNewFields() && $ret;
     }
     // if table has altered field, alter the table
     if ($table->getAlteredFields()) {
         $ret = $table->alterTable() && $ret;
     }
     // if table has updated field values, update the table
     if ($table->getUpdatedFields()) {
         $ret = $table->updateFieldsValues($table) && $ret;
     }
     // if table has droped field, alter the table
     if ($table->getDropedFields()) {
         $ret = $table->dropFields($table) && $ret;
     }
     //felix
     // if table has updated field values, update the table
     if ($table->getUpdatedWhere()) {
         $ret = $table->UpdateWhereValues($table) && $ret;
     }
     return $ret;
 }
Example #28
0
 /**
  * The real callback function for converting the input text to wiki text output
  *
  * @access	public
  * @param	string	Raw User Input
  * @param	object	Mediawiki Parser object.
  * @param	array	End Reset Booleans
  * @param	array	End Eliminate Booleans
  * @param	boolean	[Optional] Called as a parser tag
  * @return	string	Wiki/HTML Output
  */
 public function parse($input, \Parser $parser, &$reset, &$eliminate, $isParserTag = false)
 {
     wfProfileIn(__METHOD__);
     $dplStartTime = microtime(true);
     $this->parser = $parser;
     //Reset headings when being ran more than once in the same page load.
     Article::resetHeadings();
     //Check that we are not in an infinite transclusion loop
     if (isset($this->parser->mTemplatePath[$this->parser->mTitle->getPrefixedText()])) {
         $this->logger->addMessage(\DynamicPageListHooks::WARN_TRANSCLUSIONLOOP, $this->parser->mTitle->getPrefixedText());
         return $this->getFullOutput();
     }
     //Check if DPL shall only be executed from protected pages.
     if (Config::getSetting('runFromProtectedPagesOnly') === true && !$this->parser->mTitle->isProtected('edit')) {
         //Ideally we would like to allow using a DPL query if the query istelf is coded on a template page which is protected. Then there would be no need for the article to be protected.  However, how can one find out from which wiki source an extension has been invoked???
         $this->logger->addMessage(\DynamicPageListHooks::FATAL_NOTPROTECTED, $this->parser->mTitle->getPrefixedText());
         return $this->getFullOutput();
     }
     /************************************/
     /* Check for URL Arguments in Input */
     /************************************/
     if (strpos($input, '{%DPL_') >= 0) {
         for ($i = 1; $i <= 5; $i++) {
             $this->urlArguments[] = 'DPL_arg' . $i;
         }
     }
     $input = $this->resolveUrlArguments($input, $this->urlArguments);
     $this->getUrlArgs($this->parser);
     $this->parameters->setParameter('offset', $this->wgRequest->getInt('DPL_offset', $this->parameters->getData('offset')['default']));
     $offset = $this->parameters->getParameter('offset');
     /***************************************/
     /* User Input preparation and parsing. */
     /***************************************/
     $cleanParameters = $this->prepareUserInput($input);
     if (!is_array($cleanParameters)) {
         //Short circuit for dumb things.
         $this->logger->addMessage(\DynamicPageListHooks::FATAL_NOSELECTION);
         return $this->getFullOutput();
     }
     $cleanParameters = $this->parameters->sortByPriority($cleanParameters);
     $this->parameters->setParameter('includeuncat', false);
     // to check if pseudo-category of Uncategorized pages is included
     foreach ($cleanParameters as $parameter => $option) {
         foreach ($option as $_option) {
             //Parameter functions return true or false.  The full parameter data will be passed into the Query object later.
             if ($this->parameters->{$parameter}($_option) === false) {
                 //Do not build this into the output just yet.  It will be collected at the end.
                 $this->logger->addMessage(\DynamicPageListHooks::WARN_WRONGPARAM, $parameter, $_option);
             }
         }
     }
     /*************************/
     /* Execute and Exit Only */
     /*************************/
     if ($this->parameters->getParameter('execandexit') !== null) {
         //The keyword "geturlargs" is used to return the Url arguments and do nothing else.
         if ($this->parameters->getParameter('execandexit') == 'geturlargs') {
             return;
         }
         //In all other cases we return the value of the argument which may contain parser function calls.
         return $this->parameters->getParameter('execandexit');
     }
     //Construct internal keys for TableRow according to the structure of "include".  This will be needed in the output phase.
     if ($this->parameters->getParameter('seclabels') !== null) {
         $this->parameters->setParameter('tablerow', $this->updateTableRowKeys($this->parameters->getParameter('tablerow'), $this->parameters->getParameter('seclabels')));
     }
     /****************/
     /* Check Errors */
     /****************/
     $errors = $this->doQueryErrorChecks();
     if ($errors === false) {
         //WHAT HAS HAPPENED OH NOOOOOOOOOOOOO.
         return $this->getFullOutput();
     }
     $calcRows = false;
     if (!Config::getSetting('allowUnlimitedResults') && $this->parameters->getParameter('goal') != 'categories' && strpos($this->parameters->getParameter('resultsheader') . $this->parameters->getParameter('noresultsheader') . $this->parameters->getParameter('resultsfooter'), '%TOTALPAGES%') !== false) {
         $calcRows = true;
     }
     /*********/
     /* Query */
     /*********/
     try {
         $this->query = new Query($this->parameters);
         $result = $this->query->buildAndSelect($calcRows);
     } catch (MWException $e) {
         $this->logger->addMessage(\DynamicPageListHooks::FATAL_SQLBUILDERROR, $e->getMessage());
         return $this->getFullOutput();
     }
     $numRows = $this->DB->numRows($result);
     $articles = $this->processQueryResults($result);
     $this->addOutput('{{Extension DPL}}');
     //Preset these to defaults.
     $this->setVariable('TOTALPAGES', 0);
     $this->setVariable('PAGES', 0);
     $this->setVariable('VERSION', DPL_VERSION);
     /*********************/
     /* Handle No Results */
     /*********************/
     if ($numRows <= 0 || empty($articles)) {
         //Shortcut out since there is no processing to do.
         $this->DB->freeResult($result);
         return $this->getFullOutput(0, false);
     }
     $foundRows = null;
     if ($calcRows) {
         $foundRows = $this->query->getFoundRows();
     }
     //Backward scrolling: If the user specified only titlelt with descending reverse the output order.
     if ($this->parameters->getParameter('titlelt') && !$this->parameters->getParameter('titlegt') && $this->parameters->getParameter('order') == 'descending') {
         $articles = array_reverse($articles);
     }
     //Special sort for card suits (Bridge)
     if ($this->parameters->getParameter('ordersuitsymbols')) {
         $articles = $this->cardSuitSort($articles);
     }
     /*******************/
     /* Generate Output */
     /*******************/
     $listMode = new ListMode($this->parameters->getParameter('mode'), $this->parameters->getParameter('secseparators'), $this->parameters->getParameter('multisecseparators'), $this->parameters->getParameter('inlinetext'), $this->parameters->getParameter('listattr'), $this->parameters->getParameter('itemattr'), $this->parameters->getParameter('listseparators'), $offset, $this->parameters->getParameter('dominantsection'));
     $hListMode = new ListMode($this->parameters->getParameter('headingmode'), $this->parameters->getParameter('secseparators'), $this->parameters->getParameter('multisecseparators'), '', $this->parameters->getParameter('hlistattr'), $this->parameters->getParameter('hitemattr'), $this->parameters->getParameter('listseparators'), $offset, $this->parameters->getParameter('dominantsection'));
     $this->dpl = new DynamicPageList(Article::getHeadings(), $this->parameters->getParameter('headingcount'), $this->parameters->getParameter('columns'), $this->parameters->getParameter('rows'), $this->parameters->getParameter('rowsize'), $this->parameters->getParameter('rowcolformat'), $articles, $this->parameters->getParameter('ordermethods')[0], $hListMode, $listMode, $this->parameters->getParameter('escapelinks'), $this->parameters->getParameter('addexternallink'), $this->parameters->getParameter('incpage'), $this->parameters->getParameter('includemaxlen'), $this->parameters->getParameter('seclabels'), $this->parameters->getParameter('seclabelsmatch'), $this->parameters->getParameter('seclabelsnotmatch'), $this->parameters->getParameter('incparsed'), $this->parser, $this->parameters->getParameter('replaceintitle'), $this->parameters->getParameter('titlemaxlen'), $this->parameters->getParameter('defaulttemplatesuffix'), $this->parameters->getParameter('tablerow'), $this->parameters->getParameter('includetrim'), $this->parameters->getParameter('tablesortcol'), $this->parameters->getParameter('updaterules'), $this->parameters->getParameter('deleterules'));
     if ($foundRows === null) {
         $foundRows = $this->dpl->getRowCount();
     }
     $this->addOutput($this->dpl->getText());
     /*******************************/
     /* Replacement Variables       */
     /*******************************/
     $this->setVariable('TOTALPAGES', $foundRows);
     //Guaranteed to be an accurate count if SQL_CALC_FOUND_ROWS was used.  Otherwise only accurate if results are less than the SQL LIMIT.
     $this->setVariable('PAGES', $this->dpl->getRowCount());
     //This could be different than TOTALPAGES.  PAGES represents the total results within the constraints of SQL LIMIT.
     //Replace %DPLTIME% by execution time and timestamp in header and footer
     $nowTimeStamp = date('Y/m/d H:i:s');
     $dplElapsedTime = sprintf('%.3f sec.', microtime(true) - $dplStartTime);
     $dplTime = "{$dplElapsedTime} ({$nowTimeStamp})";
     $this->setVariable('DPLTIME', $dplTime);
     //Replace %LASTTITLE% / %LASTNAMESPACE% by the last title found in header and footer
     if (($n = count($articles)) > 0) {
         $firstNamespaceFound = str_replace(' ', '_', $articles[0]->mTitle->getNamespace());
         $firstTitleFound = str_replace(' ', '_', $articles[0]->mTitle->getText());
         $lastNamespaceFound = str_replace(' ', '_', $articles[$n - 1]->mTitle->getNamespace());
         $lastTitleFound = str_replace(' ', '_', $articles[$n - 1]->mTitle->getText());
     }
     $this->setVariable('FIRSTNAMESPACE', $firstNamespaceFound);
     $this->setVariable('FIRSTTITLE', $firstTitleFound);
     $this->setVariable('LASTNAMESPACE', $lastNamespaceFound);
     $this->setVariable('LASTTITLE', $lastTitleFound);
     $this->setVariable('SCROLLDIR', $this->parameters->getParameter('scrolldir'));
     /*******************************/
     /* Scroll Variables            */
     /*******************************/
     $scrollVariables = ['DPL_firstNamespace' => $firstNamespaceFound, 'DPL_firstTitle' => $firstTitleFound, 'DPL_lastNamespace' => $lastNamespaceFound, 'DPL_lastTitle' => $lastTitleFound, 'DPL_scrollDir' => $this->parameters->getParameter('scrolldir'), 'DPL_time' => $dplTime, 'DPL_count' => $this->parameters->getParameter('count'), 'DPL_totalPages' => $foundRows, 'DPL_pages' => $this->dpl->getRowCount()];
     $this->defineScrollVariables($scrollVariables);
     if ($this->parameters->getParameter('allowcachedresults')) {
         $this->parser->getOutput()->updateCacheExpiry($this->parameters->getParameter('cacheperiod') ? $this->parameters->getParameter('cacheperiod') : 3600);
     } else {
         $this->parser->disableCache();
     }
     $finalOutput = $this->getFullOutput($foundRows, false);
     $this->triggerEndResets($finalOutput, $reset, $eliminate, $isParserTag);
     wfProfileOut(__METHOD__);
     return $finalOutput;
 }
Example #29
0
 /**
  * @param object $entity
  * @param array $data
  * @return object
  */
 public function hydrate($entity, array $data)
 {
     $entity->setData(array_merge($entity->getData(), $data));
     return $entity;
 }
Example #30
0
 /**
  * Return Merge Fields mapped to Magento attributes
  *
  * @param object $customer
  * @param bool $includeEmail
  * @param integer $websiteId
  * @return array
  */
 public function getMergeVars($customer, $includeEmail = FALSE, $websiteId = NULL)
 {
     $merge_vars = array();
     $maps = $this->getMergeMaps($customer->getStoreId());
     if (!$maps) {
         return;
     }
     $request = Mage::app()->getRequest();
     //Add Customer data to Subscriber if is Newsletter_Subscriber is Customer
     if (!$customer->getDefaultShipping() && $customer->getEntityId()) {
         $customer->addData(Mage::getModel('customer/customer')->load($customer->getEntityId())->setStoreId($customer->getStoreId())->toArray());
     }
     foreach ($maps as $map) {
         $customAtt = $map['magento'];
         $chimpTag = $map['mailchimp'];
         if ($chimpTag && $customAtt) {
             $key = strtoupper($chimpTag);
             switch ($customAtt) {
                 case 'gender':
                     $val = (int) $customer->getData(strtolower($customAtt));
                     if ($val == 1) {
                         $merge_vars[$key] = 'Male';
                     } elseif ($val == 2) {
                         $merge_vars[$key] = 'Female';
                     }
                     break;
                 case 'dob':
                     $dob = (string) $customer->getData(strtolower($customAtt));
                     if ($dob) {
                         $merge_vars[$key] = substr($dob, 5, 2) . '/' . substr($dob, 8, 2);
                     }
                     break;
                 case 'billing_address':
                 case 'shipping_address':
                     $addr = explode('_', $customAtt);
                     $address = $customer->{'getPrimary' . ucfirst($addr[0]) . 'Address'}();
                     if ($address) {
                         $merge_vars[$key] = array('addr1' => $address->getStreet(1), 'addr2' => $address->getStreet(2), 'city' => $address->getCity(), 'state' => !$address->getRegion() ? $address->getCity() : $address->getRegion(), 'zip' => $address->getPostcode(), 'country' => $address->getCountryId());
                         $telephone = $address->getTelephone();
                         if ($telephone) {
                             $merge_vars['TELEPHONE'] = $telephone;
                         }
                         $company = $address->getCompany();
                         if ($company) {
                             $merge_vars['COMPANY'] = $company;
                         }
                     }
                     break;
                 case 'date_of_purchase':
                     $last_order = Mage::getResourceModel('sales/order_collection')->addFieldToFilter('customer_email', $customer->getEmail())->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))->setOrder('created_at', 'desc')->getFirstItem();
                     if ($last_order->getId()) {
                         $merge_vars[$key] = Mage::helper('core')->formatDate($last_order->getCreatedAt());
                     }
                     break;
                 case 'ee_customer_balance':
                     $merge_vars[$key] = '';
                     if ($this->isEnterprise() && $customer->getId()) {
                         $_customer = Mage::getModel('customer/customer')->load($customer->getId());
                         if ($_customer->getId()) {
                             if (Mage::app()->getStore()->isAdmin()) {
                                 $websiteId = is_null($websiteId) ? Mage::app()->getStore()->getWebsiteId() : $websiteId;
                             }
                             $balance = Mage::getModel('enterprise_customerbalance/balance')->setWebsiteId($websiteId)->setCustomerId($_customer->getId())->loadByCustomer();
                             $merge_vars[$key] = $balance->getAmount();
                         }
                     }
                     break;
                 case 'group_id':
                     $group_id = (int) $customer->getData(strtolower($customAtt));
                     $customerGroup = Mage::helper('customer')->getGroups()->toOptionHash();
                     if ($group_id == 0) {
                         $merge_vars[$key] = 'NOT LOGGED IN';
                     } else {
                         $merge_vars[$key] = $customerGroup[$group_id];
                     }
                     break;
                 default:
                     if ($value = (string) $customer->getData(strtolower($customAtt)) or $value = (string) $request->getPost(strtolower($customAtt))) {
                         $merge_vars[$key] = $value;
                     }
                     break;
             }
         }
     }
     //GUEST
     if (!$customer->getId() && (!$request->getPost('firstname') || !$request->getPost('lastname'))) {
         $guestFirstName = $this->config('guest_name', $customer->getStoreId());
         $guestLastName = $this->config('guest_lastname', $customer->getStoreId());
         if ($guestFirstName) {
             $merge_vars['FNAME'] = $guestFirstName;
         }
         if ($guestLastName) {
             $merge_vars['LNAME'] = $guestLastName;
         }
     }
     //GUEST
     if ($includeEmail) {
         $merge_vars['EMAIL'] = $customer->getEmail();
     }
     $groups = $customer->getListGroups();
     $groupings = array();
     if (is_array($groups) && count($groups)) {
         foreach ($groups as $groupId => $grupoptions) {
             $groupings[] = array('id' => $groupId, 'groups' => is_array($grupoptions) ? implode(', ', $grupoptions) : $grupoptions);
         }
     }
     $merge_vars['GROUPINGS'] = $groupings;
     //magemonkey_mergevars_after
     $blank = new Varien_Object();
     Mage::dispatchEvent('magemonkey_mergevars_after', array('vars' => $merge_vars, 'customer' => $customer, 'newvars' => $blank));
     if ($blank->hasData()) {
         $merge_vars = array_merge($merge_vars, $blank->toArray());
     }
     //magemonkey_mergevars_after
     return $merge_vars;
 }