/** * {@inheritdoc} */ public function startQuery($sql, array $params = null, array $types = null) { $this->query = null; if (!(\DBG::getMode() & DBG_DOCTRINE) && !(\DBG::getMode() & DBG_DOCTRINE_CHANGE) && !(\DBG::getMode() & DBG_DOCTRINE_ERROR)) { return; } // prepare SQL statement if ($params) { $sql = str_replace('?', "'%s'", $sql); //$this->query = vsprintf($sql, $params); foreach ($params as &$param) { // serialize arrays if (is_array($param)) { $param = serialize($param); } elseif (is_object($param)) { // serialize objects switch (get_class($param)) { case 'DateTime': // output DateTime object as date literal $param = $param->format(ASCMS_DATE_FORMAT_DATETIME); break; default: break; } } } $sql = vsprintf($sql, $params); } \DBG::logSQL($sql); $this->startTime = microtime(true); }
/** * Cloudrexx * * @link http://www.cloudrexx.com * @copyright Cloudrexx AG 2007-2015 * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Cloudrexx" is a registered trademark of Cloudrexx AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ function _marketUpdate() { global $objDatabase, $_ARRAYLANG; $query = "SELECT id FROM " . DBPREFIX . "module_market_settings WHERE name='codeMode'"; $objCheck = $objDatabase->SelectLimit($query, 1); if ($objCheck !== false) { if ($objCheck->RecordCount() == 0) { $query = "INSERT INTO `" . DBPREFIX . "module_market_settings` ( `id` , `name` , `value` , `description` , `type` )\n VALUES ( NULL , 'codeMode', '1', 'TXT_MARKET_SET_CODE_MODE', '2')"; if ($objDatabase->Execute($query) === false) { return _databaseError($query, $objDatabase->ErrorMsg()); } } } else { return _databaseError($query, $objDatabase->ErrorMsg()); } $arrColumns = $objDatabase->MetaColumns(DBPREFIX . 'module_market_mail'); if ($arrColumns === false) { setUpdateMsg(sprintf($_ARRAYLANG['TXT_UNABLE_GETTING_DATABASE_TABLE_STRUCTURE'], DBPREFIX . 'module_market_mail')); return false; } if (!isset($arrColumns['MAILTO'])) { $query = "ALTER TABLE `" . DBPREFIX . "module_market_mail` ADD `mailto` VARCHAR( 10 ) NOT NULL AFTER `content`"; if ($objDatabase->Execute($query) === false) { return _databaseError($query, $objDatabase->ErrorMsg()); } } /***************************************************************** * EXTENSION: New attributes 'color' and 'sort_id' for entries * * ADDED: Contrexx v2.1.0 * *****************************************************************/ $arrColumns = $objDatabase->MetaColumns(DBPREFIX . 'module_market'); if ($arrColumns === false) { setUpdateMsg(sprintf($_ARRAYLANG['TXT_UNABLE_GETTING_DATABASE_TABLE_STRUCTURE'], DBPREFIX . 'module_market')); return false; } if (!isset($arrColumns['SORT_ID'])) { $query = "ALTER TABLE `" . DBPREFIX . "module_market` ADD `sort_id` INT( 4 ) NOT NULL DEFAULT '0' AFTER `paypal`"; if ($objDatabase->Execute($query) === false) { return _databaseError($query, $objDatabase->ErrorMsg()); } } if (!isset($arrColumns['COLOR'])) { $query = "ALTER TABLE `" . DBPREFIX . "module_market` ADD `color` VARCHAR(50) NOT NULL DEFAULT '' AFTER `description`"; if ($objDatabase->Execute($query) === false) { return _databaseError($query, $objDatabase->ErrorMsg()); } } try { // delete obsolete table contrexx_module_market_access \Cx\Lib\UpdateUtil::drop_table(DBPREFIX . 'module_market_access'); \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_market_spez_fields', array('id' => array('type' => 'INT(5)', 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'name' => array('type' => 'VARCHAR(100)'), 'value' => array('type' => 'VARCHAR(100)'), 'type' => array('type' => 'INT(1)', 'notnull' => true, 'default' => '1'), 'lang_id' => array('type' => 'INT(2)', 'notnull' => true, 'default' => '0'), 'active' => array('type' => 'INT(1)', 'notnull' => true, 'default' => '0'))); } catch (\Cx\Lib\UpdateException $e) { DBG::trace(); return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } return true; }
/** * Event handler to add logs * * We need to do this with an event handler so there's no dependency to this component * @param string $eventName Name of triggered event, should always be static::EVENT_NAME * @param array $eventArgs Supplied arguments, should be an array (see DBG message below) */ public function onEvent($eventName, array $eventArgs) { if ($eventName != static::EVENT_NAME) { return; } if (empty($eventArgs['severity']) || empty($eventArgs['message']) || empty($eventArgs['data'])) { \DBG::msg('Triggered event "SysLog/Add" with wrong arguments. I need an array with non-empty values for the keys "severity", "message" and "data"'); return; } $this->addSysLog(new \Cx\Core_Modules\SysLog\Model\Entity\Log($eventArgs['severity'], $eventArgs['message'], $eventArgs['data'])); }
/** * Cloudrexx * * @link http://www.cloudrexx.com * @copyright Cloudrexx AG 2007-2015 * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Cloudrexx" is a registered trademark of Cloudrexx AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ function _auctionUpdate() { try { // delete obsolete table contrexx_module_auction_access \Cx\Lib\UpdateUtil::drop_table(DBPREFIX . 'module_auction_access'); } catch (\Cx\Lib\UpdateException $e) { // we COULD do something else here.. DBG::trace(); return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } return true; }
/** * Convert idn to utf8 format * * @param string $name * * @return string */ public static function convertIdnToUtf8Format($name) { if (empty($name)) { return; } if (!function_exists('idn_to_utf8')) { \DBG::msg('Idn is not supported in this system.'); } else { $name = idn_to_utf8($name); } return $name; }
/** * Clears a cache page * @param string $urlPattern Drop all pages that match the pattern, for exact format, make educated guesses * @param string $domain Domain name to drop cache page of * @param int $port Port to drop cache page of */ protected function clearCachePageForDomainAndPort($urlPattern, $domain, $port) { $errno = 0; $errstr = ''; $varnishSocket = fsockopen($this->hostname, $this->port, $errno, $errstr); if (!$varnishSocket) { \DBG::log('Varnish error: ' . $errstr . ' (' . $errno . ') on server ' . $this->hostname . ':' . $this->port); } $domainOffset = ASCMS_PATH_OFFSET; $request = 'BAN ' . $domainOffset . $urlPattern . " HTTP/1.0\r\n"; $request .= 'Host: ' . $domain . ':' . $port . "\r\n"; $request .= "User-Agent: Cloudrexx Varnish Cache Clear\r\n"; $request .= "Connection: Close\r\n\r\n"; fwrite($varnishSocket, $request); fclose($varnishSocket); }
protected function execute() { switch ($this->mode) { case self::MODE_DQL: $this->result = ''; $strQuery = trim($this->code); $lister = new \Cx\Core_Modules\Listing\Controller\ListingController(function (&$offset, &$count, &$criteria, &$order) use($strQuery) { return \Env::get('em')->createQuery($strQuery); }); try { $table = new \BackendTable($lister->getData()); $this->result = $table->toHtml() . $lister; } catch (\Exception $e) { $this->result = 'Could not execute query (' . $e->getMessage() . ')!'; } break; case self::MODE_PHP: $dbgMode = \DBG::getMode(); try { // This error handler catches all Warnings and Notices and some Strict errors \DBG::activate(DBG_PHP); set_error_handler(array($this, 'phpErrorsAsExceptionsHandler')); $this->errrorHandlerActive = true; // Since DBG catches the rest (E_PARSE) let's use that ob_start(); $function = create_function('$em, $cx', '' . $this->code . ';'); $dbgContents = ob_get_clean(); \DBG::activate($dbgMode); if (!is_callable($function)) { // parse exception throw new SandboxException($dbgContents); } $this->result = var_export($function(\Env::get('em'), \Env::get('cx')), true); restore_error_handler(); $this->errrorHandlerActive = false; } catch (\Exception $e) { \DBG::activate($dbgMode); restore_error_handler(); $this->errrorHandlerActive = false; $this->result = get_class($e) . ': ' . $e->getMessage(); } break; default: break; } }
public static function set($prop, &$val) { switch ($prop) { case 'cx': // set is only used for installerCx. Normal cx class will load with \Env::get('cx') self::$props[$prop] = $val; \DBG::msg(__METHOD__ . ": Setting '{$prop}' is deprecated. Use only for installer, otherwise use \\Env::('{$prop}')"); \DBG::stack(); break; case 'em': self::$props[$prop] = $val; \DBG::msg(__METHOD__ . ": Setting '{$prop}' is deprecated. Env::get({$prop}) always returns the active/preferred instance of {$prop}."); \DBG::stack(); break; default: self::$props[$prop] = $val; break; } }
public static function processRequest($token, $arrOrder) { global $_CONFIG; if (empty($token)) { return array('status' => 'error', 'message' => 'invalid token'); } $testMode = intval(\Cx\Core\Setting\Controller\Setting::getValue('paymill_use_test_account', 'Shop')) == 0; $apiKey = $testMode ? \Cx\Core\Setting\Controller\Setting::getValue('paymill_test_private_key', 'Shop') : \Cx\Core\Setting\Controller\Setting::getValue('paymill_live_private_key', 'Shop'); if ($token) { try { $request = new Paymill\Request($apiKey); $transaction = new Paymill\Models\Request\Transaction(); $transaction->setAmount($arrOrder['amount'])->setCurrency($arrOrder['currency'])->setToken($token)->setDescription($arrOrder['note'])->setSource('contrexx_' . $_CONFIG['coreCmsVersion']); DBG::log("Transactoin created with token:" . $token); $response = $request->create($transaction); $paymentId = $response->getId(); DBG::log("Payment ID" . $paymentId); return array('status' => 'success', 'payment_id' => $paymentId); } catch (\Paymill\Services\PaymillException $e) { //Do something with the error informations below return array('status' => 'error', 'response_code' => $e->getResponseCode(), 'status_code' => $e->getStatusCode(), 'message' => $e->getErrorMessage()); } } }
public static function setSQLQueryCache($msg) { self::$sql_query_cache = $msg; }
/** * Shows the image manipulation component. * * @global array $_ARRAYLANG * @return string Parsed content. */ function editMedia() { global $_ARRAYLANG; $this->_objTpl->loadTemplateFile('module_media_edit.html', true, true); $this->pageTitle = $_ARRAYLANG['TXT_MEDIA_EDIT_FILE']; if (isset($_GET['saveError']) && $_GET['saveError'] === 'true') { $this->_objTpl->setVariable(array('TXT_MEDIA_ERROR_OCCURED' => $_ARRAYLANG['TXT_MEDIA_ERROR_OCCURED'], 'TXT_MEDIA_ERROR_MESSAGE' => $_ARRAYLANG['TXT_MEDIA_CANNOT_SAVE_IMAGE'])); $this->_objTpl->parse('mediaErrorFile'); return; } // Activate cx \JS::activate('cx'); // Activate jQuery and imgAreaSelect \JS::activate('jquery'); \JS::activate('jquery-imgareaselect'); try { // Get quality options from the settings $arrImageSettings = $this->getImageSettings(); } catch (\Exception $e) { \DBG::msg('Could not query image settings: ' . $e->getMessage()); } $check = true; empty($this->getFile) ? $check = false : ''; empty($this->getPath) ? $check = false : ''; !file_exists($this->path . $this->getFile) ? $check = false : ''; if ($check) { // File exists $this->_objTpl->setVariable(array('TXT_MEDIA_SAVE' => $_ARRAYLANG['TXT_MEDIA_SAVE'], 'TXT_MEDIA_SAVE_AS' => $_ARRAYLANG['TXT_MEDIA_SAVE_AS'], 'TXT_MEDIA_RESET' => $_ARRAYLANG['TXT_MEDIA_RESET'], 'TXT_MEDIA_PREVIEW' => $_ARRAYLANG['TXT_PREVIEW'], 'MEDIA_EDIT_ACTION' => 'index.php?cmd=Media&archive=' . $this->archive . '&act=editImage&path=' . $this->webPath, 'MEDIA_DIR' => $this->webPath, 'MEDIA_FILE' => $this->getFile)); $icon = $this->_getIcon($this->path . $this->getFile); $info = pathinfo($this->getFile); $fileExt = $info['extension']; $ext = !empty($fileExt) ? '.' . $fileExt : ''; $fileName = substr($this->getFile, 0, strlen($this->getFile) - strlen($ext)); // Icon, file & extension name $this->_objTpl->setVariable(array('MEDIA_FILE_ICON' => self::_getIconWebPath() . $icon . '.png', 'MEDIA_FILE_DIR' => $this->webPath, 'MEDIA_FILE_NAME' => $fileName, 'MEDIA_FILE_EXT' => $fileExt)); // Edit image $imageSize = @getimagesize($this->path . $this->getFile); $this->_objTpl->setVariable(array('TXT_MEDIA_IMAGE_MANIPULATION' => $_ARRAYLANG['TXT_MEDIA_IMAGE_MANIPULATION'], 'TXT_MEDIA_WIDTH' => $_ARRAYLANG['TXT_MEDIA_WIDTH'], 'TXT_MEDIA_HEIGHT' => $_ARRAYLANG['TXT_MEDIA_HEIGHT'], 'TXT_MEDIA_BALANCE' => $_ARRAYLANG['TXT_MEDIA_BALANCE'], 'TXT_MEDIA_QUALITY' => $_ARRAYLANG['TXT_MEDIA_QUALITY'], 'TXT_MEDIA_SAVE' => $_ARRAYLANG['TXT_MEDIA_SAVE'], 'TXT_MEDIA_RESET' => $_ARRAYLANG['TXT_MEDIA_RESET'], 'TXT_MEDIA_SET_IMAGE_NAME' => $_ARRAYLANG['TXT_MEDIA_SET_IMAGE_NAME'], 'TXT_MEDIA_CONFIRM_REPLACE_IMAGE' => $_ARRAYLANG['TXT_MEDIA_CONFIRM_REPLACE_IMAGE'], 'TXT_MEDIA_REPLACE' => $_ARRAYLANG['TXT_MEDIA_REPLACE'], 'TXT_MEDIA_OR' => $_ARRAYLANG['TXT_MEDIA_OR'], 'TXT_MEDIA_SAVE_NEW_COPY' => $_ARRAYLANG['TXT_MEDIA_SAVE_NEW_COPY'], 'TXT_MEDIA_CROP' => $_ARRAYLANG['TXT_MEDIA_CROP'], 'TXT_MEDIA_CROP_INFO' => $_ARRAYLANG['TXT_MEDIA_CROP_INFO'], 'TXT_MEDIA_CANCEL' => $_ARRAYLANG['TXT_MEDIA_CANCEL'], 'TXT_MEDIA_ROTATE' => $_ARRAYLANG['TXT_MEDIA_ROTATE'], 'TXT_MEDIA_ROTATE_INFO' => $_ARRAYLANG['TXT_MEDIA_ROTATE_INFO'], 'TXT_MEDIA_SCALE_COMPRESS' => $_ARRAYLANG['TXT_MEDIA_SCALE_COMPRESS'], 'TXT_MEDIA_SCALE_INFO' => $_ARRAYLANG['TXT_MEDIA_SCALE_INFO'], 'TXT_MEDIA_PREVIEW' => $_ARRAYLANG['TXT_MEDIA_PREVIEW'], 'MEDIA_IMG_WIDTH' => $imageSize[0], 'MEDIA_IMG_HEIGHT' => $imageSize[1])); foreach ($this->arrImageQualityValues as $value) { $this->_objTpl->setVariable(array('IMAGE_QUALITY_VALUE' => $value, 'IMAGE_QUALITY_OPTION_CHECKED' => $value == $arrImageSettings['image_compression'] ? 'selected="selected"' : '')); $this->_objTpl->parse('mediaEditImageQualityOptions'); } $this->_objTpl->parse('mediaEditImage'); } else { // File doesn't exist $this->_objTpl->setVariable(array('TXT_MEDIA_ERROR_OCCURED' => $_ARRAYLANG['TXT_MEDIA_ERROR_OCCURED'], 'TXT_MEDIA_ERROR_MESSAGE' => $_ARRAYLANG['TXT_MEDIA_FILE_DONT_EXISTS'])); $this->_objTpl->parse('mediaErrorFile'); } // Variables $this->_objTpl->setVariable(array('CSRF' => \Cx\Core\Csrf\Controller\Csrf::param(), 'MEDIA_EDIT_AJAX_ACTION' => 'index.php?cmd=Media&archive=' . $this->archive . '&act=editImage&path=' . $this->webPath, 'MEDIA_EDIT_REDIRECT' => 'index.php?cmd=Media&archive=' . $this->archive . '&path=' . $this->webPath, 'MEDIA_BACK_HREF' => 'index.php?cmd=Media&archive=' . $this->archive . '&path=' . $this->webPath, 'MEDIA_FILE_IMAGE_SRC' => 'index.php?cmd=Media&archive=' . $this->archive . '&act=getImage&path=' . $this->webPath . '&file=' . $this->getFile . '&' . \Cx\Core\Csrf\Controller\Csrf::param(), 'MEDIA_IMAGE_WIDTH' => !empty($imageSize) ? intval($imageSize[0]) : 0, 'MEDIA_IMAGE_HEIGHT' => !empty($imageSize) ? intval($imageSize[1]) : 0, 'MEDIA_IMAGE_CROP_WIDTH' => $arrImageSettings['image_cut_width'], 'MEDIA_IMAGE_CROP_HEIGHT' => $arrImageSettings['image_cut_height'], 'MEDIA_IMAGE_RESIZE_QUALITY' => $arrImageSettings['image_compression'])); }
/** * Generate a component.yml for each theme available on the system * only used in update process for fixing invalid themes */ public function convertAllThemesToComponent() { foreach ($this->findAll() as $theme) { if ($theme->isComponent()) { continue; } try { $this->convertThemeToComponent($theme); } catch (\Exception $ex) { \DBG::log($ex->getMessage()); \DBG::log($theme->getThemesname() . ' : Unable to convert theme to component'); } } }
/** * This function saves an entity to the database * * @param string $entityWithNS class name including namespace * @access protected * @global array $_ARRAYLANG array containing the language variables */ protected function saveEntry($entityWithNS) { global $_ARRAYLANG; $cx = \Cx\Core\Core\Controller\Cx::instanciate(); $em = $cx->getDb()->getEntityManager(); // if entityId is a number the user edited an existing entry. If it is null we create a new one $entityId = contrexx_input2raw($this->getEntryId()); $this->renderFormForEntry($entityId); // if the form is not valid in any case, we stay in this view and do not save anything, because we can not be // sure that everything is alright if (!$this->validateForm()) { return; } // if there are no data submitted, we stay on this view, because we have nothing to save if (!$this->checkBlankPostRequest()) { return; } $entityClassMetadata = $em->getClassMetadata($entityWithNS); $associationMappings = $entityClassMetadata->getAssociationMappings(); // if we have a entityId, we came from edit mode and so we try to load the existing entry if ($entityId != 0) { $entity = $em->getRepository($entityWithNS)->find($entityId); $entityArray = array(); // This array is used for the existing values if ($this->object->entryExists($entityId)) { $entityArray = $this->object->getEntry($entityId); } if (empty($entityArray)) { \Message::add($_ARRAYLANG['TXT_CORE_RECORD_NO_SUCH_ENTRY'], \Message::CLASS_ERROR); return; } } else { // create new entity without calling the constructor TODO: this might break certain entities! $entity = $entityClassMetadata->newInstance(); } $classMethods = get_class_methods($entity); // this array is used to store all oneToMany associated entities, because we need to persist them for doctrine, // but we can not persist them before the main entity, so we need to buffer them $associatedEntityToPersist = array(); foreach ($associationMappings as $name => $value) { /* if we can not find the class name or the function to save the association we skip the entry, because there is now way to store it without these information */ if (empty($value['targetEntity'])) { \Message::add(sprintf($_ARRAYLANG['TXT_CORE_RECORD_CLASS_NOT_FOUND'], $name), \Message::CLASS_ERROR); continue; } /* this variable is the name of the field where we saved the values of the one to many associations because css does not support \ in class name */ $relatedClassInputFieldName = str_replace('\\', '_', strtolower($value["targetEntity"])); if (!empty($relatedClassInputFieldName) && !empty($_POST[$relatedClassInputFieldName]) && $em->getClassMetadata($entityWithNS)->isCollectionValuedAssociation($name)) { // store one to many associated entries $associatedEntityClassMetadata = $em->getClassMetadata($value["targetEntity"]); foreach ($_POST[$relatedClassInputFieldName] as $relatedPostData) { $entityData = array(); parse_str($relatedPostData, $entityData); // if we have already an entry (on update) we take the existing one and update it. // Otherwise we create a new one if (isset($entityData['id']) && $entityData['id'] != 0) { // update/edit case $associatedClassRepo = $em->getRepository($value["targetEntity"]); $associatedEntity = $associatedClassRepo->find($entityData['id']); } else { // add case $associatedEntity = $associatedEntityClassMetadata->newInstance(); } // if there are any entries which the user wants to delete, we delete them here if (isset($entityData['delete']) && $entityData['delete'] == 1) { $em->remove($associatedEntity); } // save the "n" associated class data to its class $this->savePropertiesToClass($associatedEntity, $associatedEntityClassMetadata, $entityData, $entityWithNS); // Linking 1: link the associated entity to the main entity for doctrine $methodName = 'add' . str_replace(' ', '', ucwords(str_replace('_', ' ', $name))); if (!in_array($methodName, $classMethods)) { \Message::add(sprintf($_ARRAYLANG['TXT_CORE_RECORD_FUNCTION_NOT_FOUND'], $name, $methodName), \Message::CLASS_ERROR); continue; } $entity->{$methodName}($associatedEntity); // Linking 2: link the main entity to its associated entity. This should normally be done by // 'Linking 1' but because not all components have implemented this, we do it here by ourselves $method = 'set' . ucfirst($value["mappedBy"]); if (method_exists($associatedEntity, $method)) { $associatedEntity->{$method}($entity); } // buffer entity, so we can persist it later $associatedEntityToPersist[] = $associatedEntity; } } } if ($entityId != 0) { // edit case // update the main entry in doctrine so we can store it over doctrine to database later $this->savePropertiesToClass($entity, $entityClassMetadata); $param = 'editid'; $successMessage = $_ARRAYLANG['TXT_CORE_RECORD_UPDATED_SUCCESSFUL']; } else { // add case // save main formular class data to its class over $_POST $this->savePropertiesToClass($entity, $entityClassMetadata); $param = 'add'; $successMessage = $_ARRAYLANG['TXT_CORE_RECORD_ADDED_SUCCESSFUL']; } $showSuccessMessage = false; if ($entity instanceof \Cx\Core\Model\Model\Entity\YamlEntity) { // Save the yaml entities $entityRepository = $em->getRepository($entityWithNS); if (!$entityRepository->isManaged($entity)) { $entityRepository->add($entity); } $entityRepository->flush(); $showSuccessMessage = true; } else { if ($entity instanceof \Cx\Model\Base\EntityBase) { /* We try to store the prepared em. This may fail if (for example) we have a one to many association which can not be null but was not set in the post request. This cases should be caught here. */ try { // persist main entity. This must be done first, otherwise saving oneToManyAssociated entities won't work $em->persist($entity); // now we can persist the associated entities. We need to do this, because otherwise it will fail, // if yaml does not contain a cascade option foreach ($associatedEntityToPersist as $associatedEntity) { $em->persist($associatedEntity); } $em->flush(); $showSuccessMessage = true; } catch (\Cx\Core\Error\Model\Entity\ShinyException $e) { /* Display the message from the exception. If this message is empty, we output a general message, so the user knows what to do in every case */ if ($e->getMessage() != "") { \Message::add($e->getMessage(), \Message::CLASS_ERROR); } else { \Message::add($_ARRAYLANG['TXT_CORE_RECORD_UNKNOWN_ERROR'], \Message::CLASS_ERROR); } return; } catch (\Exception $e) { echo $e->getMessage(); die; } } else { \Message::add($_ARRAYLANG['TXT_CORE_RECORD_VALIDATION_FAILED'], \Message::CLASS_ERROR); \DBG::msg('Unkown entity model ' . get_class($entity) . '! Trying to persist using entity manager...'); } } if ($showSuccessMessage) { \Message::add($successMessage); } // get the proper action url and redirect the user $actionUrl = clone $cx->getRequest()->getUrl(); $actionUrl->setParam($param, null); \Cx\Core\Csrf\Controller\Csrf::redirect($actionUrl); }
/** * Returns an array of SQL snippets to include the selected Text records * in the query. * * Provide a single value for the $key, or an array. * If you use an array, the array keys *MUST* contain distinct alias names * for the respective text keys. * The array returned looks as follows: * array( * 'alias' => The array of Text field aliases: * array(key => field name alias, ...) * Use the alias to access the text content in the resulting * recordset, or if you need to sort the result by that * column. * 'field' => Field snippet to be included in the SQL SELECT, uses * aliased field names for the id ("text_#_id") and text * ("text_#_text") fields. * No leading comma is included! * 'join' => SQL JOIN snippet, the LEFT JOIN with the core_text table * and conditions * ) * The '#' is replaced by a unique integer number. * The '*' may be any descriptive part of the name that disambiguates * multiple foreign keys in a single table, like 'name', or 'value'. * Note that the $lang_id parameter is mandatory and *MUST NOT* be * emtpy. $alias may be null (or omitted), in which case it is ignored, * and the default form "text_<index>" is used, where <index> is an integer * incremented on each use. * @static * @param string $field_id The name of the text ID * foreign key field. Note that this * is not part of the SELECTed fields, * but used in the JOIN only. * @param integer $lang_id The language ID * @param string $section The section * @param mixed $keys A single key, or an array thereof * @return array The array with SQL code parts * @author Reto Kohli <*****@*****.**> */ static function getSqlSnippets($field_id, $lang_id, $section, $keys) { static $table_alias_index = 0; if (empty($field_id)) { DBG::log("Text::getSqlSnippets(): ERROR: Empty field ID"); return false; } if (empty($lang_id)) { DBG::log("Text::getSqlSnippets(): ERROR: Empty language ID"); return false; } if (empty($section)) { DBG::log("Text::getSqlSnippets(): ERROR: Empty section"); return false; } if (empty($keys)) { DBG::log("Text::getSqlSnippets(): ERROR: Empty keys"); return false; } if (!is_array($keys)) { $keys = array($keys); } $query_field = ''; $query_join = ''; $arrSql = array(); foreach ($keys as $alias => $key) { $table_alias = 'text_' . ++$table_alias_index; $field_id_alias = $table_alias . '_id'; $field_text_alias = $alias ? $alias : $table_alias . '_text'; $field_text_name = "`{$table_alias}`.`text`"; $query_field .= ($query_field ? ', ' : '') . "\n `{$table_alias}`.`id` AS `{$field_id_alias}`,\n {$field_text_name} AS `{$field_text_alias}`"; $query_join .= "\n LEFT JOIN `" . DBPREFIX . "core_text` as `{$table_alias}`\n ON `{$table_alias}`.`id`={$field_id}\n AND `{$table_alias}`.`lang_id`={$lang_id}\n AND `{$table_alias}`.`section`" . (isset($section) ? "='" . addslashes($section) . "'" : ' IS NULL') . "\n AND `{$table_alias}`.`key`='" . addslashes($key) . "'"; $arrSql['alias'][$alias] = $field_text_name; } $arrSql['field'] = $query_field; $arrSql['join'] = $query_join; //DBG::log("Text::getSqlSnippets(): field: {$arrSql['field']}"); //DBG::log("Text::getSqlSnippets(): join: {$arrSql['join']}"); return $arrSql; }
/** * Find the url exists or not * * @param string $url url * * @return boolean true on url exists, false otherwise */ function urlfind($url) { if (!ini_get('allow_url_fopen')) { ini_set('allow_url_fopen', 'On'); } if (ini_get('allow_url_fopen')) { if ($url) { $file = @fopen($url . '/modules/Calendar/Controller/CalendarWebserviceServer.class.php', "r"); } if ($file) { fclose($file); return true; } else { return false; } } else { try { $request = new \HTTP_Request2($url . 'modules/Calendar/Controller/CalendarWebserviceServer.class.php'); $response = $request->send(); if (404 == $response->getStatus()) { return false; } else { return true; } } catch (Exception $e) { \DBG::msg($e->getMessage()); return false; } } }
function _newsletterUpdate() { global $objDatabase, $objUpdate, $_CONFIG; try { \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_category', array('id' => array('type' => 'INT(11)', 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'status' => array('type' => 'TINYINT(1)', 'notnull' => true, 'default' => '0', 'after' => 'id'), 'name' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'status'), 'notification_email' => array('type' => 'VARCHAR(250)', 'notnull' => true, 'default' => '', 'after' => 'name')), array('name' => array('fields' => array('name')))); \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_confirm_mail', array('id' => array('type' => 'INT(1)', 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'title' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'id'), 'content' => array('type' => 'longtext', 'after' => 'title'), 'recipients' => array('type' => 'text', 'after' => 'content'))); \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter', array('id' => array('type' => 'INT(11)', 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'subject' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'id'), 'template' => array('type' => 'INT(11)', 'notnull' => true, 'default' => '0', 'after' => 'subject'), 'content' => array('type' => 'text', 'after' => 'template'), 'attachment' => array('type' => 'ENUM(\'0\',\'1\')', 'notnull' => true, 'default' => '0', 'after' => 'content'), 'priority' => array('type' => 'TINYINT(1)', 'notnull' => true, 'default' => '0', 'after' => 'attachment'), 'sender_email' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'priority'), 'sender_name' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'sender_email'), 'return_path' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'sender_name'), 'smtp_server' => array('type' => 'INT(10)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'after' => 'return_path'), 'status' => array('type' => 'INT(1)', 'notnull' => true, 'default' => '0', 'after' => 'smtp_server'), 'count' => array('type' => 'INT(11)', 'notnull' => true, 'default' => '0', 'after' => 'status'), 'recipient_count' => array('type' => 'INT(11)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'after' => 'count'), 'date_create' => array('type' => 'INT(14)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'after' => 'recipient_count'), 'date_sent' => array('type' => 'INT(14)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'after' => 'date_create'), 'tmp_copy' => array('type' => 'TINYINT(1)', 'notnull' => true, 'default' => '0', 'after' => 'date_sent'))); } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } DBG::msg("Done checking tables.. going to check settings"); //the two values notifyOnUnsubscribe and notificationUnsubscribe have been merged into the latter. $unsubscribeVal = 1; try { DBG::msg("Retrieving old unsubscribe value if set."); $res = \Cx\Lib\UpdateUtil::sql("SELECT setvalue FROM " . DBPREFIX . "module_newsletter_settings WHERE setname='notifyOnUnsubscribe'"); if (!$res->EOF) { $unsubscribeVal = $res->fields['setvalue']; } else { DBG::msg("Not found. Retrieving new unsubscribe value if set."); $res = \Cx\Lib\UpdateUtil::sql("SELECT setvalue FROM " . DBPREFIX . "module_newsletter_settings WHERE setname='notificatonUnsubscribe'"); if (!$res->EOF) { $unsubscribeVal = $res->fields['setvalue']; } } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } $settings = array('sender_mail' => array('setid' => 1, 'setname' => 'sender_mail', 'setvalue' => '*****@*****.**', 'status' => 1), 'sender_name' => array('setid' => 2, 'setname' => 'sender_name', 'setvalue' => 'admin', 'status' => 1), 'reply_mail' => array('setid' => 3, 'setname' => 'reply_mail', 'setvalue' => '*****@*****.**', 'status' => 1), 'mails_per_run' => array('setid' => 4, 'setname' => 'mails_per_run', 'setvalue' => '30', 'status' => 1), 'text_break_after' => array('setid' => 5, 'setname' => 'text_break_after', 'setvalue' => '100', 'status' => 1), 'test_mail' => array('setid' => 6, 'setname' => 'test_mail', 'setvalue' => '*****@*****.**', 'status' => 1), 'overview_entries_limit' => array('setid' => 7, 'setname' => 'overview_entries_limit', 'setvalue' => '10', 'status' => 1), 'rejected_mail_operation' => array('setid' => 8, 'setname' => 'rejected_mail_operation', 'setvalue' => 'delete', 'status' => 1), 'defUnsubscribe' => array('setid' => 9, 'setname' => 'defUnsubscribe', 'setvalue' => '0', 'status' => 1), 'notificationSubscribe' => array('setid' => 11, 'setname' => 'notificationSubscribe', 'setvalue' => '1', 'status' => 1), 'notificationUnsubscribe' => array('setid' => 10, 'setname' => 'notificationUnsubscribe', 'setvalue' => $unsubscribeVal, 'status' => 1), 'recipient_attribute_status' => array('setid' => 12, 'setname' => 'recipient_attribute_status', 'setvalue' => '{"recipient_sex":{"active":true,"required":false},"recipient_salutation":{"active":true,"required":false},"recipient_title":{"active":false,"required":false},"recipient_firstname":{"active":true,"required":false},"recipient_lastname":{"active":true,"required":false},"recipient_position":{"active":false,"required":false},"recipient_company":{"active":true,"required":false},"recipient_industry":{"active":false,"required":false},"recipient_address":{"active":true,"required":false},"recipient_city":{"active":true,"required":false},"recipient_zip":{"active":true,"required":false},"recipient_country":{"active":true,"required":false},"recipient_phone":{"active":true,"required":false},"recipient_private":{"active":false,"required":false},"recipient_mobile":{"active":false,"required":false},"recipient_fax":{"active":false,"required":false},"recipient_birthday":{"active":true,"required":false},"recipient_website":{"active":false,"required":false}}', 'status' => 1), 'reject_info_mail_text' => array('setid' => 13, 'setname' => 'reject_info_mail_text', 'setvalue' => 'Der Newsletter konnte an folgende E-Mail-Adresse nicht versendet werden:\\r\\n[[EMAIL]]\\r\\n\\r\\nUm die E-Mail Adresse zu bearbeiten, klicken Sie bitte auf den folgenden Link:\\r\\n[[LINK]]', 'status' => 1)); try { DBG::msg("Reading current settings"); $res = \Cx\Lib\UpdateUtil::sql("SELECT * FROM " . DBPREFIX . "module_newsletter_settings"); while (!$res->EOF) { $field = $res->fields['setname']; DBG::msg("...merging {$field} with default settings"); if (isset($settings[$field])) { //do we have another value for this? $settings[$field]['setvalue'] = $res->fields['setvalue']; } $res->MoveNext(); } DBG::msg("Updating settings"); foreach ($settings as $entry) { $setid = intval($entry['setid']); $field = addslashes($entry['setname']); $value = addslashes($entry['setvalue']); $status = intval($entry['status']); DBG::msg("...deleting field {$field}"); \Cx\Lib\UpdateUtil::sql("DELETE FROM " . DBPREFIX . "module_newsletter_settings WHERE setid = '{$setid}' OR setname = '{$field}'"); DBG::msg("...rewriting field {$field}"); \Cx\Lib\UpdateUtil::sql("\n INSERT INTO " . DBPREFIX . "module_newsletter_settings\n (setid, setname, setvalue, status)\n VALUES (\n '{$setid}', '{$field}', '{$value}', '{$status}'\n );\n "); } DBG::msg("Deleting old unsubscribe key if set"); \Cx\Lib\UpdateUtil::sql("DELETE FROM " . DBPREFIX . "module_newsletter_settings WHERE setname='notifyOnUnsubscribe'"); DBG::msg("Done with newsletter update"); } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } try { DBG::msg("Setting recipient count"); $objResult = \Cx\Lib\UpdateUtil::sql("SELECT `newsletter`, COUNT(1) AS recipient_count FROM `" . DBPREFIX . "module_newsletter_tmp_sending` GROUP BY `newsletter`"); if ($objResult->RecordCount()) { while (!$objResult->EOF) { \Cx\Lib\UpdateUtil::sql("UPDATE `" . DBPREFIX . "module_newsletter` SET `recipient_count` = " . $objResult->fields['recipient_count'] . " WHERE `id`=" . $objResult->fields['newsletter']); $objResult->MoveNext(); } } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } // Add notification recipients to confirm_mail table try { $objResult = \Cx\Lib\UpdateUtil::sql("SELECT id FROM `" . DBPREFIX . "module_newsletter_confirm_mail` WHERE id='3'"); if ($objResult->RecordCount() == 0) { DBG::msg("inserting standard confirm mails"); \Cx\Lib\UpdateUtil::sql("INSERT INTO `" . DBPREFIX . "module_newsletter_confirm_mail` (`id` ,`title` ,`content` ,`recipients`) VALUES ('3', '[[url]] - Neue Newsletter Empfänger [[action]]', 'Hallo Admin Eine neue Empfänger [[action]] in ihrem Newsletter System. Automatisch generierte Nachricht [[date]]', '');"); } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } try { \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_access_user', array('accessUserID' => array('type' => 'INT(5)', 'unsigned' => true), 'newsletterCategoryID' => array('type' => 'INT(11)', 'after' => 'accessUserID'), 'code' => array('type' => 'VARCHAR(255)', 'after' => 'newsletterCategoryID', 'notnull' => true, 'default' => '')), array('rel' => array('fields' => array('accessUserID', 'newsletterCategoryID'), 'type' => 'UNIQUE'), 'accessUserID' => array('fields' => array('accessUserID')))); // set random newsletter code for access recipients \Cx\Lib\UpdateUtil::sql('UPDATE ' . DBPREFIX . 'module_newsletter_access_user SET `code` = SUBSTR(MD5(RAND()),1,12) WHERE `code` = \'\''); \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_rel_usergroup_newsletter', array('userGroup' => array('type' => 'INT(10)', 'unsigned' => true), 'newsletter' => array('type' => 'INT(10)', 'unsigned' => true, 'after' => 'userGroup')), array('uniq' => array('fields' => array('userGroup', 'newsletter'), 'type' => 'UNIQUE'))); \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_settings', array('setid' => array('type' => 'INT(6)', 'unsigned' => true, 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'setname' => array('type' => 'VARCHAR(250)', 'after' => 'setid', 'notnull' => true, 'default' => ''), 'setvalue' => array('type' => 'text', 'after' => 'setname'), 'status' => array('type' => 'TINYINT(1)', 'notnull' => true, 'default' => '0', 'after' => 'setvalue')), array('setname' => array('fields' => array('setname'), 'type' => 'UNIQUE'))); \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_tmp_sending', array('id' => array('type' => 'INT(11)', 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'newsletter' => array('type' => 'INT(11)', 'notnull' => true, 'default' => '0', 'after' => 'id'), 'email' => array('type' => 'VARCHAR(255)', 'after' => 'newsletter', 'notnull' => true, 'default' => ''), 'sendt' => array('type' => 'TINYINT(1)', 'notnull' => true, 'default' => '0', 'after' => 'email'), 'type' => array('type' => 'ENUM(\'access\',\'newsletter\',\'core\')', 'notnull' => true, 'default' => 'newsletter', 'after' => 'sendt'), 'code' => array('type' => 'VARCHAR(10)', 'after' => 'type')), array('unique_email' => array('fields' => array('newsletter', 'email'), 'type' => 'UNIQUE'), 'email' => array('fields' => array('email')))); \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_email_link', array('id' => array('type' => 'INT(11)', 'unsigned' => true, 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'email_id' => array('type' => 'INT(11)', 'unsigned' => true, 'after' => 'id'), 'title' => array('type' => 'VARCHAR(255)', 'after' => 'email_id'), 'url' => array('type' => 'VARCHAR(255)', 'after' => 'title')), array('email_id' => array('fields' => array('email_id')))); \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_email_link_feedback', array('id' => array('type' => 'INT(11)', 'unsigned' => true, 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'link_id' => array('type' => 'INT(11)', 'unsigned' => true, 'after' => 'id'), 'email_id' => array('type' => 'INT(11)', 'unsigned' => true, 'after' => 'link_id'), 'recipient_id' => array('type' => 'INT(11)', 'unsigned' => true, 'after' => 'email_id'), 'recipient_type' => array('type' => 'ENUM(\'access\',\'newsletter\')', 'after' => 'recipient_id')), array('link_id' => array('fields' => array('link_id', 'email_id', 'recipient_id', 'recipient_type'), 'type' => 'UNIQUE'), 'email_id' => array('fields' => array('email_id')))); \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_template', array('id' => array('type' => 'INT(11)', 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'name' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'id'), 'description' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'name'), 'html' => array('type' => 'text', 'after' => 'description'), 'required' => array('type' => 'INT(1)', 'notnull' => true, 'default' => '0', 'after' => 'html'), 'type' => array('type' => 'ENUM(\'e-mail\',\'news\')', 'notnull' => true, 'default' => 'e-mail', 'after' => 'required'))); // migrate country field if (newsletter_migrate_country_field() == 'timeout') { return 'timeout'; } // IMPORTANT: the table definition statement of module_newsletter_user must be AFTER newsletter_migrate_country_field() has been called! // fix missing columns & rename old columns if required \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_newsletter_user', array('id' => array('type' => 'INT(11)', 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'code' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'id'), 'email' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'code'), 'uri' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'email'), 'sex' => array('type' => 'ENUM(\'m\',\'f\')', 'notnull' => false, 'after' => 'uri'), 'salutation' => array('type' => 'INT(10)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'after' => 'sex', 'renamefrom' => 'title'), 'title' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'salutation'), 'lastname' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'title'), 'firstname' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'lastname'), 'position' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'firstname'), 'company' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'position'), 'industry_sector' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'company'), 'address' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'industry_sector', 'renamefrom' => 'street'), 'zip' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'address'), 'city' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'zip'), 'country_id' => array('type' => 'SMALLINT(5)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'after' => 'city'), 'phone_office' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'country_id', 'renamefrom' => 'phone'), 'phone_private' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'phone_office'), 'phone_mobile' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'phone_private'), 'fax' => array('type' => 'VARCHAR(255)', 'notnull' => true, 'default' => '', 'after' => 'phone_mobile'), 'notes' => array('type' => 'text', 'after' => 'fax'), 'birthday' => array('type' => 'VARCHAR(10)', 'notnull' => true, 'default' => '00-00-0000', 'after' => 'notes'), 'status' => array('type' => 'INT(1)', 'notnull' => true, 'default' => '0', 'after' => 'birthday'), 'emaildate' => array('type' => 'INT(14)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'after' => 'status'), 'language' => array('type' => 'INT(3)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'after' => 'emaildate')), array('email' => array('fields' => array('email'), 'type' => 'UNIQUE'), 'status' => array('fields' => array('status')))); // fix user's SALUTATION of previews updates if (!$objUpdate->_isNewerVersion($_CONFIG['coreCmsVersion'], '3.0.0') && $objUpdate->_isNewerVersion($_CONFIG['coreCmsVersion'], '3.0.3')) { // set user's SALUTATION based of previews updates \Cx\Lib\UpdateUtil::sql("UPDATE `" . DBPREFIX . "module_newsletter_user` SET `salutation` = `title`, `title` = '' WHERE `salutation` = '0' AND `title` REGEXP '^[0-9]+\$'"); // clear all user's TITLE attribute that consist only of a number (it is most likely not the case that a user's TITLE is a number, // so we assume that it is a left over of the preview update bug, which did not migrate the user's TITLE attribute to the user's SALUTATION attribute \Cx\Lib\UpdateUtil::sql("UPDATE `" . DBPREFIX . "module_newsletter_user` SET `title` = '' WHERE `title` REGEXP '^[0-9]+\$'"); } // switch to source mode for all newsletter content pages \Cx\Lib\UpdateUtil::setSourceModeOnContentPage(array('module' => 'newsletter'), '3.0.1'); // replace several placeholders that have changed $search = array('/TXT_NEWSLETTER_URI/', '/NEWSLETTER_URI/', '/TXT_NEWSLETTER_STREET/', '/NEWSLETTER_STREET/'); $replace = array('TXT_NEWSLETTER_WEBSITE', 'NEWSLETTER_WEBSITE', 'TXT_NEWSLETTER_ADDRESS', 'NEWSLETTER_ADDRESS'); \Cx\Lib\UpdateUtil::migrateContentPageUsingRegex(array('module' => 'newsletter'), $search, $replace, array('content'), '3.0.1'); // sorry, brainfuck coming up... // this adds the missing template block newsletter_list as well as the placeholder [[NEWSLETTER_LIST_SELECTED]] $search = array('/(<!--\\s+BEGIN\\s+newsletter_lists\\s+-->)(.*)(<!--\\s+END\\s+newsletter_lists\\s+-->)/ms'); $callback = function ($matches) { if (preg_match('/^(.*)(<[^>]+[\'"]list\\[\\{NEWSLETTER_LIST_ID\\}\\][\'"])([^>]*>)(.*)$/ms', $matches[2], $listMatches)) { if (strpos($listMatches[2] . $listMatches[3], '{NEWSLETTER_LIST_SELECTED}') === false) { $matches[2] = $listMatches[1] . $listMatches[2] . ' {NEWSLETTER_LIST_SELECTED} ' . $listMatches[3] . $listMatches[4]; } else { $matches[2] = $listMatches[1] . $listMatches[2] . $listMatches[3] . $listMatches[4]; } } if (!preg_match('/<!--\\s+BEGIN\\s+newsletter_list\\s+-->.*<!--\\s+END\\s+newsletter_list\\s+-->/ms', $matches[2])) { return $matches[1] . '<!-- BEGIN newsletter_list -->' . $matches[2] . '<!-- END newsletter_list -->' . $matches[3]; } else { return $matches[1] . $matches[2] . $matches[3]; } }; \Cx\Lib\UpdateUtil::migrateContentPageUsingRegexCallback(array('module' => 'newsletter'), $search, $callback, array('content'), '3.0.1'); // this adds the missing placeholders [[SELECTED_DAY]], [[SELECTED_MONTH]], [[SELECTED_YEAR]] $search = array('/(<option[^>]+\\{USERS_BIRTHDAY_(DAY|MONTH|YEAR)\\}[\'"])([^>]*>)/ms'); $callback = function ($matches) { if (strpos($matches[1] . $matches[3], '{SELECTED_' . $matches[2] . '}') === false) { return $matches[1] . ' {SELECTED_' . $matches[2] . '} ' . $matches[3]; } else { return $matches[1] . $matches[3]; } }; \Cx\Lib\UpdateUtil::migrateContentPageUsingRegexCallback(array('module' => 'newsletter'), $search, $callback, array('content'), '3.0.1'); // replace [[TXT_NEWSLETTER_TITLE]] to [[TXT_NEWSLETTER_SALUTATION]] // replace [[NEWSLETTER_TITLE]] to [[NEWSLETTER_SALUTATION]] $search = array('/.*\\{NEWSLETTER_TITLE\\}.*/ms'); $callback = function ($matches) { if (!preg_match('/<!--\\s+BEGIN\\s+recipient_title\\s+-->.*\\{NEWSLETTER_TITLE\\}.*<!--\\s+END\\s+recipient_title\\s+-->/ms', $matches[0]) && !preg_match('/<!--\\s+BEGIN\\s+recipient_salutation\\s+-->/ms', $matches[0]) && !preg_match('/\\{NEWSLETTER_SALUTATION\\}/ms', $matches[0])) { return str_replace(array('TXT_NEWSLETTER_TITLE', '{NEWSLETTER_TITLE}'), array('TXT_NEWSLETTER_SALUTATION', '{NEWSLETTER_SALUTATION}'), $matches[0]); } else { return $matches[0]; } }; \Cx\Lib\UpdateUtil::migrateContentPageUsingRegexCallback(array('module' => 'newsletter'), $search, $callback, array('content'), '3.0.1'); } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } if ($objUpdate->_isNewerVersion($_CONFIG['coreCmsVersion'], '3.0.3') && empty($_SESSION['contrexx_update']['newsletter_links_decoded'])) { try { $objResult = \Cx\Lib\UpdateUtil::sql('SELECT `id`, `url` FROM `' . DBPREFIX . 'module_newsletter_email_link`'); if ($objResult !== false && $objResult->RecordCount() > 0) { while (!$objResult->EOF) { \Cx\Lib\UpdateUtil::sql('UPDATE `' . DBPREFIX . 'module_newsletter_email_link` SET `url` = ? WHERE `id` = ?', array(html_entity_decode($objResult->fields['url'], ENT_QUOTES, CONTREXX_CHARSET), $objResult->fields['id'])); $objResult->MoveNext(); } } $_SESSION['contrexx_update']['newsletter_links_decoded'] = true; } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } } if ($objUpdate->_isNewerVersion($_CONFIG['coreCmsVersion'], '3.0.0')) { // add access to access ids 152/171/172/174/175/176 for user groups which had access to access id 25 try { $result = \Cx\Lib\UpdateUtil::sql("SELECT `group_id` FROM `" . DBPREFIX . "access_group_static_ids` WHERE access_id = 25 GROUP BY group_id"); if ($result !== false) { while (!$result->EOF) { \Cx\Lib\UpdateUtil::sql("INSERT IGNORE INTO `" . DBPREFIX . "access_group_static_ids` (`access_id`, `group_id`)\n VALUES\n (152, " . intval($result->fields['group_id']) . "),\n (171, " . intval($result->fields['group_id']) . "),\n (172, " . intval($result->fields['group_id']) . "),\n (174, " . intval($result->fields['group_id']) . "),\n (175, " . intval($result->fields['group_id']) . "),\n (176, " . intval($result->fields['group_id']) . ")\n "); $result->MoveNext(); } } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } } // add access id 176 for user groups which had access to 172 if version is older than 3.1.0 if ($objUpdate->_isNewerVersion($_CONFIG['coreCmsVersion'], '3.1.0')) { try { $result = \Cx\Lib\UpdateUtil::sql("SELECT `group_id` FROM `" . DBPREFIX . "access_group_static_ids` WHERE access_id = 172 GROUP BY `group_id`"); if ($result !== false) { while (!$result->EOF) { \Cx\Lib\UpdateUtil::sql("INSERT IGNORE INTO `" . DBPREFIX . "access_group_static_ids` (`access_id`, `group_id`)\n VALUES (176, " . intval($result->fields['group_id']) . ")"); $result->MoveNext(); } } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } } return true; }
/** * Fetches a json response via HTTP request * @todo Support cookies (to allow login and similiar features) * @param string $url URL to get json from * @param array $data (optional) HTTP post data * @param boolean $secure (optional) Wheter to verify peer using SSL or not, default false * @param string $certificateFile (optional) Local certificate file for non public SSL certificates * @param array Set an optional HTTP Authentication method and supply its login credentials. * The supplied array must comply with the following structure: * <pre class="brush: php"> * $httpAuth = array( * 'httpAuthMethod' => 'none|basic|disgest', * 'httpAuthUsername' => '<username>', * 'httpAuthPassword' => '<password>', * ); * </pre> * @return mixed Decoded JSON on success, false otherwise */ public function getJson($url, $data = array(), $secure = false, $certificateFile = '', $httpAuth = array(), $files = array()) { $request = new \HTTP_Request2($url, \HTTP_Request2::METHOD_POST); if (!empty($httpAuth)) { switch ($httpAuth['httpAuthMethod']) { case 'basic': $request->setAuth($httpAuth['httpAuthUsername'], $httpAuth['httpAuthPassword'], \HTTP_Request2::AUTH_BASIC); break; case 'disgest': $request->setAuth($httpAuth['httpAuthUsername'], $httpAuth['httpAuthPassword'], \HTTP_Request2::AUTH_DIGEST); break; case 'none': default: break; } } foreach ($data as $name => $value) { $request->addPostParameter($name, $value); } if (!empty($files)) { foreach ($files as $fieldId => $file) { $request->addUpload($fieldId, $file); } } if ($this->sessionId !== null) { $request->addCookie(session_name(), $this->sessionId); } $request->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false, 'follow_redirects' => true, 'strict_redirects' => true)); $response = $request->send(); //echo '<pre>';var_dump($response->getBody());echo '<br /><br />'; $cookies = $response->getCookies(); foreach ($cookies as &$cookie) { if ($cookie['name'] === session_name()) { $this->sessionId = $cookie['value']; break; } } if ($response->getStatus() != 200) { \DBG::msg(__METHOD__ . ' Request failed! Status: ' . $response->getStatus()); \DBG::msg('URL: ' . $url); \DBG::dump($data); return false; } $body = json_decode($response->getBody()); if ($body === NULL) { \DBG::msg(__METHOD__ . ' failed!'); \DBG::dump($response->getBody()); } return $body; }
/** * Validates the submitted comment data and writes it to the databse if valid. * Additionally, a notification is send out to the administration about the comment * by e-mail (only if the corresponding configuration option is set to do so). * * @param integer News message ID for which the comment shall be stored * @param string Title of the news message for which the comment shall be stored. * The title will be used in the notification e-mail * @param string The poster's name of the comment * @param string The comment's title * @param string The comment's message text * @global ADONewConnection * @global array * @global array * @global array * @return array Returns an array of two elements. The first is either TRUE on success or FALSE on failure. * The second element contains an error message on failure. */ private function storeMessageComment($newsMessageId, $newsMessageTitle, $name, $title, $message) { global $objDatabase, $_ARRAYLANG, $_CORELANG, $_CONFIG; if (!isset($_SESSION['news'])) { $_SESSION['news'] = array(); $_SESSION['news']['comments'] = array(); } // just comment if ($this->checkForCommentFlooding($newsMessageId)) { return array(false, sprintf($_ARRAYLANG['TXT_NEWS_COMMENT_INTERVAL_MSG'], $this->arrSettings['news_comments_timeout'])); } if (empty($title)) { return array(false, $_ARRAYLANG['TXT_NEWS_MISSING_COMMENT_TITLE']); } if (empty($message)) { return array(false, $_ARRAYLANG['TXT_NEWS_MISSING_COMMENT_MESSAGE']); } $date = time(); $userId = 0; if (\FWUser::getFWUserObject()->objUser->login()) { $userId = \FWUser::getFWUserObject()->objUser->getId(); $name = \FWUser::getParsedUserTitle($userId); } elseif ($this->arrSettings['news_comments_anonymous'] == '1') { // deny comment if the poster did not specify his name if (empty($name)) { return array(false, $_ARRAYLANG['TXT_NEWS_POSTER_NAME_MISSING']); } // check CAPTCHA for anonymous posters if (!\Cx\Core_Modules\Captcha\Controller\Captcha::getInstance()->check()) { return array(false, null); } } else { // Anonymous comments are not allowed return array(false, null); } $isActive = $this->arrSettings['news_comments_autoactivate']; $ipAddress = contrexx_input2raw($_SERVER['REMOTE_ADDR']); $objResult = $objDatabase->Execute("\n INSERT INTO `" . DBPREFIX . "module_news_comments` \n SET `title` = '" . contrexx_raw2db($title) . "',\n `text` = '" . contrexx_raw2db($message) . "',\n `newsid` = '" . contrexx_raw2db($newsMessageId) . "',\n `date` = '" . contrexx_raw2db($date) . "',\n `poster_name` = '" . contrexx_raw2db($name) . "',\n `userid` = '" . contrexx_raw2db($userId) . "',\n `ip_address` = '" . contrexx_raw2db($ipAddress) . "',\n `is_active` = '" . contrexx_raw2db($isActive) . "'"); if (!$objResult) { return array(false, $_ARRAYLANG['TXT_NEWS_COMMENT_SAVE_ERROR']); } /* Prevent comment flooding from same user: Either user is authenticated or had to validate a CAPTCHA. In either way, a Contrexx session had been initialized, therefore we are able to use the $_SESSION to log this comment */ $_SESSION['news']['comments'][$newsMessageId] = $date; // Don't send a notification e-mail to the administrator if (!$this->arrSettings['news_comments_notification']) { return array(true, null); } // Send a notification e-mail to administrator if (!@(include_once ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php')) { \DBG::msg('Unable to send e-mail notification to admin'); //DBG::stack(); return array(true, null); } $objMail = new \phpmailer(); if ($_CONFIG['coreSmtpServer'] > 0 && @(include_once ASCMS_CORE_PATH . '/SmtpSettings.class.php')) { if (($arrSmtp = \SmtpSettings::getSmtpAccount($_CONFIG['coreSmtpServer'])) !== false) { $objMail->IsSMTP(); $objMail->Host = $arrSmtp['hostname']; $objMail->Port = $arrSmtp['port']; $objMail->SMTPAuth = true; $objMail->Username = $arrSmtp['username']; $objMail->Password = $arrSmtp['password']; } } $objMail->CharSet = CONTREXX_CHARSET; $objMail->From = $_CONFIG['coreAdminEmail']; $objMail->FromName = $_CONFIG['coreGlobalPageTitle']; $objMail->IsHTML(false); $objMail->Subject = sprintf($_ARRAYLANG['TXT_NEWS_COMMENT_NOTIFICATION_MAIL_SUBJECT'], $newsMessageTitle); $manageCommentsUrl = ASCMS_PROTOCOL . '://' . $_CONFIG['domainUrl'] . ($_SERVER['SERVER_PORT'] == 80 ? NULL : ':' . intval($_SERVER['SERVER_PORT'])) . ASCMS_ADMIN_WEB_PATH . '/index.php?cmd=News&act=comments&newsId=' . $newsMessageId; $activateCommentTxt = $this->arrSettings['news_comments_autoactivate'] ? '' : sprintf($_ARRAYLANG['TXT_NEWS_COMMENT_NOTIFICATION_MAIL_LINK'], $manageCommentsUrl); $objMail->Body = sprintf($_ARRAYLANG['TXT_NEWS_COMMENT_NOTIFICATION_MAIL_BODY'], $_CONFIG['domainUrl'], $newsMessageTitle, \FWUser::getParsedUserTitle($userId, $name), $title, nl2br($message), $activateCommentTxt); $objMail->AddAddress($_CONFIG['coreAdminEmail']); if (!$objMail->Send()) { \DBG::msg('Sending of notification e-mail failed'); //DBG::stack(); } return array(true, null); }
/** * Cloudrexx * * @link http://www.cloudrexx.com * @copyright Cloudrexx AG 2007-2015 * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Cloudrexx" is a registered trademark of Cloudrexx AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ function _utf8Update() { global $objUpdate, $_DBCONFIG, $objDatabase, $_ARRAYLANG, $_CORELANG; $preferedCollation = 'utf8_unicode_ci'; $usedCollation = ''; $result = true; // fetch currently used collation try { $objResult = \Cx\Lib\UpdateUtil::sql('SHOW CREATE TABLE `' . DBPREFIX . 'access_users`'); if ($objResult->EOF) { setUpdateMsg(sprintf($_ARRAYLANG['TXT_UNABLE_GETTING_DATABASE_TABLE_STRUCTURE'], DBPREFIX . 'access_users')); return false; } $createStatement = $objResult->fields['Create Table']; // note: if charset latin1 is used, collation won't be set $matches = array(); if (preg_match('/COLLATE=([a-z_0-9]*)/', $createStatement, $matches)) { $usedCollation = $matches[1]; } \DBG::dump('Currently used collation: ' . $usedCollation); } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } // fetch available collations $arrCollations = _getUtf8Collations(); if (!is_array($arrCollations)) { return $arrCollations; } if (!isset($_SESSION['contrexx_update']['update']['core'])) { $_SESSION['contrexx_update']['update']['core'] = array(); } // note: $usedCollation is the currently used collation. // in case $usedCollation is non-utf8, then the following var // won't be set. This will cause the update system to ask the user // to select an utf8 collation. if (in_array($usedCollation, $arrCollations)) { $_SESSION['contrexx_update']['update']['core']['utf8_collation'] = $usedCollation; } if (isset($_DBCONFIG['charset']) && $_DBCONFIG['charset'] == 'utf8') { // do not update templates if they should be utf8 already $_SESSION['contrexx_update']['update']['utf'] = true; } // show dialog to select utf8 collation if (empty($_SESSION['contrexx_update']['update']['core']['utf8_collation'])) { if (isset($_POST['dbCollation']) && in_array($objUpdate->stripslashes($_POST['dbCollation']), $arrCollations)) { $_SESSION['contrexx_update']['update']['core']['utf8_collation'] = $objUpdate->stripslashes($_POST['dbCollation']); } else { $collationMenu = '<select name="dbCollation">'; foreach ($arrCollations as $collation) { $collationMenu .= '<option value="' . $collation . '"' . ($collation == $preferedCollation ? ' selected="selected"' : '') . '>' . $collation . '</option>'; } $collationMenu .= '</select><br />'; setUpdateMsg($_ARRAYLANG['TXT_SELECT_DB_COLLATION'], 'title'); setUpdateMsg(sprintf($_ARRAYLANG['TXT_SELECT_DB_COLLATION_MSG'] . '<br /><br />', $collationMenu), 'msg'); setUpdateMsg('<input type="submit" value="' . $_CORELANG['TXT_CONTINUE_UPDATE'] . '" name="updateNext" /><input type="hidden" name="processUpdate" id="processUpdate" />', 'button'); return false; } } // WRITE COLLATION TO CONFIG FILE IF NECESSARY if (empty($_DBCONFIG['collation'])) { \DBG::msg('New collation set in _utf8Update(): ' . $_SESSION['contrexx_update']['update']['core']['utf8_collation']); // configuration.php will get written by core.php's _writeNewConfigurationFile() $_DBCONFIG['collation'] = $_SESSION['contrexx_update']['update']['core']['utf8_collation']; // IMPORTANT! // setting result to 'charset_changed' will cause a reinitialization of the update system // to ensure that the db-connections use the proper charset/collation $result = 'charset_changed'; } // SET DATABASE CHARSET AND COLLATION try { $objDbStatement = \Cx\Lib\UpdateUtil::sql("SHOW CREATE DATABASE `" . $_DBCONFIG['database'] . "`"); if (!preg_match('#DEFAULT\\sCHARACTER\\sSET\\sutf8\\sCOLLATE\\s' . $_SESSION['contrexx_update']['update']['core']['utf8_collation'] . '#s', $objDbStatement->fields['Create Database'])) { \Cx\Lib\UpdateUtil::sql("ALTER DATABASE `" . $_DBCONFIG['database'] . "` DEFAULT CHARACTER SET utf8 COLLATE " . $objUpdate->addslashes($_SESSION['contrexx_update']['update']['core']['utf8_collation'])); } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } // CHANGE TABLE CHARSET AND COLLATION $arrContrexxTables = array(DBPREFIX . 'access_group_dynamic_ids', DBPREFIX . 'access_group_static_ids', DBPREFIX . 'access_rel_user_group', DBPREFIX . 'access_settings', DBPREFIX . 'access_users', DBPREFIX . 'access_user_attribute', DBPREFIX . 'access_user_attribute_name', DBPREFIX . 'access_user_attribute_value', DBPREFIX . 'access_user_core_attribute', DBPREFIX . 'access_user_groups', DBPREFIX . 'access_user_mail', DBPREFIX . 'access_user_network', DBPREFIX . 'access_user_profile', DBPREFIX . 'access_user_title', DBPREFIX . 'access_user_validity', DBPREFIX . 'module_block_blocks', DBPREFIX . 'module_block_categories', DBPREFIX . 'module_block_rel_lang_content', DBPREFIX . 'module_block_rel_pages', DBPREFIX . 'module_block_settings', DBPREFIX . 'module_blog_categories', DBPREFIX . 'module_blog_comments', DBPREFIX . 'module_blog_messages', DBPREFIX . 'module_blog_messages_lang', DBPREFIX . 'module_blog_message_to_category', DBPREFIX . 'module_blog_networks', DBPREFIX . 'module_blog_networks_lang', DBPREFIX . 'module_blog_settings', DBPREFIX . 'module_blog_votes', DBPREFIX . 'module_calendar', DBPREFIX . 'module_calendar_categories', DBPREFIX . 'module_calendar_form_data', DBPREFIX . 'module_calendar_form_fields', DBPREFIX . 'module_calendar_registrations', DBPREFIX . 'module_calendar_settings', DBPREFIX . 'module_calendar_style', DBPREFIX . 'module_checkout_settings_general', DBPREFIX . 'module_checkout_settings_mails', DBPREFIX . 'module_checkout_settings_yellowpay', DBPREFIX . 'module_checkout_transactions', DBPREFIX . 'module_contact_form', DBPREFIX . 'module_contact_form_data', DBPREFIX . 'module_contact_form_field', DBPREFIX . 'module_contact_form_field_lang', DBPREFIX . 'module_contact_form_lang', DBPREFIX . 'module_contact_form_submit_data', DBPREFIX . 'module_contact_recipient', DBPREFIX . 'module_contact_recipient_lang', DBPREFIX . 'module_contact_settings', DBPREFIX . 'backend_areas', DBPREFIX . 'backups', DBPREFIX . 'content_node', DBPREFIX . 'content_page', DBPREFIX . 'core_country', DBPREFIX . 'core_mail_template', DBPREFIX . 'core_setting', DBPREFIX . 'core_text', DBPREFIX . 'ids', DBPREFIX . 'languages', DBPREFIX . 'lib_country', DBPREFIX . 'log', DBPREFIX . 'log_entry', DBPREFIX . 'modules', DBPREFIX . 'module_repository', DBPREFIX . 'sessions', DBPREFIX . 'settings', DBPREFIX . 'settings_image', DBPREFIX . 'settings_smtp', DBPREFIX . 'skins', DBPREFIX . 'module_data_categories', DBPREFIX . 'module_data_messages', DBPREFIX . 'module_data_messages_lang', DBPREFIX . 'module_data_message_to_category', DBPREFIX . 'module_data_placeholders', DBPREFIX . 'module_data_settings', DBPREFIX . 'module_directory_categories', DBPREFIX . 'module_directory_dir', DBPREFIX . 'module_directory_inputfields', DBPREFIX . 'module_directory_levels', DBPREFIX . 'module_directory_mail', DBPREFIX . 'module_directory_rel_dir_cat', DBPREFIX . 'module_directory_rel_dir_level', DBPREFIX . 'module_directory_settings', DBPREFIX . 'module_directory_settings_google', DBPREFIX . 'module_directory_vote', DBPREFIX . 'module_docsys', DBPREFIX . 'module_docsys_categories', DBPREFIX . 'module_docsys_entry_category', DBPREFIX . 'module_downloads_category', DBPREFIX . 'module_downloads_category_locale', DBPREFIX . 'module_downloads_download', DBPREFIX . 'module_downloads_download_locale', DBPREFIX . 'module_downloads_group', DBPREFIX . 'module_downloads_group_locale', DBPREFIX . 'module_downloads_rel_download_category', DBPREFIX . 'module_downloads_rel_download_download', DBPREFIX . 'module_downloads_rel_group_category', DBPREFIX . 'module_downloads_settings', DBPREFIX . 'module_ecard_ecards', DBPREFIX . 'module_ecard_settings', DBPREFIX . 'module_egov_configuration', DBPREFIX . 'module_egov_orders', DBPREFIX . 'module_egov_products', DBPREFIX . 'module_egov_product_calendar', DBPREFIX . 'module_egov_product_fields', DBPREFIX . 'module_egov_settings', DBPREFIX . 'module_feed_category', DBPREFIX . 'module_feed_news', DBPREFIX . 'module_feed_newsml_association', DBPREFIX . 'module_feed_newsml_categories', DBPREFIX . 'module_feed_newsml_documents', DBPREFIX . 'module_feed_newsml_providers', DBPREFIX . 'module_filesharing', DBPREFIX . 'module_filesharing_mail_template', DBPREFIX . 'module_forum_access', DBPREFIX . 'module_forum_categories', DBPREFIX . 'module_forum_categories_lang', DBPREFIX . 'module_forum_notification', DBPREFIX . 'module_forum_postings', DBPREFIX . 'module_forum_rating', DBPREFIX . 'module_forum_settings', DBPREFIX . 'module_forum_statistics', DBPREFIX . 'module_gallery_categories', DBPREFIX . 'module_gallery_comments', DBPREFIX . 'module_gallery_language', DBPREFIX . 'module_gallery_language_pics', DBPREFIX . 'module_gallery_pictures', DBPREFIX . 'module_gallery_settings', DBPREFIX . 'module_gallery_votes', DBPREFIX . 'module_guestbook', DBPREFIX . 'module_guestbook_settings', DBPREFIX . 'module_jobs', DBPREFIX . 'module_jobs_categories', DBPREFIX . 'module_jobs_location', DBPREFIX . 'module_jobs_rel_loc_jobs', DBPREFIX . 'module_jobs_settings', DBPREFIX . 'module_knowledge_articles', DBPREFIX . 'module_knowledge_article_content', DBPREFIX . 'module_knowledge_categories', DBPREFIX . 'module_knowledge_categories_content', DBPREFIX . 'module_knowledge_settings', DBPREFIX . 'module_knowledge_tags', DBPREFIX . 'module_knowledge_tags_articles', DBPREFIX . 'module_livecam', DBPREFIX . 'module_livecam_settings', DBPREFIX . 'module_market', DBPREFIX . 'module_market_categories', DBPREFIX . 'module_market_mail', DBPREFIX . 'module_market_paypal', DBPREFIX . 'module_market_settings', DBPREFIX . 'module_market_spez_fields', DBPREFIX . 'module_media_settings', DBPREFIX . 'module_mediadir_categories', DBPREFIX . 'module_mediadir_categories_names', DBPREFIX . 'module_mediadir_comments', DBPREFIX . 'module_mediadir_entries', DBPREFIX . 'module_mediadir_forms', DBPREFIX . 'module_mediadir_form_names', DBPREFIX . 'module_mediadir_inputfields', DBPREFIX . 'module_mediadir_inputfield_names', DBPREFIX . 'module_mediadir_inputfield_types', DBPREFIX . 'module_mediadir_inputfield_verifications', DBPREFIX . 'module_mediadir_levels', DBPREFIX . 'module_mediadir_level_names', DBPREFIX . 'module_mediadir_mails', DBPREFIX . 'module_mediadir_mail_actions', DBPREFIX . 'module_mediadir_masks', DBPREFIX . 'module_mediadir_order_rel_forms_selectors', DBPREFIX . 'module_mediadir_rel_entry_categories', DBPREFIX . 'module_mediadir_rel_entry_inputfields', DBPREFIX . 'module_mediadir_rel_entry_levels', DBPREFIX . 'module_mediadir_settings', DBPREFIX . 'module_mediadir_settings_num_categories', DBPREFIX . 'module_mediadir_settings_num_entries', DBPREFIX . 'module_mediadir_settings_num_levels', DBPREFIX . 'module_mediadir_settings_perm_group_forms', DBPREFIX . 'module_mediadir_votes', DBPREFIX . 'module_memberdir_directories', DBPREFIX . 'module_memberdir_name', DBPREFIX . 'module_memberdir_settings', DBPREFIX . 'module_memberdir_values', DBPREFIX . 'module_news', DBPREFIX . 'module_news_categories', DBPREFIX . 'module_news_categories_locale', DBPREFIX . 'module_news_comments', DBPREFIX . 'module_news_locale', DBPREFIX . 'module_news_settings', DBPREFIX . 'module_news_settings_locale', DBPREFIX . 'module_news_stats_view', DBPREFIX . 'module_news_teaser_frame', DBPREFIX . 'module_news_teaser_frame_templates', DBPREFIX . 'module_news_ticker', DBPREFIX . 'module_news_types', DBPREFIX . 'module_news_types_locale', DBPREFIX . 'module_newsletter', DBPREFIX . 'module_newsletter_access_user', DBPREFIX . 'module_newsletter_attachment', DBPREFIX . 'module_newsletter_category', DBPREFIX . 'module_newsletter_confirm_mail', DBPREFIX . 'module_newsletter_email_link', DBPREFIX . 'module_newsletter_email_link_feedback', DBPREFIX . 'module_newsletter_rel_cat_news', DBPREFIX . 'module_newsletter_rel_usergroup_newsletter', DBPREFIX . 'module_newsletter_rel_user_cat', DBPREFIX . 'module_newsletter_settings', DBPREFIX . 'module_newsletter_template', DBPREFIX . 'module_newsletter_tmp_sending', DBPREFIX . 'module_newsletter_user', DBPREFIX . 'module_newsletter_user_title', DBPREFIX . 'module_podcast_category', DBPREFIX . 'module_podcast_medium', DBPREFIX . 'module_podcast_rel_category_lang', DBPREFIX . 'module_podcast_rel_medium_category', DBPREFIX . 'module_podcast_settings', DBPREFIX . 'module_podcast_template', DBPREFIX . 'module_recommend', DBPREFIX . 'module_shop_article_group', DBPREFIX . 'module_shop_attribute', DBPREFIX . 'module_shop_categories', DBPREFIX . 'module_shop_currencies', DBPREFIX . 'module_shop_customer_group', DBPREFIX . 'module_shop_discountgroup_count_name', DBPREFIX . 'module_shop_discountgroup_count_rate', DBPREFIX . 'module_shop_discount_coupon', DBPREFIX . 'module_shop_importimg', DBPREFIX . 'module_shop_lsv', DBPREFIX . 'module_shop_manufacturer', DBPREFIX . 'module_shop_option', DBPREFIX . 'module_shop_orders', DBPREFIX . 'module_shop_order_attributes', DBPREFIX . 'module_shop_order_items', DBPREFIX . 'module_shop_payment', DBPREFIX . 'module_shop_payment_processors', DBPREFIX . 'module_shop_pricelists', DBPREFIX . 'module_shop_products', DBPREFIX . 'module_shop_rel_countries', DBPREFIX . 'module_shop_rel_customer_coupon', DBPREFIX . 'module_shop_rel_discount_group', DBPREFIX . 'module_shop_rel_payment', DBPREFIX . 'module_shop_rel_product_attribute', DBPREFIX . 'module_shop_rel_shipper', DBPREFIX . 'module_shop_shipment_cost', DBPREFIX . 'module_shop_shipper', DBPREFIX . 'module_shop_vat', DBPREFIX . 'module_shop_zones', DBPREFIX . 'stats_browser', DBPREFIX . 'stats_colourdepth', DBPREFIX . 'stats_config', DBPREFIX . 'stats_country', DBPREFIX . 'stats_hostname', DBPREFIX . 'stats_javascript', DBPREFIX . 'stats_operatingsystem', DBPREFIX . 'stats_referer', DBPREFIX . 'stats_requests', DBPREFIX . 'stats_requests_summary', DBPREFIX . 'stats_screenresolution', DBPREFIX . 'stats_search', DBPREFIX . 'stats_spiders', DBPREFIX . 'stats_spiders_summary', DBPREFIX . 'stats_visitors', DBPREFIX . 'stats_visitors_summary', DBPREFIX . 'module_u2u_address_list', DBPREFIX . 'module_u2u_message_log', DBPREFIX . 'module_u2u_sent_messages', DBPREFIX . 'module_u2u_settings', DBPREFIX . 'module_u2u_user_log', DBPREFIX . 'voting_additionaldata', DBPREFIX . 'voting_email', DBPREFIX . 'voting_rel_email_system', DBPREFIX . 'voting_results', DBPREFIX . 'voting_system', DBPREFIX . 'module_feed_newsml_content_item', DBPREFIX . 'module_newsletter_system', DBPREFIX . 'module_newsletter_config', DBPREFIX . 'module_shop_shipment'); // fetch table collations try { $objInstalledTable = \Cx\Lib\UpdateUtil::sql("SHOW TABLE STATUS LIKE '" . DBPREFIX . "%'"); while (!$objInstalledTable->EOF) { $arrInstalledTables[$objInstalledTable->fields['Name']] = $objInstalledTable->fields['Collation']; $objInstalledTable->MoveNext(); } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } // remove existing constraints $arrInstalledTableNames = array_keys($arrInstalledTables); if (!isset($_SESSION['contrexx_update']['update']['core']['constraints'])) { $_SESSION['contrexx_update']['update']['core']['constraints'] = array(); } try { foreach ($arrInstalledTableNames as $table) { // fetch constraints $constraints = \Cx\Lib\UpdateUtil::get_constraints($table); // check if any constraints are set if (!count($constraints)) { continue; } // backup constraint definition (will be restored after the data has been migrated) $_SESSION['contrexx_update']['update']['core']['constraints'][$table] = $constraints; // remove constraints \Cx\Lib\UpdateUtil::set_constraints($table, array()); } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } // migrate tables to utf8 collation try { foreach ($arrContrexxTables as $table) { $converted = false; if (in_array($table, $arrInstalledTableNames)) { if ($arrInstalledTables[$table] == $_SESSION['contrexx_update']['update']['core']['utf8_collation']) { continue; } else { \DBG::msg('UTF-8: Migrate DB-Table: ' . $table); if (!in_array($table . '_new', $arrInstalledTableNames)) { $objTableStructure = \Cx\Lib\UpdateUtil::sql("SHOW CREATE TABLE `" . $table . "`"); $objTableStructure->fields['Create Table'] = preg_replace(array('/TABLE `' . $table . '/', '/collate[\\s|=][a-z0-9_]+_bin/i', '/default current_timestamp on update current_timestamp/i', '/character\\s+set[\\s|=][a-z0-9_]+/i', '/collate[\\s|=][a-z0-9_]+/i', '/default charset=[a-z0-9_]+/i'), array('TABLE `' . $table . '_new', 'BINARY', '', '', '', ''), $objTableStructure->fields['Create Table']); \Cx\Lib\UpdateUtil::sql($objTableStructure->fields['Create Table'] . " DEFAULT CHARSET=utf8 COLLATE=" . $objUpdate->addslashes($_SESSION['contrexx_update']['update']['core']['utf8_collation']) . ";\n"); } $objResult = \Cx\Lib\UpdateUtil::sql("SELECT COUNT(1) AS rowCount FROM `" . $table . "`"); $oriCount = $objResult->fields['rowCount']; $objResult = \Cx\Lib\UpdateUtil::sql("SELECT COUNT(1) AS rowCount FROM `" . $table . "_new`"); $newCount = $objResult->fields['rowCount']; if ($oriCount !== $newCount) { // migrate data \Cx\Lib\UpdateUtil::sql("TRUNCATE TABLE `" . $table . "_new`"); \Cx\Lib\UpdateUtil::sql("INSERT INTO `" . $table . "_new` SELECT * FROM `" . $table . "`"); } \Cx\Lib\UpdateUtil::sql("DROP TABLE `" . $table . "`"); $converted = true; } } if (in_array($table . '_new', $arrInstalledTableNames) || $converted) { \Cx\Lib\UpdateUtil::sql("RENAME TABLE `" . $table . "_new` TO `" . $table . "`"); } if (!checkTimeoutLimit()) { return 'timeout'; } } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } // reset constraints try { foreach ($_SESSION['contrexx_update']['update']['core']['constraints'] as $table => $constraints) { // set constraints \Cx\Lib\UpdateUtil::set_constraints($table, $constraints); } } catch (\Cx\Lib\UpdateException $e) { return \Cx\Lib\UpdateUtil::DefaultActionHandler($e); } // migrate themes to utf8 if (!isset($_SESSION['contrexx_update']['update']['utf'])) { if (_convertThemes2UTF()) { $_SESSION['contrexx_update']['update']['utf'] = true; } else { return false; } } // $result is either TRUE or 'charset_changed' in case the charset/collation has been changed return $result; }
/** * * @param Cx\Core_Modules\Listing\Model\ExportInterface $exportInterface * @param type $filename * @throws \Cx\Lib\FileSystem\FileSystemException */ public function exportToFile(\Cx\Core_Modules\Listing\Model\Entity\Exportable $exportInterface, $filename) { try { $objFile = new \Cx\Lib\FileSystem\File($filename); $objFile->touch(); $objFile->write($this->export($exportInterface)); } catch (\Cx\Lib\FileSystem\FileSystemException $e) { \DBG::msg($e->getMessage()); throw new DataSetException("Failed to export data to file {$filename}!"); } }
/** * Handle the calendar image upload * * @param string $id unique form id * * @return string image path */ function _handleUpload($fieldName, $id) { $tup = self::getTemporaryUploadPath($fieldName, $id); $tmpUploadDir = \Env::get('cx')->getWebsitePath() . $tup[1] . '/' . $tup[2] . '/'; //all the files uploaded are in here $depositionTarget = $this->uploadImgPath; //target folder $pic = ''; //move all files if (!\Cx\Lib\FileSystem\FileSystem::exists($tmpUploadDir)) { throw new \Exception("could not find temporary upload directory '{$tmpUploadDir}'"); } $h = opendir($tmpUploadDir); if ($h) { while (false !== ($f = readdir($h))) { // skip folders and thumbnails if ($f == '..' || $f == '.' || preg_match("/(?:\\.(?:thumb_thumbnail|thumb_medium|thumb_large)\\.[^.]+\$)|(?:\\.thumb)\$/i", $f)) { continue; } //do not overwrite existing files. $prefix = ''; while (file_exists($depositionTarget . $prefix . $f)) { if (empty($prefix)) { $prefix = 0; } $prefix++; } // move file try { $objFile = new \Cx\Lib\FileSystem\File($tmpUploadDir . $f); $fileInfo = pathinfo($tmpUploadDir . $f); $objFile->move($depositionTarget . $prefix . $f, false); $imageName = $prefix . $f; if (in_array($fileInfo['extension'], array('gif', 'jpg', 'jpeg', 'png'))) { $objImage = new \ImageManager(); $objImage->_createThumb($this->uploadImgPath, $this->uploadImgWebPath, $imageName, 180); } $pic = contrexx_input2raw($this->uploadImgWebPath . $imageName); // abort after one file has been fetched, as all event upload // fields do allow a single file only anyway break; } catch (\Cx\Lib\FileSystem\FileSystemException $e) { \DBG::msg($e->getMessage()); } } } return $pic; }
/** * Fixes database errors. * * @global array $_CONFIG * * @return boolean * @throws SupportException */ static function errorHandler() { global $_CONFIG; try { \Cx\Core\Setting\Controller\Setting::init('Support', '', 'Yaml'); //setup group \Cx\Core\Setting\Controller\Setting::init('Support', 'setup', 'Yaml'); if (!\Cx\Core\Setting\Controller\Setting::isDefined('faqUrl') && !\Cx\Core\Setting\Controller\Setting::add('faqUrl', 'https://www.cloudrexx.com/FAQ', 1, \Cx\Core\Setting\Controller\Setting::TYPE_TEXT, null, 'setup')) { throw new SupportException("Failed to add Setting entry for faq url"); } if (!\Cx\Core\Setting\Controller\Setting::isDefined('recipientMailAddress') && !\Cx\Core\Setting\Controller\Setting::add('recipientMailAddress', $_CONFIG['coreAdminEmail'], 2, \Cx\Core\Setting\Controller\Setting::TYPE_TEXT, null, 'setup')) { throw new SupportException("Failed to add Setting entry for recipient mail address"); } } catch (\Exception $e) { \DBG::msg($e->getMessage()); } // Always! return false; }
/** * Update values from array * * @param Array $newData */ public function updateFromArray($newData) { foreach ($newData as $key => $value) { try { call_user_func(array($this, "set" . ucfirst($key)), $value); } catch (Exception $e) { \DBG::log("\r\nskipped " . $key); } } }
/** * Get uploader code * * @param string $fieldKey uploadFieldKey * @param string $fieldName uploadFieldName * @param string $uploadCallBack upload callback function * @param boolean $allowImageOnly allow only images files * * @return string uploaderCode * @throws \Exception */ protected function getUploaderCode($fieldKey, $fieldName, $uploadCallBack = "uploadFinished", $allowImageOnly = true) { \cmsSession::getInstance(); $cx = \Cx\Core\Core\Controller\Cx::instanciate(); try { $uploader = new \Cx\Core_Modules\Uploader\Model\Entity\Uploader(); $uploaderId = $uploader->getId(); $uploadOptions = array('id' => 'calendarUploader_' . $uploaderId, 'style' => 'display: none'); if ($allowImageOnly) { $uploadOptions['allowed-extensions'] = array('gif', 'jpg', 'png', 'jpeg'); } $uploader->setCallback($fieldName . 'JsCallback'); $uploader->setUploadLimit(1); $uploader->setOptions($uploadOptions); $uploader->setFinishedCallback(array($cx->getCodeBaseModulePath() . '/Calendar/Controller/Calendar.class.php', '\\Cx\\Modules\\Calendar\\Controller\\Calendar', $uploadCallBack)); $folderWidget = new \Cx\Core_Modules\MediaBrowser\Model\Entity\FolderWidget($_SESSION->getTempPath() . '/' . $uploaderId); $this->_objTpl->setVariable(array(strtoupper($fieldName) . '_WIDGET_CODE' => $folderWidget->getXHtml(), "{$this->moduleLangVar}_" . strtoupper($fieldKey) => $uploaderId)); $strJs = <<<JAVASCRIPT {$uploader->getXHtml()} <script type="text/javascript"> cx.ready(function() { //called if user clicks on the field jQuery('#{$fieldName}').bind('click', function() { jQuery('#calendarUploader_{$uploaderId}').trigger('click'); return false; }); }); //uploader javascript callback function function {$fieldName}JsCallback(callback) { angular.element('#mediaBrowserfolderWidget_{$folderWidget->getId()}').scope().refreshBrowser(); } </script> JAVASCRIPT; return $strJs; } catch (\Exception $e) { \DBG::msg('<!-- failed initializing uploader -->'); throw new \Exception("failed initializing uploader"); } }
private function checkModRewrite() { global $_CONFIG; if ($this->_isNewerVersion('3.0.0', $_CONFIG['coreCmsVersion'])) { return true; } if (function_exists('apache_get_modules')) { $apacheModules = apache_get_modules(); $modRewrite = in_array('mod_rewrite', $apacheModules); } else { try { include_once UPDATE_LIB . '/PEAR/HTTP/Request2.php'; $request = new HTTP_Request2('http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['SCRIPT_NAME'], 0, -9) . 'rewrite_test/'); $objResponse = $request->send(); $arrHeaders = $objResponse->getHeader(); } catch (\HTTP_Request2_Exception $e) { \DBG::log($e->getMessage()); } if (empty($arrHeaders['location'])) { $modRewrite = 'warning'; } else { if (strpos($arrHeaders['location'], 'weiterleitungen_funktionieren') !== false) { $modRewrite = true; } else { $modRewrite = false; } } } return $modRewrite; }
public function setMode($mode) { if ($mode == 'frontend' || $mode == 'backend') { $this->mode = $mode; } else { \DBG::msg('URL: Invalid url mode "' . $mode . '"'); } }
/** * Handle uploads * @see Contact::_uploadFilesLegacy() * @param array $arrFields * @param boolean move should the files be moved or * do we just want an array of filenames? * defaults to false. no effect in legacy mode. * @return array A list of files that have been stored successfully in the system */ protected function _uploadFiles($arrFields, $move = false) { /* the field unique_id has been introduced with the new uploader. * it helps us to tell whether we're handling an form generated * before the new uploader using the classic input fields or * if we have to treat the files already uploaded by the uploader. */ if ($this->legacyMode) { //legacy function for old uploader return $this->_uploadFilesLegacy($arrFields); } else { //new uploader used if (!$this->hasFileField) { //nothing to do for us, no files return array(); } $arrFiles = array(); //we'll collect name => path of all files here and return this $documentRootPath = \Env::get('cx')->getWebsiteDocumentRootPath(); foreach ($arrFields as $fieldId => $arrField) { // skip non-upload fields if (!in_array($arrField['type'], array('file', 'multi_file'))) { continue; } $tup = self::getTemporaryUploadPath($this->submissionId, $fieldId); $tmpUploadDir = $tup[1] . '/' . $tup[2] . '/'; //all the files uploaded are in here $depositionTarget = ""; //target folder //on the first call, _uploadFiles is called with move=false. //this is done in order to get an array of the moved files' names, but //the files are left in place. //the second call is done with move=true - here we finally move the //files. // //the target folder is created in the first call, because if we can't //create the folder, the target path is left pointing at the path //specified by $arrSettings['fileUploadDepositionPath']. // //to remember the target folder for the second call, it is stored in //$this->depositionTarget. if (!$move) { //first call - create folder //determine where form uploads are stored $arrSettings = $this->getSettings(); $depositionTarget = $arrSettings['fileUploadDepositionPath'] . '/'; //find an unique folder name for the uploaded files $folderName = date("Ymd") . '_' . $fieldId; $suffix = ""; if (file_exists($documentRootPath . $depositionTarget . $folderName)) { $suffix = 1; while (file_exists($documentRootPath . $depositionTarget . $folderName . '-' . $suffix)) { $suffix++; } $suffix = '-' . $suffix; } $folderName .= $suffix; //try to make the folder and change target accordingly on success if (\Cx\Lib\FileSystem\FileSystem::make_folder($documentRootPath . $depositionTarget . $folderName)) { \Cx\Lib\FileSystem\FileSystem::makeWritable($documentRootPath . $depositionTarget . $folderName); $depositionTarget .= $folderName . '/'; } $this->depositionTarget[$fieldId] = $depositionTarget; } else { $depositionTarget = $this->depositionTarget[$fieldId]; } //move all files if (!\Cx\Lib\FileSystem\FileSystem::exists($tmpUploadDir)) { throw new \Cx\Core_Modules\Contact\Controller\ContactException("could not find temporary upload directory '{$tmpUploadDir}'"); } $h = opendir(\Env::get('cx')->getWebsitePath() . $tmpUploadDir); while (false !== ($f = readdir($h))) { if ($f != '..' && $f != '.') { //do not overwrite existing files. $prefix = ''; while (file_exists($documentRootPath . $depositionTarget . $prefix . $f)) { if (empty($prefix)) { $prefix = 0; } $prefix++; } if ($move) { // move file try { $objFile = new \Cx\Lib\FileSystem\File($tmpUploadDir . $f); $objFile->move($documentRootPath . $depositionTarget . $prefix . $f, false); } catch (\Cx\Lib\FileSystem\FileSystemException $e) { \DBG::msg($e->getMessage()); } } $arrFiles[$fieldId][] = array('name' => $f, 'path' => $depositionTarget . $prefix . $f); } } } //cleanup //TODO: this does not work for certain reloads - add cleanup routine //@rmdir($tmpUploadDir); return $arrFiles; } }
/** * Create a new Order * * @param integer $productId productId * @param object $objUser \User object * @param string $transactionReference transactionReference * @param array $subscriptionOptions subscriptionOptions * * @return boolean * @throws OrderRepositoryException */ public function createOrder($productId, \Cx\Modules\Crm\Model\Entity\Currency $currency, \User $objUser, $transactionReference, $subscriptionOptions = array()) { if (\FWValidator::isEmpty($productId) || \FWValidator::isEmpty($subscriptionOptions) || \FWValidator::isEmpty($transactionReference) || \FWValidator::isEmpty($currency)) { return; } $contactId = $objUser->getCrmUserId(); if (\FWValidator::isEmpty($contactId)) { return; } try { $order = new \Cx\Modules\Order\Model\Entity\Order(); $order->setContactId($contactId); $order->setCurrency($currency); $productRepository = \Env::get('em')->getRepository('Cx\\Modules\\Pim\\Model\\Entity\\Product'); $product = $productRepository->findOneBy(array('id' => $productId)); //create subscription $subscription = $order->createSubscription($product, $subscriptionOptions); // set discount price for first payment period of subscription if (!empty($subscriptionOptions['oneTimeSalePrice'])) { $subscription->setPaymentAmount($subscriptionOptions['oneTimeSalePrice']); } $order->billSubscriptions(); $invoices = $order->getInvoices(); if (!empty($invoices)) { \DBG::msg(__METHOD__ . ": order has invoices"); $paymentRepo = \Env::get('em')->getRepository('\\Cx\\Modules\\Order\\Model\\Entity\\Payment'); foreach ($invoices as $invoice) { if (!$invoice->getPaid()) { \DBG::msg(__METHOD__ . ": lookup payment with transaction-reference {$transactionReference} and amount " . $invoice->getAmount()); $payment = $paymentRepo->findOneByCriteria(array('amount' => $invoice->getAmount(), 'transactionReference' => $transactionReference, 'invoice' => null)); if ($payment) { \DBG::msg(__METHOD__ . ": payment found"); //set subscription-id to Subscription::$externalSubscriptionId if ($subscription) { \DBG::msg(__METHOD__ . ": trying to link to new subscription to the external subscription ID"); $referenceArry = explode('|', $payment->getTransactionReference()); if (isset($referenceArry[4]) && !empty($referenceArry[4])) { $subscription->setExternalSubscriptionId($referenceArry[4]); } } $transactionData = $payment->getTransactionData(); if (!\FWValidator::isEmpty($transactionData) && isset($transactionData['contact']) && isset($transactionData['contact']['id'])) { \DBG::msg(__METHOD__ . ": set externalPaymentCustomerIdProfileAttributeId of user to " . $transactionData['contact']['id']); $objUser->setProfile(array(\Cx\Core\Setting\Controller\Setting::getValue('externalPaymentCustomerIdProfileAttributeId', 'MultiSite') => array(0 => $transactionData['contact']['id'])), true); if (!$objUser->store()) { \DBG::msg('Order::createOrder() Updating user failed: ' . $objUser->getErrorMsg()); } } $invoice->addPayment($payment); $payment->setInvoice($invoice); \Env::get('em')->persist($invoice); \Env::get('em')->persist($payment); break; } } } } \Env::get('em')->persist($order); \Env::get('em')->flush(); return $order; } catch (\Exception $e) { throw new OrderRepositoryException($e->getMessage()); } }
/** * Searches the content and returns an array that is built as needed by the search module. * * @param string $searchTerm * * @return array */ public function searchResultsForSearchModule($searchTerm) { $em = \Env::get('cx')->getDb()->getEntityManager(); $pageRepo = $em->getRepository('Cx\\Core\\ContentManager\\Model\\Entity\\Page'); // only list results in case the associated page of the module is active $page = $pageRepo->findOneBy(array('module' => 'MediaDir', 'lang' => FRONTEND_LANG_ID, 'type' => \Cx\Core\ContentManager\Model\Entity\Page::TYPE_APPLICATION)); //If page is not exists or page is inactive then return empty result if (!$page || !$page->isActive()) { return array(); } //get the config site values \Cx\Core\Setting\Controller\Setting::init('Config', 'site', 'Yaml'); $coreListProtectedPages = \Cx\Core\Setting\Controller\Setting::getValue('coreListProtectedPages', 'Config'); $searchVisibleContentOnly = \Cx\Core\Setting\Controller\Setting::getValue('searchVisibleContentOnly', 'Config'); //get the config otherConfigurations value \Cx\Core\Setting\Controller\Setting::init('Config', 'otherConfigurations', 'Yaml'); $searchDescriptionLength = \Cx\Core\Setting\Controller\Setting::getValue('searchDescriptionLength', 'Config'); $hasPageAccess = true; $isNotVisible = $searchVisibleContentOnly == 'on' && !$page->isVisible(); if ($coreListProtectedPages == 'off' && $page->isFrontendProtected()) { $hasPageAccess = \Permission::checkAccess($page->getFrontendAccessId(), 'dynamic', true); } //If the page is invisible and frontend access is denied then return empty result if ($isNotVisible || !$hasPageAccess) { return array(); } //get the media directory entry by the search term $entries = new \Cx\Modules\MediaDir\Controller\MediaDirectoryEntry($this->moduleName); $entries->getEntries(null, null, null, $searchTerm); //if no entries found then return empty result if (empty($entries->arrEntries)) { return array(); } $results = array(); $formEntries = array(); $defaultEntries = null; $objForm = new \Cx\Modules\MediaDir\Controller\MediaDirectoryForm(null, $this->moduleName); $numOfEntries = intval($entries->arrSettings['settingsPagingNumEntries']); foreach ($entries->arrEntries as $entry) { $pageUrlResult = null; $entryForm = $objForm->arrForms[$entry['entryFormId']]; //Get the entry's link url //check the entry's form detail view exists if not, //check the entry's form overview exists if not, //check the default overview exists if not, dont show the corresponding entry in entry switch (true) { case $entries->checkPageCmd('detail' . $entry['entryFormId']): $pageUrlResult = \Cx\Core\Routing\Url::fromModuleAndCmd($entries->moduleName, 'detail' . $entry['entryFormId'], FRONTEND_LANG_ID, array('eid' => $entry['entryId'])); break; case $pageCmdExists = $entries->checkPageCmd($entryForm['formCmd']): case $entries->checkPageCmd(''): if ($pageCmdExists && !isset($formEntries[$entryForm['formCmd']])) { $formEntries[$entryForm['formCmd']] = new \Cx\Modules\MediaDir\Controller\MediaDirectoryEntry($entries->moduleName); $formEntries[$entryForm['formCmd']]->getEntries(null, null, null, null, null, null, 1, null, 'n', null, null, $entryForm['formId']); } if (!$pageCmdExists && !isset($defaultEntries)) { $defaultEntries = new \Cx\Modules\MediaDir\Controller\MediaDirectoryEntry($entries->moduleName); $defaultEntries->getEntries(); } //get entry's form overview / default page paging position $entriesPerPage = $numOfEntries; if ($pageCmdExists) { $entriesPerPage = !empty($entryForm['formEntriesPerPage']) ? $entryForm['formEntriesPerPage'] : $numOfEntries; } $pageCmd = $pageCmdExists ? $entryForm['formCmd'] : ''; $entryKeys = $pageCmdExists ? array_keys($formEntries[$entryForm['formCmd']]->arrEntries) : array_keys($defaultEntries->arrEntries); $entryPos = array_search($entry['entryId'], $entryKeys); $position = floor($entryPos / $entriesPerPage); $pageUrlResult = \Cx\Core\Routing\Url::fromModuleAndCmd($entries->moduleName, $pageCmd, FRONTEND_LANG_ID, array('pos' => $position * $entriesPerPage)); break; default: break; } //If page url is empty then dont show it in the result if (!$pageUrlResult) { continue; } //Get the search results title and content from the form context field 'title' and 'content' $title = current($entry['entryFields']); $content = ''; $objInputfields = new MediaDirectoryInputfield($entry['entryFormId'], false, $entry['entryTranslationStatus'], $this->moduleName); $inputFields = $objInputfields->getInputfields(); foreach ($inputFields as $arrInputfield) { $contextType = isset($arrInputfield['context_type']) ? $arrInputfield['context_type'] : ''; if (!in_array($contextType, array('title', 'content'))) { continue; } $strType = isset($arrInputfield['type_name']) ? $arrInputfield['type_name'] : ''; $strInputfieldClass = "\\Cx\\Modules\\MediaDir\\Model\\Entity\\MediaDirectoryInputfield" . ucfirst($strType); try { $objInputfield = safeNew($strInputfieldClass, $this->moduleName); $arrTranslationStatus = contrexx_input2int($arrInputfield['type_multi_lang']) == 1 ? $entry['entryTranslationStatus'] : null; $arrInputfieldContent = $objInputfield->getContent($entry['entryId'], $arrInputfield, $arrTranslationStatus); if (\Cx\Core\Core\Controller\Cx::instanciate()->getMode() == \Cx\Core\Core\Controller\Cx::MODE_FRONTEND && \Cx\Core\Setting\Controller\Setting::getValue('blockStatus', 'Config')) { $arrInputfieldContent[$this->moduleLangVar . '_INPUTFIELD_VALUE'] = preg_replace('/\\[\\[(BLOCK_[A-Z0-9_-]+)\\]\\]/', '{\\1}', $arrInputfieldContent[$this->moduleLangVar . '_INPUTFIELD_VALUE']); \Cx\Modules\Block\Controller\Block::setBlocks($arrInputfieldContent[$this->moduleLangVar . '_INPUTFIELD_VALUE'], \Cx\Core\Core\Controller\Cx::instanciate()->getPage()); } } catch (\Exception $e) { \DBG::log($e->getMessage()); continue; } $inputFieldValue = $arrInputfieldContent[$this->moduleConstVar . '_INPUTFIELD_VALUE']; if (empty($inputFieldValue)) { continue; } if ($contextType == 'title') { $title = $inputFieldValue; } elseif ($contextType == 'content') { $content = \Cx\Core_Modules\Search\Controller\Search::shortenSearchContent($inputFieldValue, $searchDescriptionLength); } } $results[] = array('Score' => 100, 'Title' => html_entity_decode(contrexx_strip_tags($title), ENT_QUOTES, CONTREXX_CHARSET), 'Content' => $content, 'Link' => $pageUrlResult->toString()); } return $results; }
public static function setLevel($level) { self::$level = $level; }