/**
  * Disconnect from a network
  *
  * @param string $oauth_provider the name of the provider to disconnect from
  */
 public function deleteNetwork($oauth_provider)
 {
     global $objDatabase;
     if (!empty($this->networks[$oauth_provider])) {
         $objDatabase->Execute("DELETE FROM `" . DBPREFIX . "access_user_network` WHERE `user_id` = " . intval($this->userId) . " AND `oauth_provider` = '" . contrexx_raw2db($oauth_provider) . "'");
         unset($this->networks[$oauth_provider]);
     }
 }
 /**
  * Update settings.
  *
  * @access      public
  * @param       array       $arrYellowpay
  */
 public function update($arrYellowpay)
 {
     foreach ($arrYellowpay as $name => $value) {
         $objResult = $this->objDatabase->Execute('
             UPDATE `' . DBPREFIX . 'module_checkout_settings_yellowpay`
             SET `value`="' . contrexx_raw2db($value) . '"
             WHERE `name`="' . $name . '"
         ');
         if (!$objResult) {
             return false;
         }
     }
     return true;
 }
 /**
  * Global search event listener
  * Appends the News search results to the search object
  *
  * @param array $eventArgs
  */
 private function SearchFindContent(array $eventArgs)
 {
     $search = current($eventArgs);
     $term_db = contrexx_raw2db($search->getTerm());
     $newsLib = new \Cx\Core_Modules\News\Controller\NewsLibrary();
     $newsLib->getSettings();
     $query = '
         SELECT
             `id`,
             `text` AS "content",
             `title`,
             `date`,
             `redirect`,
             MATCH (
                 `text`,`title`,`teaser_text`
             ) AGAINST (
                 "%' . $term_db . '%"
             ) AS `score`
         FROM
             `' . DBPREFIX . 'module_news` AS `tblN`
         INNER JOIN
             `' . DBPREFIX . 'module_news_locale` AS `nl`
         ON
             `nl`.`news_id` = `tblN`.`id`
         WHERE
             (
                `text` LIKE ("%' . $term_db . '%")
                 OR `title` LIKE ("%' . $term_db . '%")
                 OR `teaser_text` LIKE ("%' . $term_db . '%")
             )' . $newsLib->getNewsFilterQuery('tblN', '', '');
     $pageUrl = function ($pageUri, $searchData) {
         static $objNewsLib = null;
         if (!$objNewsLib) {
             $objNewsLib = new \Cx\Core_Modules\News\Controller\NewsLibrary();
         }
         if (empty($searchData['redirect'])) {
             $newsId = $searchData['id'];
             $newsCategories = $objNewsLib->getCategoriesByNewsId($newsId);
             $objUrl = \Cx\Core\Routing\Url::fromModuleAndCmd('News', $objNewsLib->findCmdById('details', array_keys($newsCategories)), FRONTEND_LANG_ID, array('newsid' => $newsId));
             $pageUrlResult = $objUrl->toString();
         } else {
             $pageUrlResult = $searchData['redirect'];
         }
         return $pageUrlResult;
     };
     $result = new \Cx\Core_Modules\Listing\Model\Entity\DataSet($search->getResultArray($query, 'News', '', $pageUrl, $search->getTerm()));
     $search->appendResult($result);
 }
 /**
  * Global search event listener
  * Appends the News search results to the search object
  * 
  * @param array $eventArgs
  */
 private function SearchFindContent(array $eventArgs)
 {
     $search = current($eventArgs);
     $term_db = contrexx_raw2db($search->getTerm());
     $query = "SELECT id, text AS content, title, date, redirect,\n               MATCH (text,title,teaser_text) AGAINST ('%{$term_db}%') AS score\n          FROM " . DBPREFIX . "module_news AS tblN\n         INNER JOIN " . DBPREFIX . "module_news_locale AS tblL ON tblL.news_id = tblN.id\n         WHERE (   text LIKE ('%{$term_db}%')\n                OR title LIKE ('%{$term_db}%')\n                OR teaser_text LIKE ('%{$term_db}%'))\n           AND lang_id=" . FRONTEND_LANG_ID . "\n           AND status=1\n           AND is_active=1\n           AND (startdate<='" . date('Y-m-d') . "' OR startdate='0000-00-00')\n           AND (enddate>='" . date('Y-m-d') . "' OR enddate='0000-00-00')";
     $pageUrl = function ($pageUri, $searchData) {
         static $objNewsLib = null;
         if (!$objNewsLib) {
             $objNewsLib = new \Cx\Core_Modules\News\Controller\NewsLibrary();
         }
         if (empty($searchData['redirect'])) {
             $newsId = $searchData['id'];
             $newsCategories = $objNewsLib->getCategoriesByNewsId($newsId);
             $objUrl = \Cx\Core\Routing\Url::fromModuleAndCmd('News', $objNewsLib->findCmdById('details', array_keys($newsCategories)), FRONTEND_LANG_ID, array('newsid' => $newsId));
             $pageUrlResult = $objUrl->toString();
         } else {
             $pageUrlResult = $searchData['redirect'];
         }
         return $pageUrlResult;
     };
     $result = new \Cx\Core_Modules\Listing\Model\Entity\DataSet($search->getResultArray($query, 'News', '', $pageUrl, $search->getTerm()));
     $search->appendResult($result);
 }
 /**
  * Fix the auto increment for the content_page table
  * Ticket #1070 in bug tracker
  *
  * The last content page have been deleted and the website was moved to another server, in this case
  * the auto increment does not match the log's last object_id. This will cause a duplicate primary key.
  */
 private function fixAutoIncrement()
 {
     $database = \Env::get('db');
     $result = $database->Execute("SELECT MAX(CONVERT(`object_id`, UNSIGNED)) AS `oldAutoIncrement`\n                                        FROM `" . DBPREFIX . "log_entry`\n                                        WHERE `object_class` = 'Cx\\\\Core\\\\ContentManager\\\\Model\\\\Entity\\\\Page'");
     if ($result === false) {
         return;
     }
     $oldAutoIncrement = $result->fields['oldAutoIncrement'] + 1;
     $result = $database->Execute("SHOW TABLE STATUS LIKE '" . DBPREFIX . "content_page'");
     if ($result !== false && $result->fields['Auto_increment'] < $oldAutoIncrement) {
         $result = $database->Execute("ALTER TABLE `" . DBPREFIX . "content_page` AUTO_INCREMENT = " . contrexx_raw2db($oldAutoIncrement));
     }
 }
Example #6
0
 /**
  * Add User in the time of adding a customer based on the account settings
  *
  * @param String  $email            user email id
  * @param String  $password         user password
  * @param Boolean $sendLoginDetails status
  *
  * @return boolean
  */
 function addUser($email, $password, $sendLoginDetails = false, $result = array(), $id)
 {
     global $objDatabase, $_CORELANG, $_ARRAYLANG;
     $settings = $this->getSettings();
     if (!isset($this->contact)) {
         $this->contact = new \Cx\Modules\Crm\Model\Entity\CrmContact();
     }
     $objFWUser = \FWUser::getFWUserObject();
     $modify = isset($this->contact->id) && !empty($this->contact->id);
     $accountId = 0;
     if (!empty($id)) {
         $objUsers = $objFWUser->objUser->getUsers($filter = array('id' => intval($id)));
         if ($objUsers) {
             $accountId = $objUsers->getId();
             $email = $objUsers->getEmail();
         }
     } else {
         if (empty($id)) {
             $objUsers = $objFWUser->objUser->getUsers($filter = array('email' => addslashes($email)));
             if ($objUsers) {
                 $accountId = $objUsers->getId();
             }
         }
     }
     if ($modify) {
         $useralExists = $objDatabase->SelectLimit("SELECT id FROM `" . DBPREFIX . "module_{$this->moduleNameLC}_contacts` WHERE user_account = {$accountId}", 1);
         if ($useralExists && !empty($useralExists->fields['id']) && !empty($accountId) && intval($useralExists->fields['id']) != $this->contact->id) {
             $existId = (int) $useralExists->fields['id'];
             $custDetails = $this->getExistCrmDetail($existId);
             $existLink = "<a href='index.php?cmd=" . $this->moduleName . "&act=customers&tpl=showcustdetail&id={$existId}' target='_blank'>{$custDetails['customer_name']} {$custDetails['contact_familyname']}</a>";
             $this->_strErrMessage = sprintf($_ARRAYLANG['TXT_CRM_CONTACT_ALREADY_EXIST_ERROR'], $existLink);
             return false;
         }
         $this->contact->account_id = $objDatabase->getOne("SELECT user_account FROM `" . DBPREFIX . "module_{$this->moduleNameLC}_contacts` WHERE id = {$this->contact->id}");
         if (empty($this->contact->account_id) && !empty($accountId)) {
             $objUser = $objFWUser->objUser->getUser($accountId);
             //            $objUser = new \User($accountId);
         } elseif ((!empty($this->contact->account_id) && ($objUser = $objFWUser->objUser->getUser($this->contact->account_id))) === false) {
             if (!empty($accountId)) {
                 $objUser = $objFWUser->objUser->getUser($accountId);
             } else {
                 $objUser = new \User();
                 $objUser->setPassword($password);
             }
         } elseif (!empty($accountId) && $useralExists && $useralExists->RecordCount() == 0) {
             $objUser = $objFWUser->objUser->getUser($accountId);
         } else {
             if ((!empty($this->contact->account_id) && ($objUser = $objFWUser->objUser->getUser($this->contact->account_id))) === true) {
                 if (empty($accountId)) {
                     $objUser = new \User();
                     $objUser->setPassword($password);
                 } else {
                     $objUser = $objFWUser->objUser->getUser($this->contact->account_id);
                 }
             } else {
                 if (empty($this->contact->account_id) && empty($accountId)) {
                     $objUser = new \User();
                     $objUser->setPassword($password);
                 }
             }
         }
     } else {
         if (empty($accountId)) {
             $objUser = new \User();
             $objUser->setPassword($password);
         } else {
             $userExists = $objDatabase->getOne("SELECT id FROM `" . DBPREFIX . "module_{$this->moduleNameLC}_contacts` WHERE user_account = {$accountId}");
             if (empty($userExists)) {
                 $objUser = $objFWUser->objUser->getUser($accountId);
             } else {
                 $custDetails = $this->getExistCrmDetail($userExists);
                 $existLink = "<a href='index.php?cmd=" . $this->moduleName . "&act=customers&tpl=showcustdetail&id={$userExists}' target='_blank'>{$custDetails['customer_name']} {$custDetails['contact_familyname']}</a>";
                 $this->_strErrMessage = sprintf($_ARRAYLANG['TXT_CRM_CONTACT_ALREADY_EXIST_ERROR'], $existLink);
                 return false;
             }
         }
     }
     //update/insert additional fields
     //company
     if (!empty($result['company'])) {
         $company = $objDatabase->getOne("SELECT customer_name FROM `" . DBPREFIX . "module_{$this->moduleNameLC}_contacts` WHERE id = '" . $result['company'] . "'");
     }
     //get default website
     foreach ($result['contactwebsite'] as $value) {
         if (!empty($value['value']) && $value['primary'] == '1') {
             $website = contrexx_raw2db($value['value']);
         }
     }
     //get default phone
     foreach ($result['contactphone'] as $value) {
         if (!empty($value['value']) && $value['primary'] == '1') {
             $phone = contrexx_input2db($value['value']);
         }
     }
     //get default address
     foreach ($result['contactAddress'] as $value) {
         if ((!empty($value['address']) || !empty($value['city']) || !empty($value['state']) || !empty($value['zip']) || !empty($value['country'])) && $value['primary'] == '1') {
             $address = contrexx_input2db($value['address']);
             $city = contrexx_input2db($value['city']);
             $zip = contrexx_input2db($value['zip']);
             $country = \Cx\Core\Country\Controller\Country::getByName($value['country']);
         }
     }
     $gender = $this->contact->contact_gender == 1 ? 'gender_female' : ($this->contact->contact_gender == 2 ? 'gender_male' : 'gender_undefined');
     $setProfileData = array('firstname' => array(0 => $this->contact->customerName), 'lastname' => array(0 => $this->contact->family_name), 'gender' => array(0 => $gender), 'website' => array(0 => $website), 'company' => array(0 => $company), 'phone_office' => array(0 => $phone), 'address' => array(0 => $address), 'city' => array(0 => $city), 'zip' => array(0 => $zip), 'country' => array(0 => $country['id']));
     //set profile picture
     $picture = $objDatabase->getOne("SELECT profile_picture FROM `" . DBPREFIX . "module_{$this->moduleNameLC}_contacts` WHERE id = '" . $this->contact->id . "'");
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     if ($picture && !empty($picture)) {
         if (!file_exists($cx->getWebsiteImagesAccessProfilePath() . '/' . $picture)) {
             $file = $cx->getWebsiteImagesCrmProfilePath() . '/';
             if (($picture = self::moveUploadedImageInToPlace($objUser, $file . $picture, $picture, true)) == true) {
                 // create thumbnail
                 if (self::createThumbnailOfImage($picture, true) !== false) {
                     $setProfileData['picture'] = array();
                     array_push($setProfileData['picture'], $picture);
                 }
             }
         }
     }
     //set group ids
     $defaultUserGroup = $settings['default_user_group'];
     $groups = $objUser->getAssociatedGroupIds();
     if (!empty($defaultUserGroup) && !in_array($defaultUserGroup, $groups)) {
         array_push($groups, $defaultUserGroup);
     }
     $objUser->setGroups($groups);
     $objUser->setUsername($email);
     $objUser->setEmail($email);
     $objUser->setFrontendLanguage($result['contact_language']);
     $objUser->setBackendLanguage($settings['customer_default_language_backend']);
     $objUser->setActiveStatus(true);
     $objUser->setProfile($setProfileData);
     if (empty($objUser->error_msg) && $objUser->store()) {
         if (empty($this->contact->account_id) && $sendLoginDetails) {
             if (trim($objUser->getProfileAttribute('gender')) == 'gender_female') {
                 $saluation = $_ARRAYLANG['TXT_CRM_SALUATION_FEMALE'];
             } else {
                 if (trim($objUser->getProfileAttribute('gender')) == 'gender_male') {
                     $saluation = $_ARRAYLANG['TXT_CRM_SALUATION_MALE'];
                 } else {
                     $saluation = $_ARRAYLANG['TXT_CRM_SALUATION'];
                 }
             }
             $info['substitution'] = array('CRM_CONTACT_FIRSTNAME' => contrexx_raw2xhtml($objUser->getProfileAttribute('firstname')), 'CRM_CONTACT_LASTNAME' => contrexx_raw2xhtml($objUser->getProfileAttribute('lastname')), 'CRM_ASSIGNED_USER_EMAIL' => $objUser->getEmail(), 'CRM_CONTACT_SALUTATION' => contrexx_raw2xhtml($saluation), 'CRM_ASSIGNED_USER_NAME' => contrexx_raw2xhtml(\FWUser::getParsedUserTitle($objUser->getId())), 'CRM_CUSTOMER_COMPANY' => $this->contact->customerName . " " . $this->contact->family_name, 'CRM_DOMAIN' => ASCMS_PROTOCOL . "://{$_SERVER['HTTP_HOST']}" . $cx->getCodeBaseOffsetPath(), 'CRM_CONTACT_EMAIL' => $email, 'CRM_CONTACT_USERNAME' => $email, 'CRM_CONTACT_PASSWORD' => $password);
             //setting email template lang id
             $availableMailTempLangAry = $this->getActiveEmailTemLangId('Crm', CRM_EVENT_ON_USER_ACCOUNT_CREATED);
             $availableLangId = $this->getEmailTempLang($availableMailTempLangAry, $email);
             $info['lang_id'] = $availableLangId;
             $dispatcher = CrmEventDispatcher::getInstance();
             $dispatcher->triggerEvent(CRM_EVENT_ON_USER_ACCOUNT_CREATED, null, $info);
         }
         $this->contact->account_id = $objUser->getId();
         return true;
     } else {
         $objUser->reset();
         $this->_strErrMessage = implode("<br />", $objUser->error_msg);
         return false;
     }
     $this->_strErrMessage = 'Some thing went wrong';
     return false;
 }
 /**
  * Get multiple themes
  * @param array $crit the criterias
  * @param array $order the order, e.g. array( 'field' => 'ASC|DESC' ) 
  * @param int $languageId filter by language id
  * @return array theme objects
  */
 public function findBy($crit = array(), $order = array(), $languageId = null)
 {
     $query = 'SELECT `id`, `themesname`, `foldername`, `expert` FROM `' . DBPREFIX . 'skins`';
     if (!empty($crit)) {
         $wheres = array();
         foreach ($crit as $field => $value) {
             $wheres[] = '`' . $field . '` = \'' . contrexx_raw2db($value) . '\'';
         }
         $query .= ' WHERE ' . implode(' AND ', $wheres);
     }
     if (!empty($order)) {
         $query .= ' ORDER BY ' . implode(',', $order);
     }
     $result = $this->db->Execute($query);
     $themes = array();
     if ($result !== false) {
         while (!$result->EOF) {
             $themes[] = $this->getTheme($result->fields['id'], $result->fields['themesname'], $result->fields['foldername'], $result->fields['expert'], $languageId);
             $result->MoveNext();
         }
     }
     return $themes;
 }
 /**
  * Reports a possible intrusion attempt to the administrator
  * @param   $type    The type of intrusion attempt to report.
  * @param   $file    The file requesting the report (defaults to "Filename not available")
  * @param   $line    The line number requesting the report (defaults to "Linenumber not available")
  **/
 function reportIntrusion($type, $file = "Filename not available", $line = "Linenumber not available")
 {
     $objDatabase = \Env::get('db');
     $config = \Env::get('config');
     $remoteaddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : "Not set";
     $httpxforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : "Not set";
     $httpvia = isset($_SERVER['HTTP_VIA']) ? $_SERVER['HTTP_VIA'] : "Not set";
     $httpclientip = isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : "Not set";
     $gethostbyname = gethostbyname($remoteaddr);
     if ($gethostbyname == $remoteaddr) {
         $gethostbyname = "No matching hostname";
     }
     // Add all the user's info to $user
     $user = "******" . "HTTP_X_FORWARDED_FOR : {$httpxforwardedfor}\r\n" . "HTTP_VIA : {$httpvia}\r\n" . "HTTP_CLIENT_IP : {$httpclientip}\r\n" . "GetHostByName : {$gethostbyname}\r\n";
     // Add all requested information
     foreach ($this->criticalServerVars as $serverVar) {
         $_SERVERlite[$serverVar] = $_SERVER[$serverVar];
     }
     $httpheaders = function_exists('getallheaders') ? getallheaders() : null;
     $gpcs = "";
     $gpcs .= $this->getRequestInfo($httpheaders, "HTTP HEADER");
     $gpcs .= $this->getRequestInfo($_REQUEST, "REQUEST");
     $gpcs .= $this->getRequestInfo($_GET, "GET");
     $gpcs .= $this->getRequestInfo($_POST, "POST");
     $gpcs .= $this->getRequestInfo($_SERVERlite, "SERVER");
     $gpcs .= $this->getRequestInfo($_COOKIE, "COOKIE");
     $gpcs .= $this->getRequestInfo($_FILES, "FILES");
     $gpcs .= $this->getRequestInfo($_SESSION, "SESSION");
     // Get the data to insert in the database
     $cdate = time();
     $dbuser = htmlspecialchars(addslashes($user), ENT_QUOTES, CONTREXX_CHARSET);
     $dbuser = contrexx_raw2db($dbuser);
     $dbgpcs = htmlspecialchars(addslashes($gpcs), ENT_QUOTES, CONTREXX_CHARSET);
     $dbgpcs = contrexx_raw2db($dbgpcs);
     $where = addslashes("{$file} : {$line}");
     $where = contrexx_raw2db($where);
     // Insert the intrusion in the database
     $objDatabase->Execute("INSERT INTO " . DBPREFIX . "ids (timestamp, type, remote_addr, http_x_forwarded_for, http_via, user, gpcs, file)\n                VALUES(" . $cdate . ", '" . $type . "', '" . $remoteaddr . "', '" . $httpxforwardedfor . "', '" . $httpvia . "', '" . $dbuser . "', '" . $dbgpcs . "', '" . $where . "')");
     // The headers for the e-mail
     $emailto = $config['coreAdminName'] . " <" . $config['coreAdminEmail'] . ">";
     // The message to send
     $message = "DATE : {$cdate}\r\nFILE : {$where}\r\n\r\n{$user}\r\n\r\n{$gpcs}";
     // Send the e-mail to the administrator
     if (\Env::get('ClassLoader')->loadFile(ASCMS_LIBRARY_PATH . '/phpmailer/class.phpmailer.php')) {
         $objMail = new \phpmailer();
         if ($config['coreSmtpServer'] > 0 && \Env::get('ClassLoader')->loadFile(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->SetFrom($config['coreAdminEmail'], $config['coreAdminName']);
         $objMail->Subject = $_SERVER['HTTP_HOST'] . " : {$type}";
         $objMail->IsHTML(false);
         $objMail->Body = $message;
         $objMail->AddAddress($emailto);
         $objMail->Send();
     }
 }
Example #9
0
 /**
  * show thread
  *
  * @param integer $intThreadId
  * @return bool
  */
 function showThread($intThreadId)
 {
     global $objDatabase, $_ARRAYLANG;
     $objFWUser = \FWUser::getFWUserObject();
     $this->_communityLogin();
     $intThreadId = intval($intThreadId);
     if (!empty($_REQUEST['notification_update']) && $_REQUEST['notification_update'] == $_ARRAYLANG['TXT_FORUM_UPDATE_NOTIFICATION']) {
         $this->_updateNotification($intThreadId);
     }
     $intCatId = !empty($_REQUEST['category_id']) ? intval($_REQUEST['category_id']) : '0';
     if ($intCatId == 0) {
         $intCatId = $this->_getCategoryIdFromThread($intThreadId);
     }
     if (empty($intCatId)) {
         \Cx\Core\Csrf\Controller\Csrf::header('Location: index.php?section=Forum');
         die;
     }
     if ($objFWUser->objUser->login()) {
         $this->_objTpl->touchBlock('notificationRow');
     } else {
         $this->_objTpl->hideBlock('notificationRow');
     }
     $intPostId = !empty($_REQUEST['postid']) ? intval($_REQUEST['postid']) : 0;
     $intPostId = $intPostId == 0 && !empty($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : $intPostId;
     $this->_objTpl->setVariable('FORUM_EDIT_POST_ID', $intPostId);
     $_REQUEST['act'] = !empty($_REQUEST['act']) ? $_REQUEST['act'] : '';
     if ($_REQUEST['act'] == 'delete') {
         if ($this->_checkAuth($intCatId, 'delete')) {
             if ($this->_deletePost($intCatId, $intThreadId, $_REQUEST['postid'])) {
                 $this->_objTpl->setVariable('TXT_FORUM_SUCCESS', '<br />' . $_ARRAYLANG['TXT_FORUM_DELETED_SUCCESSFULLY']);
             } else {
                 $this->_objTpl->setVariable('TXT_FORUM_ERROR', '<br />' . $_ARRAYLANG['TXT_FORUM_DELETE_FAILED']);
             }
         } else {
             $this->_objTpl->setVariable('TXT_FORUM_ERROR', '<br />' . $_ARRAYLANG['TXT_FORUM_NO_ACCESS']);
         }
     }
     $pos = !empty($_REQUEST['pos']) ? intval($_REQUEST['pos']) : 0;
     $this->_objTpl->setVariable(array('FORUM_PAGING_POS' => $pos));
     if (!empty($_REQUEST['preview_new'])) {
         $pos = $this->_getLastPos($intPostId, $intThreadId);
     }
     if (!empty($_REQUEST['postid'])) {
         if ($_REQUEST['act'] == 'quote') {
             $pos = $this->_getLastPos($intPostId, $intThreadId);
         }
         if ($_REQUEST['act'] == 'edit') {
             $pos = $this->_getEditPos($intPostId, $intThreadId);
         }
     }
     if (!empty($_REQUEST['l']) && $_REQUEST['l'] == 1) {
         $pos = $this->_getEditPos($intPostId, $intThreadId);
     }
     $arrPosts = $this->createPostArray($intThreadId, $pos);
     if (!empty($_REQUEST['preview_edit']) && $_REQUEST['post_id'] != 0 && $_REQUEST['act'] != 'quote') {
         $intPostId = intval($intPostId);
         $pos = $this->_getEditPos($intPostId, $intThreadId);
         $arrPosts = $this->createPostArray($intThreadId, $pos);
         $arrPosts[$intPostId]['subject'] = !empty($_REQUEST['subject']) ? contrexx_strip_tags($_REQUEST['subject']) : $_ARRAYLANG['TXT_FORUM_NO_SUBJECT'];
         $arrPosts[$intPostId]['content'] = \Cx\Core\Wysiwyg\Wysiwyg::prepareBBCodeForOutput(contrexx_input2raw($_REQUEST['message']));
     }
     $userId = $objFWUser->objUser->login() ? $objFWUser->objUser->getId() : 0;
     $icon = !empty($_REQUEST['icons']) ? intval($_REQUEST['icons']) : 1;
     if ($_REQUEST['act'] == 'edit') {
         //submit is an edit
         $arrEditedPost = $this->_getPostingData($intPostId);
         $subject = addcslashes(htmlentities($arrEditedPost['subject'], ENT_QUOTES, CONTREXX_CHARSET), '\\');
         $content = $arrEditedPost['content'];
         $keywords = addcslashes(htmlentities($arrEditedPost['keywords'], ENT_QUOTES, CONTREXX_CHARSET), '\\');
         $attachment = $arrEditedPost['attachment'];
         $this->_objTpl->setVariable('FORUM_POST_EDIT_USERID', $arrPosts[$intPostId]['user_id']);
         if (!empty($attachment)) {
             $this->_objTpl->setVariable('TXT_FORUM_DELETE_ATTACHMENT', sprintf($_ARRAYLANG['TXT_FORUM_DELETE_ATTACHMENT'], $attachment));
         }
         $this->_objTpl->touchBlock('updatePost');
         $this->_objTpl->hideBlock('createPost');
         $this->_objTpl->hideBlock('previewNewPost');
         $this->_objTpl->touchBlock('previewEditPost');
     } else {
         //new post
         if ($this->_objTpl->blockExists('delAttachment')) {
             $this->_objTpl->hideBlock('delAttachment');
         }
         $subject = !empty($_REQUEST['subject']) ? contrexx_strip_tags($_REQUEST['subject']) : '';
         $content = !empty($_REQUEST['message']) ? contrexx_input2raw(strip_tags($_REQUEST['message'])) : '';
         $keywords = !empty($_REQUEST['keywords']) ? contrexx_strip_tags($_REQUEST['keywords']) : '';
         $attachment = !empty($_REQUEST['attachment']) ? contrexx_strip_tags($_REQUEST['attachment']) : '';
         $this->_objTpl->touchBlock('createPost');
         $this->_objTpl->hideBlock('updatePost');
         $this->_objTpl->touchBlock('previewNewPost');
         $this->_objTpl->hideBlock('previewEditPost');
     }
     if ($_REQUEST['act'] == 'quote') {
         $quoteContent = $this->_getPostingData($intPostId);
         $subject = 'RE: ' . addcslashes(htmlentities($quoteContent['subject'], ENT_QUOTES, CONTREXX_CHARSET), '\\');
         $content = '[quote=' . $arrPosts[$intPostId]['user_name'] . ']' . strip_tags($quoteContent['content']) . '[/quote]';
     }
     $firstPost = current($arrPosts);
     if ($this->_arrSettings['wysiwyg_editor'] == 1) {
         //IF WYSIWIG enabled..
         $strMessageInputHTML = new \Cx\Core\Wysiwyg\Wysiwyg('message', $content, 'bbcode');
     } else {
         //plain textarea
         $strMessageInputHTML = '<textarea style="width: 400px; height: 150px;" rows="5" cols="10" name="message">' . contrexx_raw2xhtml($content) . '</textarea>';
     }
     $this->_objTpl->setGlobalVariable(array('FORUM_JAVASCRIPT_GOTO' => $this->getJavascript('goto'), 'FORUM_JAVASCRIPT_DELETE' => $this->getJavascript('deletePost'), 'FORUM_JAVASCRIPT_SCROLLTO' => $this->getJavascript('scrollto'), 'FORUM_SCROLLPOS' => !empty($_REQUEST['scrollpos']) ? intval($_REQUEST['scrollpos']) : '0', 'FORUM_JAVASCRIPT_INSERT_TEXT' => $this->getJavascript('insertText', array($intCatId, $intThreadId, $firstPost)), 'FORUM_NAME' => $this->_shortenString($firstPost['subject'], $this->_maxStringlength), 'FORUM_TREE' => $this->_createNavTree($intCatId) . '<a title="' . $this->_arrTranslations[$intCatId][$this->_intLangId]['name'] . '" href="index.php?section=Forum&amp;cmd=board&amp;id=' . $intCatId . '">' . $this->_shortenString($this->_arrTranslations[$intCatId][$this->_intLangId]['name'], $this->_maxStringlength) . '</a> > ', 'FORUM_DROPDOWN' => $this->createForumDD('forum_quickaccess', $intCatId, 'onchange="gotoForum(this);"', ''), 'TXT_FORUM_COMMA_SEPARATED_KEYWORDS' => $_ARRAYLANG['TXT_FORUM_COMMA_SEPARATED_KEYWORDS'], 'TXT_FORUM_KEYWORDS' => $_ARRAYLANG['TXT_FORUM_KEYWORDS'], 'TXT_FORUM_FILE_ATTACHMENT' => $_ARRAYLANG['TXT_FORUM_FILE_ATTACHMENT'], 'TXT_FORUM_RATING' => $_ARRAYLANG['TXT_FORUM_RATING'], 'TXT_FORUM_ADD_POST' => $_ARRAYLANG['TXT_FORUM_ADD_POST'], 'TXT_FORUM_SUBJECT' => $_ARRAYLANG['TXT_FORUM_SUBJECT'], 'TXT_FORUM_MESSAGE' => $_ARRAYLANG['TXT_FORUM_MESSAGE'], 'TXT_FORUM_RESET' => $_ARRAYLANG['TXT_FORUM_RESET'], 'TXT_FORUM_CREATE_POST' => $_ARRAYLANG['TXT_FORUM_CREATE_POST'], 'TXT_FORUM_ICON' => $_ARRAYLANG['TXT_FORUM_ICON'], 'TXT_FORUM_QUOTE' => $_ARRAYLANG['TXT_FORUM_QUOTE'], 'TXT_FORUM_EDIT' => $_ARRAYLANG['TXT_FORUM_EDIT'], 'TXT_FORUM_DELETE' => $_ARRAYLANG['TXT_FORUM_DELETE'], 'TXT_FORUM_PREVIEW' => $_ARRAYLANG['TXT_FORUM_PREVIEW'], 'TXT_FORUM_UPDATE_POST' => $_ARRAYLANG['TXT_FORUM_UPDATE_POST'], 'TXT_FORUM_NOTIFY_NEW_POSTS' => $_ARRAYLANG['TXT_FORUM_NOTIFY_NEW_POSTS'], 'TXT_FORUM_QUICKACCESS' => $_ARRAYLANG['TXT_FORUM_QUICKACCESS'], 'TXT_FORUM_UPDATE_NOTIFICATION' => $_ARRAYLANG['TXT_FORUM_UPDATE_NOTIFICATION'], 'TXT_FORUM_THREAD_ACTION_DESC' => $_ARRAYLANG['TXT_FORUM_THREAD_ACTION_DESC'], 'TXT_FORUM_THREAD_ACTION_MOVE' => $_ARRAYLANG['TXT_FORUM_THREAD_ACTION_MOVE'], 'TXT_FORUM_THREAD_ACTION_CLOSE' => $_ARRAYLANG['TXT_FORUM_THREAD_ACTION_CLOSE_' . $firstPost['is_locked']], 'TXT_FORUM_THREAD_ACTION_STICKY' => $_ARRAYLANG['TXT_FORUM_THREAD_ACTION_STICKY_' . $firstPost['is_sticky']], 'TXT_FORUM_THREAD_ACTION_DELETE' => $_ARRAYLANG['TXT_FORUM_THREAD_ACTION_DELETE'], 'TXT_FORUM_CHOOSE_FILE' => $_ARRAYLANG['TXT_FORUM_CHOOSE_FILE'], 'FORUM_NOTIFICATION_CHECKBOX_CHECKED' => $this->_hasNotification($intThreadId) ? 'checked="checked"' : '', 'FORUM_SUBJECT' => stripslashes($subject), 'FORUM_KEYWORDS' => stripslashes($keywords), 'FORUM_ATTACHMENT_OLDNAME' => $attachment, 'FORUM_MESSAGE_INPUT' => $strMessageInputHTML, 'FORUM_CAPTCHA_CODE' => \Cx\Core_Modules\Captcha\Controller\Captcha::getInstance()->getCode(), 'FORUM_THREAD_ID' => $intThreadId, 'FORUM_CATEGORY_ID' => $intCatId, 'FORUM_POSTS_PAGING' => getPaging($this->_postCount, $pos, '&section=Forum&cmd=thread&id=' . $intThreadId, $_ARRAYLANG['TXT_FORUM_OVERVIEW_POSTINGS'], true, $this->_arrSettings['posting_paging'])));
     if ($objFWUser->objUser->login()) {
         $this->_objTpl->hideBlock('captcha');
     } else {
         $this->_objTpl->touchBlock('captcha');
     }
     $this->_setIcons($this->_getIcons());
     if (!$this->_checkAuth($intCatId, 'read')) {
         $this->_objTpl->setVariable('TXT_FORUM_ERROR', '<br />' . $_ARRAYLANG['TXT_FORUM_NO_ACCESS']);
         return false;
     }
     $intCounter = 0;
     foreach ($arrPosts as $postId => $arrValues) {
         $strRating = '<span id="forum_current_rating_' . $postId . '" class="rating_%s">%s</span>';
         if ($arrValues['rating'] == 0) {
             $class = 'none';
         } elseif ($arrValues['rating'] > 0) {
             $class = 'pos';
         } else {
             $class = 'neg';
         }
         $strRating = sprintf($strRating, $class, $arrValues['rating']);
         $strUserProfileLink = $arrValues['user_id'] > 0 ? '<a title="' . $arrValues['user_name'] . '" href="index.php?section=Access&amp;cmd=user&amp;id=' . $arrValues['user_id'] . '">' . $arrValues['user_name'] . '</a>' : $this->_anonymousName;
         $arrAttachment = $this->_getAttachment($arrValues['attachment']);
         $this->_objTpl->setGlobalVariable(array('FORUM_POST_ROWCLASS' => $intCounter++ % 2 + 1));
         $quoteLink = "id=" . $intThreadId . "&act=quote&postid=" . $postId;
         $quoteLinkLoggedIn = "location.href='" . \Cx\Core\Csrf\Controller\Csrf::enhanceURI("index.php?section=Forum") . "&amp;cmd=thread&amp;" . htmlentities($quoteLink) . "';";
         $quoteLinkNotLoggedIn = "location.href='" . \Cx\Core\Csrf\Controller\Csrf::enhanceURI("index.php?section=Login") . "&amp;redirect=" . base64_encode("index.php?section=Forum&cmd=thread&" . $quoteLink) . "';";
         $this->_objTpl->setVariable(array('FORUM_POST_DATE' => $arrValues['time_created'], 'FORUM_POST_LAST_EDITED' => $arrValues['time_edited'] != date(ASCMS_DATE_FORMAT, 0) ? $_ARRAYLANG['TXT_FORUM_LAST_EDITED'] . $arrValues['time_edited'] : '', 'FORUM_USER_ID' => $arrValues['user_id'], 'FORUM_USER_NAME' => $strUserProfileLink, 'FORUM_USER_IMAGE' => !empty($arrValues['user_image']) ? '<img border="0" width="60" height="60" src="' . $arrValues['user_image'] . '" title="' . $arrValues['user_name'] . '\'s avatar" alt="' . $arrValues['user_name'] . '\'s avatar" />' : '', 'FORUM_USER_GROUP' => '', 'FORUM_USER_RANK' => '', 'FORUM_USER_REGISTERED_SINCE' => '', 'FORUM_USER_POSTING_COUNT' => '', 'FORUM_USER_CONTACTS' => '', 'FORUM_POST_NUMBER' => '#' . $arrValues['post_number'], 'FORUM_POST_ICON' => $arrValues['post_icon'], 'FORUM_POST_SUBJECT' => $arrValues['subject'], 'FORUM_POST_MESSAGE' => $arrValues['content'], 'FORUM_POST_RATING' => $strRating, 'FORUM_POST_ATTACHMENT_LINK' => $arrAttachment['webpath'], 'FORUM_POST_ATTACHMENT_FILENAME' => $arrAttachment['name'], 'FORUM_POST_ATTACHMENT_ICON' => $arrAttachment['icon'], 'FORUM_POST_ATTACHMENT_FILESIZE' => $arrAttachment['size'], 'FORUM_QUOTE_ONCLICK' => $this->_checkAuth($intCatId, 'write') ? $quoteLinkLoggedIn : $quoteLinkNotLoggedIn));
         if (!$objFWUser->objUser->login() && !$this->_checkAuth($intCatId, 'write')) {
             $button = '<input type="button" value="' . $_ARRAYLANG['TXT_FORUM_CREATE_POST'] . '" onclick="location.href=\'' . \Cx\Core\Csrf\Controller\Csrf::enhanceURI('index.php?section=Login') . '&redirect=' . base64_encode($_SERVER['REQUEST_URI']) . '\';" />';
             $this->_objTpl->setVariable(array('FORUM_POST_REPLY_REDIRECT' => $button));
         }
         $this->_objTpl->setVariable(array('FORUM_POST_ID' => $postId, 'FORUM_RATING_POST_ID' => $postId));
         if ($firstPost['is_locked'] != 1 && ($this->_checkAuth($intCatId, 'edit') || $objFWUser->objUser->login() && $arrValues['user_id'] == $objFWUser->objUser->getId())) {
             $this->_objTpl->touchBlock('postEdit');
         } else {
             $this->_objTpl->hideBlock('postEdit');
         }
         if ($firstPost['is_locked'] != 1 && ($this->_checkAuth($intCatId, 'write') || !$firstPost['is_locked'])) {
             $this->_objTpl->touchBlock('postQuote');
         } else {
             $this->_objTpl->hideBlock('postQuote');
         }
         if ($this->_checkAuth($intCatId, 'delete') && $arrValues['post_number'] != 1) {
             $this->_objTpl->setVariable(array('FORUM_POST_ID' => $postId));
             $this->_objTpl->touchBlock('postDelete');
         } else {
             $this->_objTpl->hideBlock('postDelete');
         }
         if ($this->_objTpl->blockExists('rating')) {
             if ($objFWUser->objUser->login() && !$this->_hasRated($postId)) {
                 $this->_objTpl->parse('rating');
             } else {
                 $this->_objTpl->hideBlock('rating');
             }
         }
         if ($this->_objTpl->blockExists('attachment')) {
             if (!empty($arrValues['attachment'])) {
                 $this->_objTpl->parse('attachment');
             } else {
                 $this->_objTpl->hideBlock('attachment');
             }
         }
         $this->_objTpl->parse('forumPosts');
     }
     if (!$this->_checkAuth($intCatId, 'write') || $firstPost['is_locked'] == 1) {
         $this->_objTpl->hideBlock('addPost');
         $this->_objTpl->hideBlock('addPostAnchor');
     } else {
         $this->_objTpl->touchBlock('addPostAnchor');
     }
     // initialize the uploader
     $this->initForumUploader();
     //addpost code
     if (!empty($_REQUEST['create']) && $_REQUEST['create'] == $_ARRAYLANG['TXT_FORUM_CREATE_POST']) {
         if (!$this->_checkAuth($intCatId, 'write') && $firstPost['is_locked'] != 1) {
             //auth check
             $this->_objTpl->setVariable('TXT_FORUM_ERROR', '<br />' . $_ARRAYLANG['TXT_FORUM_NO_ACCESS']);
             $this->_objTpl->hideBlock('addPost');
             return false;
         }
         if (!$objFWUser->objUser->login() && !\Cx\Core_Modules\Captcha\Controller\Captcha::getInstance()->check()) {
             //captcha check
             return false;
         }
         if (strlen(trim($content)) < $this->_minPostlength) {
             //content check
             $this->_objTpl->setVariable('TXT_FORUM_ERROR', sprintf('<br />' . $_ARRAYLANG['TXT_FORUM_POST_EMPTY'], $this->_minPostlength));
             return false;
         }
         if (false !== ($match = $this->_hasBadWords($content))) {
             $this->_objTpl->setVariable('TXT_FORUM_ERROR', sprintf('<br />' . $_ARRAYLANG['TXT_FORUM_BANNED_WORD'], $match[1]));
             return false;
         }
         $fileInfo = $this->_handleUpload('forum_attachment');
         if ($fileInfo === false) {
             //an error occured, the file wasn't properly transferred. exit function to display error set in _handleUpload()
             return false;
         }
         $lastPostIdQuery = '    SELECT max( id ) as last_post_id
                                 FROM ' . DBPREFIX . 'module_forum_postings
                                 WHERE category_id = ' . $intCatId . '
                                 AND      thread_id = ' . $intThreadId;
         if (($objRSmaxId = $objDatabase->SelectLimit($lastPostIdQuery, 1)) !== false) {
             $intPrevPostId = $objRSmaxId->fields['last_post_id'];
         } else {
             die('Database error: ' . $objDatabase->ErrorMsg());
         }
         $insertQuery = 'INSERT INTO ' . DBPREFIX . 'module_forum_postings (
                         id,             category_id,    thread_id,            prev_post_id,
                         user_id,         time_created,    time_edited,         is_locked,
                         is_sticky,         rating,         views,                 icon,
                         keywords,        subject,        content,             attachment
                     ) VALUES (
                         NULL, ' . $intCatId . ', ' . $intThreadId . ', ' . $intPrevPostId . ',
                         ' . $userId . ', ' . time() . ',         0,                     0,
                         0,                   0,        0, ' . $icon . ",\n                            '{$keywords}' ,'" . $subject . "',    '" . contrexx_raw2db($content) . "', '" . $fileInfo['name'] . "'\n                        )";
         if ($objDatabase->Execute($insertQuery) !== false) {
             $lastInsertId = $objDatabase->Insert_ID();
             $this->updateViewsNewItem($intCatId, $lastInsertId, true);
             $this->_updateNotification($intThreadId);
             $this->_sendNotifications($intThreadId, $subject, $content);
             $pageId = \Cx\Core\Core\Controller\Cx::instanciate()->getPage()->getId();
             $cacheManager = new \Cx\Core_Modules\Cache\Controller\CacheManager();
             $cacheManager->deleteSingleFile($pageId);
         }
         \Cx\Core\Csrf\Controller\Csrf::header('Location: index.php?section=Forum&cmd=thread&id=' . $intThreadId . '&pos=' . $this->_getLastPos($postId, $intThreadId));
         die;
     }
     if (!empty($_REQUEST['preview_new'])) {
         $content = \Cx\Core\Wysiwyg\Wysiwyg::prepareBBCodeForOutput($content);
         if (false !== ($match = $this->_hasBadWords($content))) {
             $this->_objTpl->setVariable('TXT_FORUM_ERROR', sprintf('<br />' . $_ARRAYLANG['TXT_FORUM_BANNED_WORD'], $match[1]));
             return false;
         }
         if (strlen(trim($content)) < $this->_minPostlength) {
             //content check
             $this->_objTpl->setVariable('TXT_FORUM_ERROR', sprintf('<br />' . $_ARRAYLANG['TXT_FORUM_POST_EMPTY'], $this->_minPostlength));
             return false;
         }
         $this->_objTpl->setVariable(array('FORUM_POST_ROWCLASS' => $intCounter++ % 2 + 1, 'FORUM_POST_DATE' => date(ASCMS_DATE_FORMAT, time()), 'FORUM_USER_ID' => $userId, 'FORUM_USER_NAME' => $objFWUser->objUser->login() ? '<a href="index.php?section=Access&amp;cmd=user&amp;id=' . $userId . '" title="' . htmlentities($objFWUser->objUser->getUsername(), ENT_QUOTES, CONTREXX_CHARSET) . '">' . htmlentities($objFWUser->objUser->getUsername(), ENT_QUOTES, CONTREXX_CHARSET) . '</a>' : $this->_anonymousName, 'FORUM_USER_IMAGE' => !empty($arrValues['user_image']) ? '<img border="0" width="60" height="60" src="' . $arrValues['user_image'] . '" title="' . $arrValues['user_name'] . '\'s avatar" alt="' . $arrValues['user_name'] . '\'s avatar" />' : '', 'FORUM_USER_GROUP' => '', 'FORUM_USER_RANK' => '', 'FORUM_USER_REGISTERED_SINCE' => '', 'FORUM_USER_POSTING_COUNT' => '', 'FORUM_USER_CONTACTS' => '', 'FORUM_POST_NUMBER' => '#' . ($this->_postCount + 1), 'FORUM_POST_ICON' => $this->getThreadIcon($icon), 'FORUM_POST_SUBJECT' => stripslashes($subject), 'FORUM_POST_MESSAGE' => $content, 'FORUM_POST_RATING' => '0'));
         $this->_objTpl->touchBlock('createPost');
         $this->_objTpl->hideBlock('updatePost');
         if ($this->_objTpl->blockExists('attachment')) {
             $this->_objTpl->hideBlock('attachment');
         }
         $this->_objTpl->hideBlock('postEdit');
         $this->_objTpl->hideBlock('postQuote');
         $this->_objTpl->touchBlock('previewNewPost');
         $this->_objTpl->hideBlock('previewEditPost');
         $this->_objTpl->parse('forumPosts');
     }
     if (!empty($_REQUEST['update']) && $_REQUEST['update'] == $_ARRAYLANG['TXT_FORUM_UPDATE_POST']) {
         if (strlen(trim($content)) < $this->_minPostlength) {
             //content size check
             $this->_objTpl->setVariable('TXT_FORUM_ERROR', sprintf('<br />' . $_ARRAYLANG['TXT_FORUM_POST_EMPTY'], $this->_minPostlength));
             return false;
         }
         if (!$this->_checkAuth($intCatId, 'edit') && (!$objFWUser->objUser->login() || $arrValues['user_id'] != $objFWUser->objUser->getId())) {
             $this->_objTpl->setVariable('TXT_FORUM_ERROR', '<br />' . $_ARRAYLANG['TXT_FORUM_NO_ACCESS']);
             $this->_objTpl->hideBlock('postEdit');
             return false;
         }
         if (!$objFWUser->objUser->login() && !\Cx\Core_Modules\Captcha\Controller\Captcha::getInstance()->check()) {
             $this->_objTpl->touchBlock('updatePost');
             $this->_objTpl->hideBlock('createPost');
             return false;
         }
         if (false !== ($match = $this->_hasBadWords($content))) {
             $this->_objTpl->setVariable('TXT_FORUM_ERROR', sprintf('<br />' . $_ARRAYLANG['TXT_FORUM_BANNED_WORD'], $match[1]));
             return false;
         }
         $fileInfo = $this->_handleUpload('forum_attachment');
         if ($fileInfo === false) {
             //an error occured, the file wasn't properly transferred. exit function to display error set in _handleUpload()
             return false;
         }
         if (empty($_POST['forum_delete_attachment']) && empty($fileInfo['name']) && !empty($_REQUEST['forum_attachment_oldname'])) {
             $fileInfo['name'] = contrexx_addslashes($_REQUEST['forum_attachment_oldname']);
         } elseif (!empty($_POST['forum_delete_attachment']) && $_POST['forum_delete_attachment'] == 1 || !empty($_REQUEST['forum_attachment_oldname']) && $fileInfo['name'] != $_REQUEST['forum_attachment_oldname']) {
             unlink(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteMediaForumUploadPath() . '/' . str_replace(array('./', '.\\'), '', $_REQUEST['forum_attachment_oldname']));
         }
         $updateQuery = 'UPDATE ' . DBPREFIX . 'module_forum_postings SET
                         time_edited = ' . mktime() . ',
                         icon = ' . $icon . ',
                         subject = \'' . $subject . '\',
                         keywords = \'' . $keywords . '\',
                         content = \'' . contrexx_raw2db($content) . '\',
                         attachment = \'' . $fileInfo['name'] . '\'
                         WHERE id = ' . $intPostId;
         if ($objDatabase->Execute($updateQuery) !== false) {
             $this->updateViews($intThreadId, $intPostId);
             $pageId = \Cx\Core\Core\Controller\Cx::instanciate()->getPage()->getId();
             $cacheManager = new \Cx\Core_Modules\Cache\Controller\CacheManager();
             $cacheManager->deleteSingleFile($pageId);
         }
         \Cx\Core\Csrf\Controller\Csrf::header('Location: index.php?section=Forum&cmd=thread&id=' . $intThreadId . '&pos=' . $this->_getLastPos($postId, $intThreadId));
         die;
     }
     if (!empty($_REQUEST['preview_edit'])) {
         $this->_objTpl->touchBlock('updatePost');
         $this->_objTpl->hideBlock('createPost');
         $this->_objTpl->hideBlock('previewNewPost');
         $this->_objTpl->touchBlock('previewEditPost');
     }
     $hasAccess = false;
     foreach (array('STICKY', 'MOVE', 'CLOSE', 'DELETE') as $action) {
         if (!$this->_checkAuth($intCatId, strtolower($action))) {
             $this->_objTpl->setVariable('FORUM_THREAD_ACTIONS_DISABLED_' . $action, 'disabled="disabled"');
         } else {
             $hasAccess = true;
         }
     }
     if ($this->_objTpl->blockExists('threadActionsSelect')) {
         if ($userId < 1 || !$hasAccess) {
             $this->_objTpl->hideBlock('threadActionsSelect');
         } else {
             $this->_objTpl->touchBlock('threadActionsSelect');
         }
     }
     if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'move' && !empty($_REQUEST['id'])) {
         $thread = intval($_REQUEST['id']);
         $newCat = intval($_REQUEST['moveToThread']);
         $oldCat = $this->_getCategoryIdFromThread($thread);
         $query = "UPDATE `" . DBPREFIX . "module_forum_postings` SET `category_id` = {$newCat} WHERE `thread_id` = " . $thread;
         if ($objDatabase->Execute($query)) {
             $intMovedPosts = $objDatabase->Affected_Rows();
             $query = "SELECT max( `id` ) as `lastid` FROM `" . DBPREFIX . "module_forum_postings` WHERE `thread_id` = {$thread}";
             $objRS = $objDatabase->SelectLimit($query, 1);
             $intMovedPostLastId = $objRS->fields['lastid'];
             $query = "SELECT max( `id` ) as `lastid` FROM `" . DBPREFIX . "module_forum_postings` WHERE `category_id` = {$oldCat}";
             $objRS = $objDatabase->SelectLimit($query, 1);
             $query = "UPDATE `" . DBPREFIX . "module_forum_statistics` SET `thread_count` = `thread_count` - 1, `post_count` = `post_count` - {$intMovedPosts}, `last_post_id` = " . (intval($objRS->fields['lastid']) > 0 ? intval($objRS->fields['lastid']) : 0) . " WHERE `category_id` = {$oldCat}";
             $objDatabase->Execute($query);
             $query = "SELECT `id` FROM `" . DBPREFIX . "module_forum_postings` WHERE `category_id` = {$newCat} GROUP BY `time_created` DESC";
             $objRS = $objDatabase->Execute($query);
             $query = "UPDATE `" . DBPREFIX . "module_forum_statistics` SET `thread_count` = `thread_count` + 1, `post_count` = `post_count` + {$intMovedPosts}, `last_post_id` = " . $objRS->fields['id'] . " WHERE `category_id` = {$newCat}";
             $objDatabase->Execute($query);
             $this->_objTpl->hideBlock('moveForm');
             $this->_objTpl->setVariable(array('TXT_THREAD_ACTION_' . ($success ? 'SUCCESS' : 'ERROR') => $_ARRAYLANG['TXT_FORUM_THREAD_ACTION_MOVE' . (!$success ? 'UN' : '') . 'SUCCESSFUL'], 'FORUM_CATEGORY_ID' => $intCatId, 'FORUM_THREAD_ID' => $intThreadId));
             \Cx\Core\Csrf\Controller\Csrf::header('Location: index.php?section=Forum&cmd=thread&id=' . $thread);
         }
     }
     if (!empty($_GET['a'])) {
         $this->_objTpl->setVariable(array('TXT_FORUM_' . ($_GET['r'] == 1 ? 'SUCCESS' : 'ERROR') => '<br />' . $_ARRAYLANG['TXT_FORUM_THREAD_ACTION_' . strtoupper($_GET['a']) . '_' . (!$_GET['r'] ? 'UN' : '') . 'SUCCESSFUL' . $_GET['s']]));
     }
     $success = false;
     if (!empty($_REQUEST['thread_actions'])) {
         $action = contrexx_addslashes($_REQUEST['thread_actions']);
         if ($this->_checkAuth($intCatId, $action)) {
             switch ($action) {
                 case 'move':
                     $arrForums = $this->createForumArray($this->_intLangId);
                     foreach ($arrForums as $intCatID => $arrThread) {
                         $strOptions .= '<option value="' . $intCatID . '" ' . ($arrThread['level'] == 0 ? 'disabled="disabled"' : '') . '>' . str_repeat('&nbsp;', $arrThread['level'] * 2) . $arrThread['name'] . '</option>';
                     }
                     $this->_objTpl->setVariable(array('FORUM_THREADS' => $strOptions));
                     $success = true;
                     $suffix = '';
                     \Env::get('cx')->getPage()->setTitle($_ARRAYLANG['TXT_FORUM_THREAD_ACTION_MOVE']);
                     break;
                 case 'close':
                     $query = "UPDATE `" . DBPREFIX . "module_forum_postings` SET `is_locked` = IF(`is_locked` = '0' OR `is_locked` = '', '1', '0') WHERE thread_id = " . intval($_REQUEST['id']);
                     if ($objDatabase->Execute($query) !== false) {
                         $success = true;
                     }
                     $suffix = '_' . $firstPost['is_locked'];
                     break;
                 case 'sticky':
                     $query = "UPDATE `" . DBPREFIX . "module_forum_postings` SET `is_sticky` = IF(`is_sticky` = '0' OR `is_sticky` = '', '1', '0') WHERE thread_id = " . intval($_REQUEST['id']);
                     if ($objDatabase->Execute($query) !== false) {
                         $success = true;
                     }
                     $suffix = '_' . $firstPost['is_sticky'];
                     break;
                 default:
                     break;
             }
             if ($action != 'move') {
                 \Cx\Core\Csrf\Controller\Csrf::header('Location: index.php?section=Forum&cmd=thread&id=' . $intThreadId . '&a=' . $action . '&r=' . $success . '&s=' . $suffix);
             }
         } else {
             $this->_objTpl->setVariable('TXT_THREAD_ACTION_ERROR', $_ARRAYLANG['TXT_FORUM_NO_ACCESS']);
         }
         $this->_objTpl->parse('threadActions');
         $this->_objTpl->touchBlock('threadActions');
         $this->_objTpl->hideBlock('threadDisplay');
     } else {
         $this->updateViews($intThreadId, $intPostId);
         $this->_objTpl->hideBlock('threadActions');
     }
     return true;
 }
Example #10
0
function _blogUpdate()
{
    global $objDatabase, $_ARRAYLANG, $_CORELANG, $objUpdate, $_CONFIG;
    /*
     * Check for missing setting "blog_comments_editor" in database. In the update-package for 1.2 this value somehow
     * got lost.
     */
    $query = '	SELECT 	name
				FROM	`' . DBPREFIX . 'module_blog_settings`
				WHERE	name="blog_comments_editor"
				LIMIT	1';
    $objResult = $objDatabase->Execute($query);
    if ($objResult !== false) {
        if ($objResult->RecordCount() == 0) {
            $query = "INSERT INTO `" . DBPREFIX . "module_blog_settings` ( `name` , `value` ) VALUES ('blog_comments_editor', 'wysiwyg')";
            if ($objDatabase->Execute($query) === false) {
                return _databaseError($query, $objDatabase->ErrorMsg());
            }
        }
    } else {
        return _databaseError($query, $objDatabase->ErrorMsg());
    }
    try {
        \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_blog_categories', array('category_id' => array('type' => 'INT(4)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'primary' => true), 'lang_id' => array('type' => 'INT(2)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'primary' => true), 'is_active' => array('type' => 'ENUM(\'0\',\'1\')', 'notnull' => true, 'default' => '1'), 'name' => array('type' => 'VARCHAR(100)', 'notnull' => true, 'default' => '')));
        \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_blog_comments', array('comment_id' => array('type' => 'INT(7)', 'unsigned' => true, 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'message_id' => array('type' => 'INT(6)', 'unsigned' => true, 'notnull' => true, 'default' => '0'), 'lang_id' => array('type' => 'INT(2)', 'unsigned' => true, 'notnull' => true, 'default' => '0'), 'is_active' => array('type' => 'ENUM(\'0\',\'1\')', 'notnull' => true, 'default' => '1'), 'time_created' => array('type' => 'INT(14)', 'unsigned' => true, 'notnull' => true, 'default' => '0'), 'ip_address' => array('type' => 'VARCHAR(15)', 'notnull' => true, 'default' => '0.0.0.0'), 'user_id' => array('type' => 'INT(5)', 'unsigned' => true, 'notnull' => true, 'default' => '0'), 'user_name' => array('type' => 'VARCHAR(50)', 'notnull' => false), 'user_mail' => array('type' => 'VARCHAR(250)', 'notnull' => false), 'user_www' => array('type' => 'VARCHAR(255)', 'notnull' => false), 'subject' => array('type' => 'VARCHAR(250)', 'notnull' => true, 'default' => ''), 'comment' => array('type' => 'TEXT')), array('message_id' => array('fields' => array('message_id'))));
        \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_blog_message_to_category', array('message_id' => array('type' => 'INT(6)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'primary' => true), 'category_id' => array('type' => 'INT(4)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'primary' => true), 'lang_id' => array('type' => 'INT(2)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'primary' => true)), array('category_id' => array('fields' => array('category_id'))));
        \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_blog_messages', array('message_id' => array('type' => 'INT(6)', 'unsigned' => true, 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'user_id' => array('type' => 'INT(5)', 'unsigned' => true, 'notnull' => true, 'default' => '0'), 'time_created' => array('type' => 'INT(14)', 'unsigned' => true, 'notnull' => true, 'default' => '0'), 'time_edited' => array('type' => 'INT(14)', 'unsigned' => true, 'notnull' => true, 'default' => '0'), 'hits' => array('type' => 'INT(7)', 'unsigned' => true, 'notnull' => true, 'default' => '0')));
        \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_blog_networks_lang', array('network_id' => array('type' => 'INT(8)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'primary' => true), 'lang_id' => array('type' => 'INT(2)', 'unsigned' => true, 'notnull' => true, 'default' => '0', 'primary' => true)));
        \Cx\Lib\UpdateUtil::table(DBPREFIX . 'module_blog_votes', array('vote_id' => array('type' => 'INT(8)', 'unsigned' => true, 'notnull' => true, 'auto_increment' => true, 'primary' => true), 'message_id' => array('type' => 'INT(6)', 'unsigned' => true, 'notnull' => true, 'default' => '0'), 'time_voted' => array('type' => 'INT(14)', 'unsigned' => true, 'notnull' => true, 'default' => '0'), 'ip_address' => array('type' => 'VARCHAR(15)', 'notnull' => true, 'default' => '0.0.0.0'), 'vote' => array('type' => 'ENUM(\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'7\',\'8\',\'9\',\'10\')', 'notnull' => true, 'default' => '1')), array('message_id' => array('fields' => array('message_id'))));
    } catch (\Cx\Lib\UpdateException $e) {
        // we COULD do something else here..
        return \Cx\Lib\UpdateUtil::DefaultActionHandler($e);
    }
    try {
        //update to 2.2.3 in this block
        if ($objUpdate->_isNewerVersion($_CONFIG['coreCmsVersion'], '2.2.3')) {
            //we've hidden the wysiwyg - let's default to textarea
            \Cx\Lib\UpdateUtil::sql('UPDATE ' . DBPREFIX . 'module_blog_settings SET value="textarea" WHERE name="blog_comments_editor"');
            //comments: convert escaped db entries to their unescaped equivalents
            $rs = \Cx\Lib\UpdateUtil::sql('SELECT comment_id, comment FROM  ' . DBPREFIX . 'module_blog_comments');
            while (!$rs->EOF) {
                $content = $rs->fields['comment'];
                $id = $rs->fields['comment_id'];
                $content = contrexx_raw2db(html_entity_decode($content, ENT_QUOTES, CONTREXX_CHARSET));
                \Cx\Lib\UpdateUtil::sql('UPDATE ' . DBPREFIX . 'module_blog_comments SET comment="' . $content . '" WHERE comment_id=' . $id);
                $rs->MoveNext();
            }
        }
    } catch (\Cx\Lib\UpdateException $e) {
        // we COULD do something else here..
        return \Cx\Lib\UpdateUtil::DefaultActionHandler($e);
    }
    try {
        // migrate content page to version 3.0.1
        $search = array('/(.*)/ms');
        $callback = function ($matches) {
            $content = $matches[1];
            if (empty($content)) {
                return $content;
            }
            // replace placeholder {TXT_COMMENT_ADD_SPAM} with {TXT_COMMENT_CAPTCHA}
            $content = str_replace('{TXT_COMMENT_ADD_SPAM}', '{TXT_COMMENT_CAPTCHA}', $content);
            // replace <img src="[[BLOG_DETAILS_COMMENT_ADD_SPAM_URL]]" alt="[[BLOG_DETAILS_COMMENT_ADD_SPAM_ALT]]" title="[[BLOG_DETAILS_COMMENT_ADD_SPAM_ALT]]" /> with {COMMENT_CAPTCHA_CODE}
            $content = preg_replace('/<img[^>]+\\{BLOG_DETAILS_COMMENT_ADD_SPAM_URL\\}[^>]+>/ms', '{COMMENT_CAPTCHA_CODE}', $content);
            // remove <input type="text" name="frmAddComment_Captcha" />
            $content = preg_replace('/<input[^>]+name\\s*=\\s*[\'"]frmAddComment_Captcha[^>]+>/ms', '', $content);
            // remove <input type="hidden" name="frmAddComment_Offset" value="[[BLOG_DETAILS_COMMENT_ADD_SPAM_OFFSET]]" />
            $content = preg_replace('/<(div|p)[^>]*>\\s*<input[^>]+name\\s*=\\s*[\'"]frmAddComment_Offset[^>]+>\\s*<\\/(div|p)>/ms', '', $content);
            // add missing comment_captcha template block
            if (!preg_match('/<!--\\s+BEGIN\\s+comment_captcha\\s+-->.*<!--\\s+END\\s+comment_captcha\\s+-->/ms', $content)) {
                $content = preg_replace('/(.*)(<(div|p)[^{]*?>.*?\\{TXT_COMMENT_CAPTCHA\\}.*?\\{COMMENT_CAPTCHA_CODE\\}.*?<\\/\\3>)/ms', '$1<!-- BEGIN comment_captcha -->$2<!-- END comment_captcha -->', $content, -1, $count);
                if (!$count) {
                    $content = preg_replace('/(.*)(<(div|p)[^{]*?>.*?\\{COMMENT_CAPTCHA_CODE\\}.*?<\\/\\3>)/ms', '$1<!-- BEGIN comment_captcha -->$2<!-- END comment_captcha -->', $content, -1, $count);
                }
            }
            return $content;
        };
        \Cx\Lib\UpdateUtil::migrateContentPageUsingRegexCallback(array('module' => 'blog', 'cmd' => 'details'), $search, $callback, array('content'), '3.0.1');
    } catch (\Cx\Lib\UpdateException $e) {
        return \Cx\Lib\UpdateUtil::DefaultActionHandler($e);
    }
    /**
     * Everything went fine. Return without any errors.
     */
    return true;
}
 /**
  * Store each crawl result to database
  * 
  * @global array $_CONFIG
  * 
  * @param \HTTP_Request2 $request          http_request2() object
  * @param String         $requestedUrl     the requested url
  * @param String         $refererUrl       the lead url
  * @param Boolean        $image            the requested url is image or not 
  * @param Integer        $referPageId      the lead url page id
  * @param String         $requestedUrlText the requested url text
  * 
  * @return null
  */
 public function storeUrlInfos(\HTTP_Request2 $request, $requestedUrl, $refererUrl, $image, $referPageId, $requestedUrlText)
 {
     global $_CONFIG;
     try {
         $request->setUrl($requestedUrl);
         // ignore ssl issues
         // otherwise, contrexx does not activate 'https' when the server doesn't have an ssl certificate installed
         $request->setConfig(array('ssl_verify_peer' => false, 'ssl_verify_host' => false, 'follow_redirects' => true));
         $response = $request->send();
         $urlStatus = $response->getStatus();
     } catch (\Exception $e) {
         $response = true;
         $urlStatus = preg_match('#^[mailto:|javascript:]# i', $requestedUrl) ? 200 : 0;
     }
     if ($response) {
         $internalFlag = \Cx\Core_Modules\LinkManager\Controller\Url::isInternalUrl($requestedUrl);
         $flagStatus = $urlStatus == '200' ? 1 : 0;
         $linkType = $internalFlag ? 'internal' : 'external';
         //find the entry name, module name, action and parameter
         if ($linkType == 'internal') {
             list($entryTitle, $moduleName, $moduleAction, $moduleParams) = $this->getModuleDetails($requestedUrl, $refererUrl, $image);
         } else {
             $objRefererUrl = $this->isModulePage($refererUrl);
             if ($objRefererUrl) {
                 $entryTitle = $objRefererUrl->getTitle();
             }
             $moduleName = '';
             $moduleAction = '';
             $moduleParams = '';
         }
         if (!empty($referPageId)) {
             $backendReferUrl = ASCMS_PROTOCOL . '://' . $_CONFIG['domainUrl'] . ASCMS_PATH_OFFSET . '/cadmin/index.php?cmd=ContentManager&page=' . $referPageId;
         }
         //save the link
         $linkInputValues = array('lang' => contrexx_raw2db($this->langId), 'requestedPath' => contrexx_raw2db($requestedUrl), 'refererPath' => contrexx_raw2db($refererUrl), 'leadPath' => contrexx_raw2db($backendReferUrl), 'linkStatusCode' => contrexx_raw2db($urlStatus), 'entryTitle' => contrexx_raw2db($entryTitle), 'moduleName' => contrexx_raw2db($moduleName), 'moduleAction' => contrexx_raw2db($moduleAction), 'moduleParams' => contrexx_raw2db($moduleParams), 'detectedTime' => new \DateTime('now'), 'flagStatus' => contrexx_raw2db($flagStatus), 'linkStatus' => 0, 'linkRecheck' => 0, 'updatedBy' => 0, 'requestedLinkType' => contrexx_raw2db($linkType), 'brokenLinkText' => contrexx_raw2db($requestedUrlText));
         $linkAlreadyExist = $this->linkRepo->findOneBy(array('requestedPath' => $requestedUrl));
         if ($linkAlreadyExist && $linkAlreadyExist->getRefererPath() == $refererUrl) {
             if ($linkAlreadyExist->getLinkStatusCode() != $urlStatus) {
                 //move the modified link to history table
                 $historyInputValues = array('lang' => $linkAlreadyExist->getLang(), 'requestedPath' => $linkAlreadyExist->getRequestedPath(), 'refererPath' => $linkAlreadyExist->getRefererPath(), 'leadPath' => $linkAlreadyExist->getLeadPath(), 'linkStatusCode' => $linkAlreadyExist->getLinkStatusCode(), 'entryTitle' => $linkAlreadyExist->getEntryTitle(), 'moduleName' => $linkAlreadyExist->getModuleName(), 'moduleAction' => $linkAlreadyExist->getModuleAction(), 'moduleParams' => $linkAlreadyExist->getModuleParams(), 'detectedTime' => $linkAlreadyExist->getDetectedTime(), 'flagStatus' => $linkAlreadyExist->getFlagStatus(), 'linkStatus' => $linkAlreadyExist->getLinkStatus(), 'linkRecheck' => $linkAlreadyExist->getLinkRecheck(), 'updatedBy' => $linkAlreadyExist->getUpdatedBy(), 'requestedLinkType' => $linkAlreadyExist->getRequestedLinkType(), 'brokenLinkText' => $linkAlreadyExist->getBrokenLinkText());
                 $this->modifyHistory($historyInputValues);
             }
             //add the modified link to the link table
             $this->modifyLink($linkInputValues, $linkAlreadyExist);
         } else {
             //add the link to link table
             $this->modifyLink($linkInputValues);
         }
     } else {
         return;
     }
 }
 /**
  * Gets one or more entries from this DataSource
  *
  * If an argument is not provided, no restriction is made for this argument.
  * So if this is called without any arguments, all entries of this
  * DataSource are returned.
  * If no entry is found, an empty array is returned.
  * @param string $elementId (optional) ID of the element if only one is to be returned
  * @param array $filter (optional) field=>value-type condition array, only supports = for now
  * @param array $order (optional) field=>order-type array, order is either "ASC" or "DESC"
  * @param int $limit (optional) If set, no more than $limit results are returned
  * @param int $offset (optional) Entry to start with
  * @param array $fieldList (optional) Limits the result to the values for the fields in this list
  * @throws \Exception If something did not go as planned
  * @return array Two dimensional array (/table) of results (array($row=>array($fieldName=>$value)))
  */
 public function get($elementId = null, $filter = array(), $order = array(), $limit = 0, $offset = 0, $fieldList = array())
 {
     $tableName = DBPREFIX . $this->getIdentifier();
     // $elementId
     $whereList = array();
     if (isset($elementId)) {
         $whereList[] = '`id` = "' . contrexx_raw2db($elementId) . '"';
     }
     // $filter
     if (count($filter)) {
         foreach ($filter as $field => $value) {
             if (count($fieldList) && !in_array($field, $fieldList)) {
                 continue;
             }
             $whereList[] = '`' . contrexx_raw2db($field) . '` = "' . contrexx_raw2db($value) . '"';
         }
     }
     // $order
     $orderList = array();
     if (count($order)) {
         foreach ($order as $field => $ascdesc) {
             if (count($fieldList) && !in_array($field, $fieldList)) {
                 continue;
             }
             if (!in_array($ascdesc, array('ASC', 'DESC'))) {
                 $ascdesc = 'ASC';
             }
             $orderList[] = '`' . contrexx_raw2db($field) . '` ' . $ascdesc;
         }
     }
     // $limit, $offset
     $limitQuery = '';
     if ($limit) {
         $limitQuery = 'LIMIT ' . intval($limit);
         if ($offset) {
             $limitQuery .= ',' . intval($offset);
         }
     }
     // $fieldList
     $fieldListQuery = '*';
     if (count($fieldList)) {
         $fieldListQuery = '`' . implode('`, `', $fieldList) . '`';
     }
     // query parsing
     $whereQuery = '';
     if (count($whereList)) {
         $whereQuery = 'WHERE ' . implode(' AND ', $whereList);
     }
     $orderQuery = '';
     if (count($orderList)) {
         $orderQuery = 'ORDER BY ' . implode(', ', $orderList);
     }
     $query = '
         SELECT
             ' . $fieldListQuery . '
         FROM
             `' . $tableName . '`
         ' . $whereQuery . '
         ' . $orderQuery . '
         ' . $limitQuery . '
     ';
     $result = $this->cx->getDb()->getAdoDb()->query($query);
     $data = array();
     while (!$result->EOF) {
         $data[] = $result->fields;
         $result->MoveNext();
     }
     return $data;
     //new \Cx\Core_Modules\Listing\Model\Entity\DataSet($data);//array($query);
 }
Example #13
0
 /**
  * Update customer mail.
  *
  * @access      public
  * @param       array       $arrCustomerMail
  */
 public function updateCustomerMail($arrCustomerMail)
 {
     $objResult = $this->objDatabase->Execute('
         UPDATE `' . DBPREFIX . 'module_checkout_settings_mails`
         SET `title`="' . contrexx_raw2db($arrCustomerMail['title']) . '",
             `content`="' . contrexx_raw2db($arrCustomerMail['content']) . '"
         WHERE `id`=2
     ');
     if ($objResult) {
         return true;
     } else {
         return false;
     }
 }
Example #14
0
 /**
  * Processes the Order
  *
  * Verifies all data, updates and stores it in the database, and
  * initializes payment
  * @return  boolean         True on successs, false otherwise
  */
 static function process()
 {
     global $objDatabase, $_ARRAYLANG;
     // FOR TESTING ONLY (repeatedly process/store the order, also disable self::destroyCart())
     //$_SESSION['shop']['order_id'] = NULL;
     // Verify that the order hasn't yet been saved
     // (and has thus not yet been confirmed)
     if (isset($_SESSION['shop']['order_id'])) {
         return \Message::error($_ARRAYLANG['TXT_ORDER_ALREADY_PLACED']);
     }
     // No more confirmation
     self::$objTemplate->hideBlock('shopConfirm');
     // Store the customer, register the order
     $customer_ip = $_SERVER['REMOTE_ADDR'];
     $customer_host = substr(@gethostbyaddr($_SERVER['REMOTE_ADDR']), 0, 100);
     $customer_browser = substr(getenv('HTTP_USER_AGENT'), 0, 100);
     $new_customer = false;
     //\DBG::log("Shop::process(): E-Mail: ".$_SESSION['shop']['email']);
     if (self::$objCustomer) {
         //\DBG::log("Shop::process(): Existing User username ".$_SESSION['shop']['username'].", email ".$_SESSION['shop']['email']);
     } else {
         // Registered Customers are required to be logged in!
         self::$objCustomer = Customer::getRegisteredByEmail($_SESSION['shop']['email']);
         if (self::$objCustomer) {
             \Message::error($_ARRAYLANG['TXT_SHOP_CUSTOMER_REGISTERED_EMAIL']);
             \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'login') . '?redirect=' . base64_encode(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'confirm')));
         }
         // Unregistered Customers are stored as well, as their information is needed
         // nevertheless.  Their active status, however, is set to false.
         self::$objCustomer = Customer::getUnregisteredByEmail($_SESSION['shop']['email']);
         if (!self::$objCustomer) {
             self::$objCustomer = new Customer();
             // Currently, the e-mail address is set as the user name
             $_SESSION['shop']['username'] = $_SESSION['shop']['email'];
             //\DBG::log("Shop::process(): New User username ".$_SESSION['shop']['username'].", email ".$_SESSION['shop']['email']);
             self::$objCustomer->username($_SESSION['shop']['username']);
             self::$objCustomer->email($_SESSION['shop']['email']);
             // Note that the password is unset when the Customer chooses
             // to order without registration.  The generated one
             // defaults to length 8, fulfilling the requirements for
             // complex passwords.  And it's kept absolutely secret.
             $password = empty($_SESSION['shop']['password']) ? \User::make_password() : $_SESSION['shop']['password'];
             //\DBG::log("Password: $password (session: {$_SESSION['shop']['password']})");
             if (!self::$objCustomer->password($password)) {
                 \Message::error($_ARRAYLANG['TXT_INVALID_PASSWORD']);
                 \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'account'));
             }
             self::$objCustomer->active(empty($_SESSION['shop']['dont_register']));
             $new_customer = true;
         }
     }
     // Update the Customer object from the session array
     // (whether new or not -- it may have been edited)
     self::$objCustomer->gender($_SESSION['shop']['gender']);
     self::$objCustomer->firstname($_SESSION['shop']['firstname']);
     self::$objCustomer->lastname($_SESSION['shop']['lastname']);
     self::$objCustomer->company($_SESSION['shop']['company']);
     self::$objCustomer->address($_SESSION['shop']['address']);
     self::$objCustomer->city($_SESSION['shop']['city']);
     self::$objCustomer->zip($_SESSION['shop']['zip']);
     self::$objCustomer->country_id($_SESSION['shop']['countryId']);
     self::$objCustomer->phone($_SESSION['shop']['phone']);
     self::$objCustomer->fax($_SESSION['shop']['fax']);
     $arrGroups = self::$objCustomer->getAssociatedGroupIds();
     $usergroup_id = \Cx\Core\Setting\Controller\Setting::getValue('usergroup_id_reseller', 'Shop');
     if (empty($usergroup_id)) {
         //\DBG::log("Shop::process(): ERROR: Missing reseller group");
         \Message::error($_ARRAYLANG['TXT_SHOP_ERROR_USERGROUP_INVALID']);
         \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', ''));
     }
     if (!in_array($usergroup_id, $arrGroups)) {
         //\DBG::log("Shop::process(): Customer is not in Reseller group (ID $usergroup_id)");
         // Not a reseller.  See if she's a final customer
         $usergroup_id = \Cx\Core\Setting\Controller\Setting::getValue('usergroup_id_customer', 'Shop');
         if (empty($usergroup_id)) {
             //\DBG::log("Shop::process(): ERROR: Missing final customer group");
             \Message::error($_ARRAYLANG['TXT_SHOP_ERROR_USERGROUP_INVALID']);
             \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', ''));
         }
         if (!in_array($usergroup_id, $arrGroups)) {
             //\DBG::log("Shop::process(): Customer is not in final customer group (ID $usergroup_id), either");
             // Neither one, add to the final customer group (default)
             $arrGroups[] = $usergroup_id;
             self::$objCustomer->setGroups($arrGroups);
             //\DBG::log("Shop::process(): Added Customer to final customer group (ID $usergroup_id): ".var_export(self::$objCustomer->getAssociatedGroupIds(), true));
         } else {
             //\DBG::log("Shop::process(): Customer is a final customer (ID $usergroup_id) already: ".var_export(self::$objCustomer->getAssociatedGroupIds(), true));
         }
     } else {
         //\DBG::log("Shop::process(): Customer is a Reseller (ID $usergroup_id) already: ".var_export(self::$objCustomer->getAssociatedGroupIds(), true));
     }
     // Insert or update the customer
     //\DBG::log("Shop::process(): Storing Customer: ".var_export(self::$objCustomer, true));
     if (!self::$objCustomer->store()) {
         return \Message::error($_ARRAYLANG['TXT_SHOP_CUSTOMER_ERROR_STORING']);
     }
     // Authenticate new Customer
     if ($new_customer) {
         // Fails for "unregistered" Customers!
         if (self::$objCustomer->auth($_SESSION['shop']['username'], $_SESSION['shop']['password'], false, true)) {
             if (!self::_authenticate()) {
                 return \Message::error($_ARRAYLANG['TXT_SHOP_CUSTOMER_ERROR_STORING']);
             }
         }
     }
     //die();
     // Clear the ship-to country if there is no shipping
     if (!Cart::needs_shipment()) {
         $_SESSION['shop']['countryId2'] = 0;
     }
     $shipper_id = empty($_SESSION['shop']['shipperId']) ? null : $_SESSION['shop']['shipperId'];
     $payment_id = empty($_SESSION['shop']['paymentId']) ? null : $_SESSION['shop']['paymentId'];
     $objOrder = new Order();
     $objOrder->customer_id(self::$objCustomer->id());
     $objOrder->billing_gender($_SESSION['shop']['gender']);
     $objOrder->billing_firstname($_SESSION['shop']['firstname']);
     $objOrder->billing_lastname($_SESSION['shop']['lastname']);
     $objOrder->billing_company($_SESSION['shop']['company']);
     $objOrder->billing_address($_SESSION['shop']['address']);
     $objOrder->billing_city($_SESSION['shop']['city']);
     $objOrder->billing_zip($_SESSION['shop']['zip']);
     $objOrder->billing_country_id($_SESSION['shop']['countryId']);
     $objOrder->billing_phone($_SESSION['shop']['phone']);
     $objOrder->billing_fax($_SESSION['shop']['fax']);
     $objOrder->billing_email($_SESSION['shop']['email']);
     $objOrder->currency_id($_SESSION['shop']['currencyId']);
     $objOrder->sum($_SESSION['shop']['grand_total_price']);
     $objOrder->date_time(date(ASCMS_DATE_FORMAT_INTERNATIONAL_DATETIME));
     $objOrder->status(0);
     $objOrder->company($_SESSION['shop']['company2']);
     $objOrder->gender($_SESSION['shop']['gender2']);
     $objOrder->firstname($_SESSION['shop']['firstname2']);
     $objOrder->lastname($_SESSION['shop']['lastname2']);
     $objOrder->address($_SESSION['shop']['address2']);
     $objOrder->city($_SESSION['shop']['city2']);
     $objOrder->zip($_SESSION['shop']['zip2']);
     $objOrder->country_id($_SESSION['shop']['countryId2']);
     $objOrder->phone($_SESSION['shop']['phone2']);
     $objOrder->vat_amount($_SESSION['shop']['vat_price']);
     $objOrder->shipment_amount($_SESSION['shop']['shipment_price']);
     $objOrder->shipment_id($shipper_id);
     $objOrder->payment_id($payment_id);
     $objOrder->payment_amount($_SESSION['shop']['payment_price']);
     $objOrder->ip($customer_ip);
     $objOrder->host($customer_host);
     $objOrder->lang_id(FRONTEND_LANG_ID);
     $objOrder->browser($customer_browser);
     $objOrder->note($_SESSION['shop']['note']);
     if (!$objOrder->insert()) {
         // $order_id is unset!
         return \Message::error($_ARRAYLANG['TXT_SHOP_ORDER_ERROR_STORING']);
     }
     $order_id = $objOrder->id();
     $_SESSION['shop']['order_id'] = $order_id;
     // The products will be tested one by one below.
     // If any single one of them requires delivery, this
     // flag will be set to true.
     // This is used to determine the order status at the
     // end of the shopping process.
     $_SESSION['shop']['isDelivery'] = false;
     // Try to redeem the Coupon, if any
     $coupon_code = isset($_SESSION['shop']['coupon_code']) ? $_SESSION['shop']['coupon_code'] : null;
     //\DBG::log("Cart::update(): Coupon Code: $coupon_code");
     $items_total = 0;
     // Suppress Coupon messages (see Coupon::available())
     \Message::save();
     foreach (Cart::get_products_array() as $arrProduct) {
         $objProduct = Product::getById($arrProduct['id']);
         if (!$objProduct) {
             unset($_SESSION['shop']['order_id']);
             return \Message::error($_ARRAYLANG['TXT_ERROR_LOOKING_UP_ORDER']);
         }
         $product_id = $arrProduct['id'];
         $name = $objProduct->name();
         $priceOptions = !empty($arrProduct['optionPrice']) ? $arrProduct['optionPrice'] : 0;
         $quantity = $arrProduct['quantity'];
         $price = $objProduct->get_custom_price(self::$objCustomer, $priceOptions, $quantity);
         $item_total = $price * $quantity;
         $items_total += $item_total;
         $productVatId = $objProduct->vat_id();
         $vat_rate = $productVatId && Vat::getRate($productVatId) ? Vat::getRate($productVatId) : '0.00';
         // Test the distribution method for delivery
         $productDistribution = $objProduct->distribution();
         if ($productDistribution == 'delivery') {
             $_SESSION['shop']['isDelivery'] = true;
         }
         $weight = $productDistribution == 'delivery' ? $objProduct->weight() : 0;
         // grams
         if ($weight == '') {
             $weight = 0;
         }
         // Add to order items table
         $result = $objOrder->insertItem($order_id, $product_id, $name, $price, $quantity, $vat_rate, $weight, $arrProduct['options']);
         if (!$result) {
             unset($_SESSION['shop']['order_id']);
             // TODO: Verify error message set by Order::insertItem()
             return false;
         }
         // Store the Product Coupon, if applicable.
         // Note that it is not redeemed yet (uses=0)!
         if ($coupon_code) {
             $objCoupon = Coupon::available($coupon_code, $item_total, self::$objCustomer->id(), $product_id, $payment_id);
             if ($objCoupon) {
                 //\DBG::log("Shop::process(): Got Coupon for Product ID $product_id: ".var_export($objCoupon, true));
                 if (!$objCoupon->redeem($order_id, self::$objCustomer->id(), $price * $quantity, 0)) {
                     // TODO: Do something if the Coupon does not work
                     \DBG::log("Shop::process(): ERROR: Failed to store Coupon for Product ID {$product_id}");
                 }
                 $coupon_code = null;
             }
         }
     }
     // foreach product in cart
     // Store the Global Coupon, if applicable.
     // Note that it is not redeemed yet (uses=0)!
     //\DBG::log("Shop::process(): Looking for global Coupon $coupon_code");
     if ($coupon_code) {
         $objCoupon = Coupon::available($coupon_code, $items_total, self::$objCustomer->id(), null, $payment_id);
         if ($objCoupon) {
             //\DBG::log("Shop::process(): Got global Coupon: ".var_export($objCoupon, true));
             if (!$objCoupon->redeem($order_id, self::$objCustomer->id(), $items_total, 0)) {
                 \DBG::log("Shop::process(): ERROR: Failed to store global Coupon");
             }
         }
     }
     \Message::restore();
     $processor_id = Payment::getProperty($_SESSION['shop']['paymentId'], 'processor_id');
     $processor_name = PaymentProcessing::getPaymentProcessorName($processor_id);
     // other payment methods
     PaymentProcessing::initProcessor($processor_id);
     // TODO: These arguments are no longer valid.  Set them up later?
     //            Currency::getActiveCurrencyCode(),
     //            FWLanguage::getLanguageParameter(FRONTEND_LANG_ID, 'lang'));
     // if the processor is Internal_LSV, and there is account information,
     // store the information.
     if ($processor_name == 'internal_lsv') {
         if (!self::lsv_complete()) {
             // Missing mandatory data; return to payment
             unset($_SESSION['shop']['order_id']);
             \Message::error($_ARRAYLANG['TXT_ERROR_ACCOUNT_INFORMATION_NOT_AVAILABLE']);
             \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'payment'));
         }
         $query = "\n                INSERT INTO " . DBPREFIX . "module_shop" . MODULE_INDEX . "_lsv (\n                    order_id, holder, bank, blz\n                ) VALUES (\n                    {$order_id},\n                    '" . contrexx_raw2db($_SESSION['shop']['account_holder']) . "',\n                    '" . contrexx_raw2db($_SESSION['shop']['account_bank']) . "',\n                    '" . contrexx_raw2db($_SESSION['shop']['account_blz']) . "'\n                )";
         $objResult = $objDatabase->Execute($query);
         if (!$objResult) {
             // Return to payment
             unset($_SESSION['shop']['order_id']);
             \Message::error($_ARRAYLANG['TXT_ERROR_INSERTING_ACCOUNT_INFORMATION']);
             \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'payment'));
         }
     }
     $_SESSION['shop']['order_id_checkin'] = $order_id;
     $strProcessorType = PaymentProcessing::getCurrentPaymentProcessorType();
     // Test whether the selected payment method can be
     // considered an instant or deferred one.
     // This is used to set the order status at the end
     // of the shopping process.
     // TODO: Invert this flag, as it may no longer be present after paying
     // online using one of the external payment methods!  Ensure that it is set
     // instead when paying "deferred".
     $_SESSION['shop']['isInstantPayment'] = false;
     if ($strProcessorType == 'external') {
         // For the sake of simplicity, all external payment
         // methods are considered to be 'instant'.
         // All currently implemented internal methods require
         // further action from the merchant, and thus are
         // considered to be 'deferred'.
         $_SESSION['shop']['isInstantPayment'] = true;
     }
     // Send the Customer login separately, as the password possibly
     // won't be available later
     if (!empty($_SESSION['shop']['password'])) {
         self::sendLogin(self::$objCustomer->email(), $_SESSION['shop']['password']);
     }
     // Show payment processing page.
     // Note that some internal payments are redirected away
     // from this page in checkOut():
     // 'internal', 'internal_lsv'
     self::$objTemplate->setVariable('SHOP_PAYMENT_PROCESSING', PaymentProcessing::checkOut());
     // Clear the order ID.
     // The order may be resubmitted and the payment retried.
     unset($_SESSION['shop']['order_id']);
     // Custom.
     // Enable if Discount class is customized and in use.
     //self::showCustomerDiscount(Cart::get_price());
     return true;
 }
Example #15
0
 /**
  * Update currencies
  * @return  boolean             Null if nothing was changed,
  *                              boolean true upon storing everything
  *                              successfully, or false otherwise
  * @static
  */
 static function update()
 {
     global $objDatabase;
     if (empty($_POST['currency'])) {
         return null;
     }
     self::init();
     $default_id = isset($_POST['currencyDefault']) ? intval($_POST['currencyDefault']) : self::$defaultCurrencyId;
     $changed = false;
     foreach ($_POST['currencyCode'] as $currency_id => $code) {
         $code = contrexx_input2raw($code);
         $name = contrexx_input2raw($_POST['currencyName'][$currency_id]);
         $symbol = contrexx_input2raw($_POST['currencySymbol'][$currency_id]);
         $rate = floatval($_POST['currencyRate'][$currency_id]);
         $increment = floatval($_POST['currencyIncrement'][$currency_id]);
         if ($increment <= 0) {
             $increment = 0.01;
         }
         $default = $default_id == $currency_id ? 1 : 0;
         $active = empty($_POST['currencyActive'][$currency_id]) ? 0 : 1;
         // The default currency must be activated
         $active = $default ? 1 : $active;
         if ($code == self::$arrCurrency[$currency_id]['code'] && $name == self::$arrCurrency[$currency_id]['name'] && $symbol == self::$arrCurrency[$currency_id]['symbol'] && $rate == self::$arrCurrency[$currency_id]['rate'] && $increment == self::$arrCurrency[$currency_id]['increment'] && $active == self::$arrCurrency[$currency_id]['active'] && $default == self::$arrCurrency[$currency_id]['default']) {
             continue;
         }
         $query = "\n                UPDATE `" . DBPREFIX . "module_shop" . MODULE_INDEX . "_currencies`\n                   SET `code`='" . contrexx_raw2db($code) . "',\n                       `symbol`='" . contrexx_raw2db($symbol) . "',\n                       `rate`={$rate},\n                       `increment`={$increment},\n                       `active`={$active}\n                 WHERE `id`={$currency_id}";
         if (!$objDatabase->Execute($query)) {
             return false;
         }
         $changed = true;
         if (!\Text::replace($currency_id, FRONTEND_LANG_ID, 'Shop', self::TEXT_NAME, contrexx_input2raw($_POST['currencyName'][$currency_id]))) {
             return false;
         }
     }
     // end foreach
     if ($changed) {
         return self::setDefault($default_id);
     }
     return null;
 }
Example #16
0
 /**
  * Get proxy informations
  *
  * Determines if a proxy is used or not. If so, then proxy information are colleted
  */
 function _getProxyInformations()
 {
     if (isset($_SERVER['HTTP_VIA']) && $_SERVER['HTTP_VIA']) {
         // client does use a proxy
         $this->arrProxy['ip'] = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
         $this->arrProxy['host'] = @gethostbyaddr($this->arrProxy['ip']);
         $proxyUseragent = trim(addslashes(urldecode(strstr($_SERVER['HTTP_VIA'], ' '))));
         $startPos = strpos($proxyUseragent, "(");
         $this->arrProxy['useragent'] = substr($proxyUseragent, $startPos + 1);
         $endPos = strpos($this->arrProxy['useragent'], ")");
         $this->arrProxy['useragent'] = substr($this->arrProxy['useragent'], 0, $endPos - 1);
         if ($this->arrProxy['host'] == $this->arrProxy['ip']) {
             // no hostname found, try to take it out from useragent-infos
             $endPos = strpos($proxyUseragent, "(");
             $this->arrProxy['host'] = substr($proxyUseragent, 0, $endPos);
         }
         if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
             $this->arrClient['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
             if ($_SERVER['HTTP_X_FORWARDED_FOR'] == $_SERVER['HTTP_VIA']) {
                 $this->arrProxy['type'] = 2;
                 // Simple Anonymous Proxy
             } else {
                 $this->arrProxy['type'] = 1;
                 // Transparent or Distorting Proxy
             }
         } else {
             $this->arrProxy['type'] = 3;
             // High Anonymous Proxy
             if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
                 $this->arrClient['ip'] = $_SERVER['HTTP_CLIENT_IP'];
             } else {
                 $this->arrClient['ip'] = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
             }
         }
     } else {
         // Client does not use proxy
         $this->arrClient['ip'] = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : $_SERVER['REMOTE_ADDR'];
         $this->arrProxy['type'] = 0;
         // No proxy
         $this->arrProxy['ip'] = "";
         $this->arrProxy['host'] = "";
         $this->arrProxy['useragent'] = "";
     }
     foreach ($this->arrClient as &$client) {
         $client = contrexx_raw2db(strip_tags($client));
     }
     foreach ($this->arrProxy as &$proxy) {
         $proxy = contrexx_raw2db(strip_tags($proxy));
     }
 }
Example #17
0
/**
 * Note: the body of this function is by intention not enclosed in a try/catch block. We wan't the calling sections to catch and handle exceptions themself.
 */
function newsletter_migrate_country_field()
{
    /*
    TEST
                    $countryId = 0;
    $text = 'Switzerland';
                    $objText= \Cx\Lib\UpdateUtil::sql("SELECT `id` FROM `".DBPREFIX."core_text` WHERE `section` = 'core' AND `key` = 'core_country_name' AND `text` = '".contrexx_raw2db($text)."'");
                    if (!$objResult->EOF) {
                        $countryId = $objText->fields['id'];
                    }
    \DBG::dump($countryId);
    return;
    */
    ///////////////////////////
    // MIGRATE COUNTRY FIELD //
    ///////////////////////////
    // 1. backup country column to country_old
    if (\Cx\Lib\UpdateUtil::column_exist(DBPREFIX . 'module_newsletter_user', 'country')) {
        \Cx\Lib\UpdateUtil::sql('ALTER TABLE `' . DBPREFIX . 'module_newsletter_user` CHANGE `country` `country_old` VARCHAR(255) NOT NULL DEFAULT \'\'');
    }
    // 2. add new column country_id (format int)
    if (!\Cx\Lib\UpdateUtil::column_exist(DBPREFIX . 'module_newsletter_user', 'country_id')) {
        \Cx\Lib\UpdateUtil::sql('ALTER TABLE `' . DBPREFIX . 'module_newsletter_user` ADD `country_id` SMALLINT( 5 ) UNSIGNED NOT NULL DEFAULT \'0\' AFTER `country_old`');
    }
    // 3. migrate to new country format (using IDs)
    if (\Cx\Lib\UpdateUtil::column_exist(DBPREFIX . 'module_newsletter_user', 'country_old')) {
        $objResult = \Cx\Lib\UpdateUtil::sql('SELECT `id`, `country_old` FROM `' . DBPREFIX . 'module_newsletter_user` WHERE `country_id` = 0 AND `country_old` <> \'\'');
        if ($objResult->RecordCount()) {
            while (!$objResult->EOF) {
                // try setting country_id based on a guess from country_old
                $countryId = 0;
                $objText = \Cx\Lib\UpdateUtil::sql("SELECT `id` FROM `" . DBPREFIX . "core_text` WHERE `section` = 'core' AND `key` = 'core_country_name' AND `text` = '" . contrexx_raw2db($objResult->fields['country_old']) . "'");
                if (!$objResult->EOF) {
                    $countryId = $objText->fields['id'];
                }
                \Cx\Lib\UpdateUtil::sql('UPDATE `' . DBPREFIX . 'module_newsletter_user` SET `country_id` = \'' . contrexx_raw2db($countryId) . '\', `country_old` = \'\' WHERE `id` = ' . $objResult->fields['id']);
                if (!checkTimeoutLimit()) {
                    return 'timeout';
                }
                $objResult->MoveNext();
            }
        }
        // backup literal country name in field notes
        if (!\Cx\Lib\UpdateUtil::column_exist(DBPREFIX . 'module_newsletter_user', 'notes')) {
            if (\Cx\Lib\UpdateUtil::column_exist(DBPREFIX . 'module_newsletter_user', 'fax')) {
                $column = 'fax';
            } else {
                // versions pre 3.0.0 didn't have the column 'fax' yet
                $column = 'phone';
            }
            \Cx\Lib\UpdateUtil::sql('ALTER TABLE `' . DBPREFIX . 'module_newsletter_user` ADD `notes` text NOT NULL AFTER `' . $column . '`');
        }
        \Cx\Lib\UpdateUtil::sql('UPDATE `' . DBPREFIX . 'module_newsletter_user` SET `notes` = `country_old`');
        // drop obsolete column country_old'
        \Cx\Lib\UpdateUtil::sql('ALTER TABLE `' . DBPREFIX . 'module_newsletter_user` DROP `country_old`');
    }
    ////////////////////////////////
    // END: MIGRATE COUNTRY FIELD //
    ////////////////////////////////
}
Example #18
0
 /**
  * Add the new tag
  *
  * @global object $objDatabase
  * @param string $tag New Tag to be inserted
  * @return boolean|integer Retrun inserted Tag id and retrun false if
  *                         failed to insert
  */
 public function addTag($tag)
 {
     global $objDatabase, $_ARRAYLANG;
     if (!empty($tag)) {
         $insertQuery = 'INSERT INTO `' . DBPREFIX . 'module_news_tags` ' . '(`tag`) ' . 'VALUES ("' . contrexx_raw2db($tag) . '")';
         if ($objDatabase->Execute($insertQuery)) {
             return $objDatabase->Insert_ID();
         }
     }
     //TODO@  Throw execption or log error message
     $this->errMsg[] = $_ARRAYLANG['TXT_ERROR_SAVE_NEWS_TAG'];
     return false;
 }
Example #19
0
 /**
  * Insert this object into the database.
  *
  * Fails if either the ID or lang_id is empty.
  * @return  boolean                     True on success, false otherwise
  * @global  mixed       $objDatabase    Database object
  * @author  Reto Kohli <*****@*****.**>
  */
 function insert()
 {
     global $objDatabase;
     if (empty($this->id)) {
         DBG::log("Text::insert(): Invalid ID " . var_export($this, true));
         return false;
     }
     if (empty($this->lang_id)) {
         DBG::log("Text::insert(): Invalid language ID " . var_export($this, true));
         return false;
     }
     if (empty($this->key)) {
         DBG::log("Text::insert(): Invalid key " . var_export($this, true));
         return false;
     }
     $query = "\n            INSERT INTO `" . DBPREFIX . "core_text` (\n                `id`, `lang_id`, `section`, `key`, `text`\n            ) VALUES (\n                {$this->id}, {$this->lang_id}, " . (isset($this->section) ? "'" . contrexx_raw2db($this->section) . "'" : 'NULL') . ",\n                '" . contrexx_raw2db($this->key) . "',\n                '" . contrexx_raw2db($this->text) . "'\n            )";
     $objResult = $objDatabase->Execute($query);
     if (!$objResult) {
         DBG::log("Text::insert(): Failed to insert " . var_export($this, true));
         return self::errorHandler();
     }
     return true;
 }
Example #20
0
 /**
  * Save the cam's settings
  *
  */
 function saveCam()
 {
     global $objDatabase;
     $id = intval($_POST['id']);
     if (!$id) {
         return false;
     }
     $currentImagePath = \Cx\Lib\FileSystem\FileSystem::sanitizePath(contrexx_input2raw($_POST['currentImagePath']));
     if (!\FWValidator::isUri($currentImagePath) && strpos($currentImagePath, '/') !== 0) {
         $currentImagePath = '/' . $currentImagePath;
     }
     $maxImageWidth = intval($_POST['maxImageWidth']);
     $archivePath = \Cx\Lib\FileSystem\FileSystem::sanitizePath(contrexx_input2raw($_POST['archivePath']));
     if (!\FWValidator::isUri($archivePath) && strpos($archivePath, '/') !== 0) {
         $archivePath = '/' . $archivePath;
     }
     $thumbnailPath = \Cx\Lib\FileSystem\FileSystem::sanitizePath(contrexx_input2raw($_POST['thumbnailPath']));
     if (!\FWValidator::isUri($thumbnailPath) && strpos($thumbnailPath, '/') !== 0) {
         $thumbnailPath = '/' . $thumbnailPath;
     }
     $thumbMaxSize = intval($_POST['thumbMaxSize']);
     $shadowboxActivate = intval($_POST['shadowboxActivate']);
     $hourFrom = intval($_POST['hourFrom']);
     $hourTill = intval($_POST['hourTill']);
     $minuteFrom = intval($_POST['minuteFrom']);
     $minuteTill = intval($_POST['minuteTill']);
     $showFrom = mktime($hourFrom, $minuteFrom);
     $showTill = mktime($hourTill, $minuteTill);
     $query = " UPDATE " . DBPREFIX . "module_livecam\n                   SET currentImagePath = '" . contrexx_raw2db($currentImagePath) . "',\n                       maxImageWidth = " . $maxImageWidth . ",\n                       archivePath = '" . contrexx_raw2db($archivePath) . "',\n                       thumbnailPath = '" . contrexx_raw2db($thumbnailPath) . "',\n                       thumbMaxSize = " . $thumbMaxSize . ",\n                       shadowboxActivate = '" . $shadowboxActivate . "',\n                       showFrom = {$showFrom},\n                       showTill = {$showTill}\n                   WHERE id = " . $id;
     if ($objDatabase->Execute($query) === false) {
         // return a 500 or so
         header("HTTP/1.0 500 Internal Server Error");
         die;
     }
     die;
 }
Example #21
0
 /**
  * @static
  * @param integer $fileId file id
  * @return bool is shared or not
  */
 public static function isShared($fileId = null, $fileSource = null)
 {
     global $objDatabase;
     $fileSource = str_replace(\Cx\Core\Core\Controller\Cx::instanciate()->getWebsiteOffsetPath(), '', $fileSource);
     if ($fileSource != NULL) {
         $objResult = $objDatabase->SelectLimit("SELECT `id` FROM " . DBPREFIX . "module_filesharing WHERE `source` = '" . contrexx_raw2db($fileSource) . "'", 1, -1);
         if ($objResult !== false && $objResult->RecordCount() > 0) {
             $fileId = $objResult->fields["id"];
         }
     }
     return self::getDownloadLink($fileId) && self::getDeleteLink($fileId) && $fileId;
 }
 function _prepareNewsletterLinksForStore($MailId)
 {
     global $objDatabase;
     $objMail = $objDatabase->SelectLimit("\n            SELECT `content`\n            FROM " . DBPREFIX . "module_newsletter\n            WHERE id={$MailId}", 1);
     if ($objMail !== false && $objMail->RecordCount() == 1) {
         $htmlContent = $objMail->fields['content'];
         $linkIds = array();
         $matches = NULL;
         if (preg_match_all("/<a([^>]+)>(.*?)<\\/a>/is", $htmlContent, $matches)) {
             $tagCount = count($matches[0]);
             $fullKey = 0;
             $attrKey = 1;
             $textKey = 2;
             $rmatches = NULL;
             for ($i = 0; $i < $tagCount; $i++) {
                 // TODO: wouldn't that
                 if (!preg_match("/href\\s*=\\s*['\"][^#]/i", $matches[$attrKey][$i])) {
                     // be the same as
                     //                     if (preg_match("/href\s*=\s*['\"][#]/i", $matches[$attrKey][$i])) {
                     // ?
                     // we might have a placeholder link here, it will be parsed on send
                     continue;
                 }
                 $rel = '';
                 $href = '';
                 if (preg_match("/rel\\s*=\\s*(['\"])(.*?)\\1/i", $matches[$attrKey][$i], $rmatches)) {
                     $rel = $rmatches[2];
                 }
                 if (preg_match("/href\\s*=\\s*(['\"])(.*?)\\1/i", $matches[$attrKey][$i], $rmatches)) {
                     $href = html_entity_decode($rmatches[2], ENT_QUOTES, CONTREXX_CHARSET);
                 }
                 if ($rel) {
                     if (preg_match("/newsletter_link_(\\d+)/i", $rel, $rmatches)) {
                         if (in_array($rmatches[1], $linkIds)) {
                             $query = "INSERT INTO " . DBPREFIX . "module_newsletter_email_link (email_id, title, url) VALUES\n                                    (" . intval($MailId) . ", '" . contrexx_raw2db($matches[$textKey][$i]) . "', '" . contrexx_raw2db($href) . "')";
                             if ($objDatabase->Execute($query)) {
                                 $linkId = $objDatabase->Insert_ID();
                                 $matches[$attrKey][$i] = str_replace('newsletter_link_' . $rmatches[1], 'newsletter_link_' . $linkId, $matches[$attrKey][$i]);
                             }
                         } else {
                             // update existed link
                             $query = "UPDATE " . DBPREFIX . "module_newsletter_email_link\n                                    SET title = '" . contrexx_raw2db($matches[$textKey][$i]) . "',\n                                        url = '" . contrexx_raw2db($href) . "'\n                                    WHERE id = " . intval($rmatches[1]);
                             $objDatabase->Execute($query);
                             $linkId = $rmatches[1];
                         }
                     } else {
                         // insert new link into database and update rel attribute
                         $query = "INSERT INTO " . DBPREFIX . "module_newsletter_email_link (email_id, title, url) VALUES\n                                (" . intval($MailId) . ", '" . contrexx_raw2db($matches[$textKey][$i]) . "', '" . contrexx_raw2db($href) . "')";
                         if ($objDatabase->Execute($query)) {
                             $linkId = $objDatabase->Insert_ID();
                             $matches[$attrKey][$i] = preg_replace("/rel\\s*=\\s*(['\"])(.*?)\\1/i", "rel=\"\$2 newsletter_link_" . $linkId . "\"", $matches[$attrKey][$i]);
                         }
                     }
                 } else {
                     // insert new link into database and create rel attribute
                     $query = "INSERT INTO " . DBPREFIX . "module_newsletter_email_link (email_id, title, url) VALUES\n                            (" . intval($MailId) . ", '" . contrexx_raw2db($matches[$textKey][$i]) . "', '" . contrexx_raw2db($href) . "')";
                     if ($objDatabase->Execute($query)) {
                         $linkId = $objDatabase->Insert_ID();
                         $matches[$attrKey][$i] .= ' rel="newsletter_link_' . $linkId . '"';
                     }
                 }
                 $linkIds[] = $linkId;
                 $htmlContent = preg_replace("/" . preg_quote($matches[$fullKey][$i], '/') . "/is", "<a " . $matches[$attrKey][$i] . ">" . $matches[$textKey][$i] . "</a>", $htmlContent, 1);
             }
             // update mail content
             $query = "UPDATE " . DBPREFIX . "module_newsletter\n                    SET content = '" . contrexx_raw2db($htmlContent) . "'\n                    WHERE id = " . intval($MailId);
             $objDatabase->Execute($query);
         }
         // remove deleted links from database; we can remove them, because we can't edit sent email
         if (count($linkIds) > 0) {
             $query = "DELETE FROM " . DBPREFIX . "module_newsletter_email_link\n                    WHERE id NOT IN (" . implode(", ", $linkIds) . ") AND email_id = " . $MailId;
             $objDatabase->Execute($query);
         }
     }
 }
Example #23
0
 /**
  * @param  mixed    $profileUpdated	If $profileUpdated is provided, then in case any profile
  *                                  changes are being flushed to the database, $profileUpdated
  *                                  will be set to TRUE, otherwise it'll be left untouched.
  */
 protected function storeProfile(&$profileUpdated = null)
 {
     global $objDatabase, $_CORELANG;
     $error = false;
     foreach ($this->arrLoadedUsers[$this->id]['profile'] as $attributeId => $arrValue) {
         foreach ($arrValue as $historyId => $value) {
             $newValue = !isset($this->arrCachedUsers[$this->id]['profile'][$attributeId][$historyId]);
             if ($newValue || $value != $this->arrCachedUsers[$this->id]['profile'][$attributeId][$historyId]) {
                 $query = $this->objAttribute->isCoreAttribute($attributeId) ? "UPDATE `" . DBPREFIX . "access_user_profile` SET `" . $attributeId . "` = '" . contrexx_raw2db($value) . "' WHERE `user_id` = " . $this->id : ($newValue ? "INSERT INTO `" . DBPREFIX . "access_user_attribute_value` (`user_id`, `attribute_id`, `history_id`, `value`) VALUES (" . $this->id . ", " . $attributeId . ", " . $historyId . ", '" . contrexx_raw2db($value) . "')" : "UPDATE `" . DBPREFIX . "access_user_attribute_value` SET `value` = '" . contrexx_raw2db($value) . "' WHERE `user_id` = " . $this->id . " AND `attribute_id` = " . $attributeId . " AND `history_id` = " . $historyId);
                 if ($objDatabase->Execute($query) === false) {
                     $objAttribute = $this->objAttribute->getById($attributeId);
                     $error = true;
                     $this->error_msg[] = sprintf($_CORELANG['TXT_ACCESS_UNABLE_STORE_PROFILE_ATTIRBUTE'], htmlentities($objAttribute->getName(), ENT_QUOTES, CONTREXX_CHARSET));
                 } elseif ($objDatabase->Affected_Rows()) {
                     // track flushed db change
                     $profileUpdated = true;
                 }
             }
         }
         if ($this->objAttribute->isCustomAttribute($attributeId) && isset($this->arrCachedUsers[$this->id]['profile'][$attributeId])) {
             foreach (array_diff(array_keys($this->arrCachedUsers[$this->id]['profile'][$attributeId]), array_keys($arrValue)) as $historyId) {
                 if ($objDatabase->Execute('DELETE FROM `' . DBPREFIX . 'access_user_attribute_value` WHERE `attribute_id` = ' . $attributeId . ' AND `user_id` = ' . $this->id . ' AND `history_id` = ' . $historyId) === false) {
                     $objAttribute = $this->objAttribute->getById($attributeId);
                     $error = true;
                     $this->error_msg[] = sprintf($_CORELANG['TXT_ACCESS_UNABLE_STORE_PROFILE_ATTIRBUTE'], htmlentities($objAttribute->getName(), ENT_QUOTES, CONTREXX_CHARSET));
                 } elseif ($objDatabase->Affected_Rows()) {
                     // track flushed db change
                     $profileUpdated = true;
                 }
             }
         }
     }
     return !$error;
 }
Example #24
0
 /**
  * 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);
 }
Example #25
0
/**
 * Adds slashes to the given raw string or array thereof for insertion
 * into the database.
 * @param   mixed     $raw      The raw string or array
 * @return  mixed               The slashed string or array
 */
function contrexx_raw2db($raw)
{
    if (is_array($raw)) {
        $arr = array();
        foreach ($raw as $i => $_raw) {
            $arr[$i] = contrexx_raw2db($_raw);
        }
        return $arr;
    }
    $cx = \Cx\Core\Core\Controller\Cx::instanciate();
    $db = $cx->getDb();
    if (!isset($db)) {
        throw new \Cx\Core\Model\DbException('Database not yet initialized!');
    }
    $pdo = $db->getPdoConnection();
    $rawQuoted = $pdo->quote($raw);
    //addslashes did not add quotes, but pdo:quote does
    //we remove the quotes so we do not have to change all the queries
    if (strpos($rawQuoted, '\'') === 0 && substr($rawQuoted, -1) === '\'') {
        $rawQuoted = substr($rawQuoted, 1, -1);
    }
    return $rawQuoted;
}
Example #26
0
 /**
  * get the shared files by upload id
  *
  * @param integer $uploadId the upload id of the upload
  *
  * @return array with files of the last upload
  *
  * @access private
  */
 private function getSharedFiles($uploadId)
 {
     global $objDatabase;
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     $fileSystem = new \Cx\Lib\FileSystem\FileSystem();
     $imageUrl = clone \Env::get("Resolver")->getUrl();
     // get the image url
     $files = array();
     $directory = \Env::get('Resolver')->getCmd();
     if ($directory != 'Downloads') {
         $targetPath = $cx->getWebsiteMediaFileSharingPath() . '/' . (!empty($directory) ? $directory . '/' : '');
         $targetPathWeb = $cx->getWebsiteMediaFileSharingWebPath() . '/' . (!empty($directory) ? $directory . '/' : '');
     } else {
         $targetPath = $cx->getWebsiteImagesDownloadsPath() . '/';
         $targetPathWeb = $cx->getWebsiteImagesDownloadsWebPath() . '/';
     }
     $tup = FileSharingLib::getTemporaryFilePaths($uploadId);
     $dirTempPath = $tup[0] . '/' . $tup[2] . '/';
     //get the tmp/$uploadId files
     foreach (glob($dirTempPath . '/*') as $uploadedFile) {
         $file = basename($uploadedFile);
         $uploadedFileName = $fileSystem->copyFile($dirTempPath, $file, $targetPath, $file, false);
         if ($uploadedFileName === 'error') {
             continue;
         }
         \Cx\Lib\FileSystem\FileSystem::delete_file($dirTempPath . '/' . $file);
         $uploadedFileSource = $targetPathWeb . $uploadedFileName;
         $hash = self::createHash();
         $check = self::createCheck($hash);
         $objResult = $objDatabase->Execute("INSERT INTO " . DBPREFIX . "module_filesharing (`file`, `source`, `cmd`, `hash`, `check`, `upload_id`)\n                                VALUES (\n                                    '" . contrexx_raw2db($uploadedFileName) . "',\n                                    '" . contrexx_raw2db($uploadedFileSource) . "',\n                                    '" . contrexx_raw2db($directory) . "',\n                                    '" . contrexx_raw2db($hash) . "',\n                                    '" . contrexx_raw2db($check) . "',\n                                    '" . contrexx_input2int($uploadId) . "'\n                                )");
         if (!$objResult) {
             continue;
         }
         $imageUrl->setParam("act", "image");
         $imageUrl->setParam("hash", $hash);
         $info = pathinfo($cx->getWebsiteOffsetPath() . $uploadedFileSource, PATHINFO_EXTENSION);
         // if the file is an image show a thumbnail of the image
         if (!in_array(strtoupper($info), array('JPEG', 'JPG', 'TIFF', 'GIF', 'BMP', 'PNG'))) {
             $imageUrl = false;
         }
         $fieldId = $objDatabase->Insert_ID();
         $files[] = array("name" => $uploadedFileName, "image" => $imageUrl->toString(), "download" => parent::getDownloadLink($fieldId), "delete" => parent::getDeleteLink($fieldId));
     }
     return $files;
 }
Example #27
0
 /**
  * Inserts the contact form submit into the database
  *
  * This method does store the request in the database
  * @access private
  * @global ADONewConnection
  * @global array
  * @param array Details of the contact request
  * @see errorMsg
  * @return boolean TRUE on succes, otherwise FALSE
  */
 function _insertIntoDatabase($arrFormData)
 {
     global $objDatabase, $_ARRAYLANG, $_LANGID;
     if (!empty($this->errorMsg)) {
         return false;
     }
     //handle files and collect the filenames
     //for legacy mode this has already been done in the first
     //_uploadFiles() call in getContactPage().
     if (!$this->legacyMode) {
         $arrFormData['uploadedFiles'] = $this->_uploadFiles($arrFormData['fields'], true);
     }
     $objResult = $objDatabase->Execute("INSERT INTO " . DBPREFIX . "module_contact_form_data\n                                        (`id_form`, `id_lang`, `time`, `host`, `lang`, `browser`, `ipaddress`)\n                                        VALUES\n                                        (" . $arrFormData['id'] . ",\n                                         " . $_LANGID . ",\n                                         " . $arrFormData['meta']['time'] . ",\n                                         '" . contrexx_raw2db($arrFormData['meta']['host']) . "',\n                                         '" . contrexx_raw2db($arrFormData['meta']['lang']) . "',\n                                         '" . contrexx_raw2db($arrFormData['meta']['browser']) . "',\n                                         '" . contrexx_raw2db($arrFormData['meta']['ipaddress']) . "')");
     if ($objResult === false) {
         $this->errorMsg .= $_ARRAYLANG['TXT_CONTACT_FAILED_SUBMIT_REQUEST'] . '<br />';
         return false;
     }
     $lastInsertId = $objDatabase->insert_id();
     foreach ($arrFormData['fields'] as $key => $arrField) {
         $value = '';
         if ($arrField['type'] == 'file' || $arrField['type'] == 'multi_file') {
             if ($key === 0) {
                 throw new \Cx\Core_Modules\Contact\Controller\ContactException('could not find file field for form with id ' . $arrFormData['id']);
             }
             if ($this->legacyMode) {
                 //store files according to their inputs name
                 // TODO: check legacyMode
                 $arrDBEntry = array();
                 foreach ($arrFormData['uploadedFiles'] as $key => $file) {
                     $arrDbEntry[] = base64_encode($key) . "," . base64_encode(contrexx_strip_tags($file));
                 }
                 $value = implode(';', $arrDbEntry);
             } elseif (isset($arrFormData['uploadedFiles'][$key]) && count($arrFormData['uploadedFiles'][$key]) > 0) {
                 //assign all files uploaded to the uploader fields name
                 $arrTmp = array();
                 foreach ($arrFormData['uploadedFiles'][$key] as $file) {
                     $arrTmp[] = $file['path'];
                 }
                 // a * in front of the file names marks a 'new style' entry
                 $value = implode('*', $arrTmp);
             }
         } else {
             if (isset($arrFormData['data'][$key])) {
                 $value = $arrFormData['data'][$key];
             }
         }
         if ($value != "") {
             $objDatabase->Execute("INSERT INTO " . DBPREFIX . "module_contact_form_submit_data\n                                        (`id_entry`, `id_field`, `formlabel`, `formvalue`)\n                                        VALUES\n                                        (" . $lastInsertId . ",\n                                         " . $key . ",\n                                         '" . contrexx_raw2db($arrField['lang'][$_LANGID]['name']) . "',\n                                         '" . contrexx_raw2db($value) . "')");
         }
     }
     return true;
 }
Example #28
0
 /**
  * Loads the event manager
  * 
  * @return null
  */
 function loadEventManager()
 {
     $term = isset($_GET['term']) ? contrexx_input2raw($_GET['term']) : '';
     $from = isset($_GET['from']) ? contrexx_input2raw($_GET['from']) : '';
     $till = isset($_GET['till']) ? contrexx_input2raw($_GET['till']) : '';
     $catid = isset($_GET['catid']) ? contrexx_input2raw($_GET['catid']) : '';
     $cmd = isset($_GET['cmd']) ? contrexx_input2raw($_GET['cmd']) : '';
     // get startdate
     if (!empty($from)) {
         $this->startDate = $this->getDateTime($from);
     } else {
         if ($cmd == 'archive') {
             $this->startDate = null;
             $this->sortDirection = 'DESC';
         } else {
             $this->startDate = new \DateTime();
             $startDay = isset($_GET['day']) ? $_GET['day'] : $this->startDate->format('d');
             $startMonth = isset($_GET['month']) ? $_GET['month'] : $this->startDate->format('m');
             $startYear = isset($_GET['year']) ? $_GET['year'] : $this->startDate->format('Y');
             $this->startDate->setDate($startYear, $startMonth, $startDay);
             $this->startDate->setTime(0, 0, 0);
         }
     }
     // get enddate
     if (!empty($till)) {
         $this->endDate = $this->getDateTime($till);
     } else {
         if ($cmd == 'archive') {
             $this->endDate = new \DateTime();
         } else {
             $this->endDate = new \DateTime();
             $endDay = isset($_GET['endDay']) ? $_GET['endDay'] : $this->endDate->format('d');
             $endMonth = isset($_GET['endMonth']) ? $_GET['endMonth'] : $this->endDate->format('m');
             $endYear = isset($_GET['endYear']) ? $_GET['endYear'] : $this->endDate->format('Y');
             $endYear = empty($_GET['endYear']) && empty($_GET['endMonth']) ? $endYear + 10 : $endYear;
             $this->endDate->setDate($endYear, $endMonth, $endDay);
             $this->endDate->setTime(23, 59, 59);
         }
     }
     // get datepicker-time
     if ((isset($_REQUEST["yearID"]) || isset($_REQUEST["monthID"]) || isset($_REQUEST["dayID"])) && $cmd != 'boxes') {
         $this->startDate = new \DateTime();
         $year = isset($_REQUEST["yearID"]) ? (int) $_REQUEST["yearID"] : $this->startDate->format('Y');
         $month = isset($_REQUEST["monthID"]) ? (int) $_REQUEST["monthID"] : $this->startDate->format('m');
         $day = isset($_REQUEST["dayID"]) ? (int) $_REQUEST["dayID"] : $this->startDate->format('d');
         $this->startDate->setDate($year, $month, $day);
         $this->startDate->modify("first day of this month");
         $this->startDate->setTime(0, 0, 0);
         $this->endDate = clone $this->startDate;
         // add months for the list view(month view)
         if ((empty($_GET['act']) || $_GET['act'] != 'list') && empty($_REQUEST['dayID'])) {
             $this->endDate->modify("+{$this->boxCount} months");
         }
         $this->endDate->modify("last day of this month");
         $this->endDate->setTime(23, 59, 59);
     } elseif (isset($_GET["yearID"]) && isset($_GET["monthID"]) && isset($_GET["dayID"])) {
         $this->startDate = new \DateTime();
         $year = isset($_REQUEST["yearID"]) ? (int) $_REQUEST["yearID"] : $this->startDate->format('Y');
         $month = isset($_REQUEST["monthID"]) ? (int) $_REQUEST["monthID"] : $this->startDate->format('m');
         $day = isset($_REQUEST["dayID"]) ? (int) $_REQUEST["dayID"] : $this->startDate->format('d');
         $this->startDate->setDate($year, $month, $day);
         $this->startDate->setTime(0, 0, 0);
         $this->endDate = clone $this->startDate;
         $this->endDate->setTime(23, 59, 59);
     }
     // In case $_GET['cmd'] is an integer, then we shall treat it as the
     // ID of a category and switch to category-mode
     if (!empty($cmd) && (string) intval($cmd) == $cmd) {
         $catid = intval($cmd);
         $cmd == 'category';
         $this->simulateCategoryView = true;
     }
     $this->searchTerm = !empty($term) ? contrexx_raw2db($term) : null;
     $this->categoryId = !empty($catid) ? intval($catid) : null;
     if ($cmd == 'boxes' || $cmd == 'category') {
         $this->startPos = 0;
         $this->numEvents = 'n';
     } else {
         if (!isset($_GET['search']) && ($cmd != 'list' && $cmd != 'eventlist' && $cmd != 'archive')) {
             $this->startPos = 0;
             $this->numEvents = $this->arrSettings['numEntrance'];
         } else {
             $this->startPos = isset($_GET['pos']) ? intval($_GET['pos']) : 0;
             $this->numEvents = $this->arrSettings['numPaging'];
         }
     }
     if ($cmd == 'detail') {
         $this->startDate = null;
         $this->numEvents = 'n';
     }
     if ($cmd == 'my_events') {
         $objFWUser = \FWUser::getFWUserObject();
         $objUser = $objFWUser->objUser;
         $this->author = intval($objUser->getId());
     } else {
         $this->author = null;
     }
     $this->objEventManager = new \Cx\Modules\Calendar\Controller\CalendarEventManager($this->startDate, $this->endDate, $this->categoryId, $this->searchTerm, true, $this->needAuth, true, $this->startPos, $this->numEvents, $this->sortDirection, true, $this->author);
     if (!in_array($cmd, array('detail', 'register'))) {
         $this->objEventManager->getEventList();
     } else {
         /* if($_GET['external'] == 1 && $this->arrSettings['publicationStatus'] == 1) {
                $this->objEventManager->getExternalEvent(intval($_GET['id']), intval($_GET['date'])); 
            } else { */
         $eventId = isset($_REQUEST['id']) ? contrexx_input2int($_REQUEST['id']) : 0;
         $date = isset($_REQUEST['date']) ? contrexx_input2int($_REQUEST['date']) : 0;
         $this->objEventManager->getEvent($eventId, $date);
         /* } */
     }
 }
 function saveEntry($arrData, $intEntryId = null)
 {
     global $_ARRAYLANG, $_CORELANG, $objDatabase, $_LANGID, $objInit;
     $objFWUser = \FWUser::getFWUserObject();
     $translationStatus = isset($arrData['translationStatus']) ? $arrData['translationStatus'] : array();
     //get data
     $intId = intval($intEntryId);
     $intFormId = intval($arrData['formId']);
     $strCreateDate = mktime();
     $strUpdateDate = mktime();
     $intUserId = intval($objFWUser->objUser->getId());
     $strLastIp = contrexx_addslashes($_SERVER['REMOTE_ADDR']);
     $strTransStatus = contrexx_addslashes(join(",", $translationStatus));
     //$arrCategories = explode(",",$arrData['selectedCategories']);
     //$arrLevels= explode("&",$arrData['selectedLevels']);
     if ($objInit->mode == 'backend') {
         $intReadyToConfirm = 1;
     } else {
         if ($this->arrSettings['settingsReadyToConfirm'] == 1) {
             $intReadyToConfirm = intval($arrData['readyToConfirm']);
         } else {
             $intReadyToConfirm = 1;
         }
     }
     switch ($this->arrSettings['settingsEntryDisplaydurationValueType']) {
         case 1:
             $intDiffDay = $this->arrSettings['settingsEntryDisplaydurationValue'];
             $intDiffMonth = 0;
             $intDiffYear = 0;
             break;
         case 2:
             $intDiffDay = 0;
             $intDiffMonth = $this->arrSettings['settingsEntryDisplaydurationValue'];
             $intDiffYear = 0;
             break;
         case 3:
             $intDiffDay = 0;
             $intDiffMonth = 0;
             $intDiffYear = $this->arrSettings['settingsEntryDisplaydurationValue'];
             break;
     }
     if (empty($intId)) {
         if ($objInit->mode == 'backend') {
             $intConfirmed = 1;
             $intActive = intval($arrData['status']) ? 1 : 0;
             $intShowIn = 3;
             $intDurationType = intval($arrData['durationType']);
             $intDurationStart = $this->dateFromInput($arrData['durationStart']);
             $intDurationEnd = $this->dateFromInput($arrData['durationEnd']);
         } else {
             $intConfirmed = $this->arrSettings['settingsConfirmNewEntries'] == 1 ? 0 : 1;
             $intActive = 1;
             $intShowIn = 2;
             $intDurationType = $this->arrSettings['settingsEntryDisplaydurationType'];
             $intDurationStart = mktime();
             $intDurationEnd = mktime(0, 0, 0, date("m") + $intDiffMonth, date("d") + $intDiffDay, date("Y") + $intDiffYear);
         }
         $strValidateDate = $intConfirmed == 1 ? mktime() : 0;
         //insert new entry
         $objResult = $objDatabase->Execute("\n                INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_entries\n                   SET `form_id`='" . $intFormId . "',\n                       `create_date`='" . $strCreateDate . "',\n                       `validate_date`='" . $strValidateDate . "',\n                       `update_date`='" . $strValidateDate . "',\n                       `added_by`='" . $intUserId . "',\n                       `lang_id`='" . $_LANGID . "',\n                       `hits`='0',\n                       `last_ip`='" . $strLastIp . "',\n                       `confirmed`='" . $intConfirmed . "',\n                       `active`='" . $intActive . "',\n                       `duration_type`='" . $intDurationType . "',\n                       `duration_start`='" . $intDurationStart . "',\n                       `duration_end`='" . $intDurationEnd . "',\n                       `duration_notification`='0',\n                       `translation_status`='" . $strTransStatus . "',\n                       `ready_to_confirm`='" . $intReadyToConfirm . "',\n                       `updated_by`=" . $intUserId . ",\n                       `popular_hits`=0,\n                       `popular_date`='" . $strValidateDate . "'");
         if (!$objResult) {
             return false;
         }
         $intId = $objDatabase->Insert_ID();
     } else {
         self::getEntries($intId);
         $intOldReadyToConfirm = $this->arrEntries[$intId]['entryReadyToConfirm'];
         if ($objInit->mode == 'backend') {
             $intConfirmed = 1;
             $intShowIn = 3;
             $intDurationStart = $this->dateFromInput($arrData['durationStart']);
             $intDurationEnd = $this->dateFromInput($arrData['durationEnd']);
             $arrAdditionalQuery[] = "`duration_type`='" . intval($arrData['durationType']) . "', `duration_start`='" . intval($intDurationStart) . "',  `duration_end`='" . intval($intDurationEnd) . "'";
             $arrAdditionalQuery[] = "`active`='" . (intval($arrData['status']) ? 1 : 0) . "'";
         } else {
             $intConfirmed = $this->arrSettings['settingsConfirmUpdatedEntries'] == 1 ? 0 : 1;
             $intShowIn = 2;
             $arrAdditionalQuery = null;
         }
         $arrAdditionalQuery[] = " `updated_by`='" . $intUserId . "'";
         if (intval($arrData['userId']) != 0) {
             $arrAdditionalQuery[] = "`added_by`='" . intval($arrData['userId']) . "'";
         }
         if (!empty($arrData['durationResetNotification'])) {
             $arrAdditionalQuery[] = "`duration_notification`='0'";
         }
         $strAdditionalQuery = join(",", $arrAdditionalQuery);
         $strValidateDate = $intConfirmed == 1 ? mktime() : 0;
         $objUpdateEntry = $objDatabase->Execute("\n                UPDATE " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_entries\n                   SET `update_date`='" . $strUpdateDate . "',\n                       `translation_status`='" . $strTransStatus . "',\n                       `ready_to_confirm`='" . $intReadyToConfirm . "',\n                       {$strAdditionalQuery}\n                 WHERE `id`='{$intId}'");
         if (!$objUpdateEntry) {
             return false;
         }
         $objDeleteCategories = $objDatabase->Execute("DELETE FROM " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_categories WHERE entry_id='" . $intId . "'");
         $objDeleteLevels = $objDatabase->Execute("DELETE FROM " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_levels WHERE entry_id='" . $intId . "'");
     }
     //////////////////////
     // STORE ATTRIBUTES //
     //////////////////////
     $error = false;
     foreach ($this->getInputfields() as $arrInputfield) {
         // store selected category (field = category)
         if ($arrInputfield['id'] == 1) {
             $selectedCategories = isset($arrData['selectedCategories']) ? $arrData['selectedCategories'] : array();
             foreach ($selectedCategories as $intCategoryId) {
                 $objResult = $objDatabase->Execute("\n                    INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_categories\n                       SET `entry_id`='" . intval($intId) . "',\n                           `category_id`='" . intval($intCategoryId) . "'");
                 if (!$objResult) {
                     \Message::error($objDatabase->ErrorMsg());
                     $error = true;
                 }
             }
             continue;
         }
         // store selected level (field = level)
         if ($arrInputfield['id'] == 2) {
             if ($this->arrSettings['settingsShowLevels'] == 1) {
                 $selectedLevels = isset($arrData['selectedLevels']) ? $arrData['selectedLevels'] : array();
                 foreach ($selectedLevels as $intLevelId) {
                     $objResult = $objDatabase->Execute("\n                        INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_levels\n                           SET `entry_id`='" . intval($intId) . "',\n                               `level_id`='" . intval($intLevelId) . "'");
                     if (!$objResult) {
                         \Message::error($objDatabase->ErrorMsg());
                         $error = true;
                     }
                 }
             }
             continue;
         }
         // skip meta attributes or ones that are out of scope (frontend/backend)
         if ($arrInputfield['type'] == 16 || $arrInputfield['type'] == 18 || $arrInputfield['type'] == 30 || $arrInputfield['show_in'] != $intShowIn && $arrInputfield['show_in'] != 1) {
             continue;
         }
         // truncate attribute's data ($arrInputfield) from database if it's VALUE is not set (empty) or set to it's default value
         if (empty($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']]) || $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']] == $arrInputfield['default_value'][$_LANGID]) {
             $objResult = $objDatabase->Execute("DELETE FROM " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_inputfields WHERE entry_id='" . $intId . "' AND field_id='" . intval($arrInputfield['id']) . "'");
             if (!$objResult) {
                 \Message::error($objDatabase->ErrorMsg());
                 $error = true;
             }
             continue;
         }
         // initialize attribute
         $strType = $arrInputfield['type_name'];
         $strInputfieldClass = "\\Cx\\Modules\\MediaDir\\Model\\Entity\\MediaDirectoryInputfield" . ucfirst($strType);
         try {
             $objInputfield = safeNew($strInputfieldClass, $this->moduleName);
         } catch (Exception $e) {
             \Message::error($e->getMessage());
             $error = true;
             continue;
         }
         // delete attribute's data of languages that are no longer in use
         $objDatabase->Execute("DELETE FROM " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_inputfields WHERE entry_id='" . $intId . "' AND field_id = '" . intval($arrInputfield['id']) . "' AND lang_id NOT IN (" . join(",", array_keys($this->arrFrontendLanguages)) . ")");
         // attribute is i18n
         foreach ($this->arrFrontendLanguages as $arrLang) {
             try {
                 $intLangId = $arrLang['id'];
                 // attribute is non-i18n
                 if ($arrInputfield['type_multi_lang'] == 0) {
                     $strInputfieldValue = $objInputfield->saveInputfield($arrInputfield['id'], $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']]);
                     $objResult = $objDatabase->Execute("\n                            INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_inputfields\n                               SET `entry_id`='" . intval($intId) . "',\n                                   `lang_id`='" . intval($intLangId) . "',\n                                   `form_id`='" . intval($intFormId) . "',\n                                   `field_id`='" . intval($arrInputfield['id']) . "',\n                                   `value`='" . contrexx_raw2db($strInputfieldValue) . "'\n                            ON DUPLICATE KEY\n                                UPDATE `value`='" . contrexx_raw2db($strInputfieldValue) . "'");
                     if (!$objResult) {
                         throw new \Exception($objDatabase->ErrorMsg());
                     }
                     continue;
                 }
                 // if the attribute is of type dynamic (meaning it can have an unlimited set of childs (references))
                 if ($arrInputfield['type_dynamic'] == 1) {
                     $arrDefault = array();
                     foreach ($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][0] as $intKey => $arrValues) {
                         $arrNewDefault = $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$_LANGID][$intKey];
                         $arrOldDefault = $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']]['old'][$intKey];
                         $arrNewValues = $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId][$intKey];
                         foreach ($arrValues as $strKey => $strMasterValue) {
                             if ($intLangId == $_LANGID) {
                                 if ($arrNewDefault[$strKey] != $strMasterValue) {
                                     if ($strMasterValue != $arrOldDefault[$strKey] && $arrNewDefault[$strKey] == $arrOldDefault[$strKey]) {
                                         $arrDefault[$intKey][$strKey] = $strMasterValue;
                                     } else {
                                         $arrDefault[$intKey][$strKey] = $arrNewDefault[$strKey];
                                     }
                                 } else {
                                     $arrDefault[$intKey][$strKey] = $arrNewDefault[$strKey];
                                 }
                             } else {
                                 if ($arrNewValues[$strKey] == '') {
                                     $arrDefault[$intKey][$strKey] = $strMasterValue;
                                 } else {
                                     $arrDefault = $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId];
                                 }
                             }
                         }
                         $strDefault = $arrDefault;
                     }
                     $strInputfieldValue = $objInputfield->saveInputfield($arrInputfield['id'], $strDefault, $intLangId);
                 } else {
                     if (empty($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId]) || $intLangId == $_LANGID) {
                         $strMaster = isset($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][0]) ? $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][0] : null;
                         $strNewDefault = isset($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$_LANGID]) ? $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$_LANGID] : '';
                         if ($strNewDefault != $strMaster) {
                             $strDefault = $strMaster;
                         } else {
                             $strDefault = isset($arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId]) ? $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId] : '';
                         }
                         $strInputfieldValue = $objInputfield->saveInputfield($arrInputfield['id'], $strDefault, $intLangId);
                     } else {
                         // regular attribute get parsed
                         $strInputfieldValue = $objInputfield->saveInputfield($arrInputfield['id'], $arrData[$this->moduleNameLC . 'Inputfield'][$arrInputfield['id']][$intLangId], $intLangId);
                     }
                 }
                 $objResult = $objDatabase->Execute("\n                        INSERT INTO " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_rel_entry_inputfields\n                           SET `entry_id`='" . intval($intId) . "',\n                               `lang_id`='" . intval($intLangId) . "',\n                               `form_id`='" . intval($intFormId) . "',\n                               `field_id`='" . intval($arrInputfield['id']) . "',\n                               `value`='" . contrexx_raw2db($strInputfieldValue) . "'\n                        ON DUPLICATE KEY\n                            UPDATE `value`='" . contrexx_raw2db($strInputfieldValue) . "'");
                 if (!$objResult) {
                     throw new \Exception($objDatabase->ErrorMsg());
                 }
             } catch (Exception $e) {
                 \Message::error($e->getMessage());
                 $error = true;
             }
         }
     }
     if (empty($intEntryId)) {
         if ($intReadyToConfirm == 1) {
             new MediaDirectoryMail(1, $intId, $this->moduleName);
         }
         new MediaDirectoryMail(2, $intId, $this->moduleName);
     } else {
         if ($intReadyToConfirm == 1 && $intOldReadyToConfirm == 0) {
             new MediaDirectoryMail(1, $intId, $this->moduleName);
         }
         new MediaDirectoryMail(6, $intId, $this->moduleName);
     }
     return $intId;
 }
 function saveLevel($arrData, $intLevelId = null)
 {
     global $_ARRAYLANG, $_CORELANG, $objDatabase, $_LANGID;
     //get data
     $intId = intval($intLevelId);
     $intParentId = intval($arrData['levelPosition']);
     $intShowEntries = intval($arrData['levelShowEntries']);
     $intShowSublevels = isset($arrData['levelShowSublevels']) ? contrexx_input2int($arrData['levelShowSublevels']) : 0;
     $intShowCategories = intval($arrData['levelShowCategories']);
     $intActive = intval($arrData['levelActive']);
     $strPicture = contrexx_addslashes(contrexx_strip_tags($arrData['levelImage']));
     $arrName = $arrData['levelName'];
     $arrDescription = $arrData['levelDescription'];
     if (empty($intId)) {
         //insert new category
         $objInsertAttributes = $objDatabase->Execute("\n                INSERT INTO\n                    " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_levels\n                SET\n                    `parent_id`='" . $intParentId . "',\n                    `order`=0,\n                    `show_entries`='" . $intShowEntries . "',\n                    `show_sublevels`='" . $intShowSublevels . "',\n                    `show_categories`='" . $intShowCategories . "',\n                    `picture`='" . $strPicture . "',\n                    `active`='" . $intActive . "'\n            ");
         if ($objInsertAttributes !== false) {
             $intId = $objDatabase->Insert_ID();
             foreach ($this->arrFrontendLanguages as $key => $arrLang) {
                 if (empty($arrName[0])) {
                     $arrName[0] = "[[" . $_ARRAYLANG['TXT_MEDIADIR_NEW_LEVEL'] . "]]";
                 }
                 if (empty($arrDescription[0])) {
                     $arrDescription[0] = isset($arrDescription[$_LANGID]) ? $arrDescription[$_LANGID] : '';
                 }
                 $strName = $arrName[$arrLang['id']];
                 $strDescription = $arrDescription[$arrLang['id']];
                 if (empty($strName)) {
                     $strName = $arrName[0];
                 }
                 if (empty($strDescription)) {
                     $strDescription = $arrDescription[0];
                 }
                 $objInsertNames = $objDatabase->Execute("\n                        INSERT INTO\n                            " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_level_names\n                        SET\n                            `lang_id`='" . intval($arrLang['id']) . "',\n                            `level_id`='" . intval($intId) . "',\n                            `level_name`='" . contrexx_raw2db(contrexx_input2raw($strName)) . "',\n                            `level_description`='" . contrexx_raw2db(contrexx_input2raw($strDescription)) . "'\n                    ");
             }
             if ($objInsertNames !== false) {
                 return true;
             } else {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         //update category
         if ($intParentId == $intLevelId) {
             $parentSql = null;
         } else {
             $parentSql = "`parent_id`='" . $intParentId . "',";
         }
         $objUpdateAttributes = $objDatabase->Execute("\n                UPDATE\n                    " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_levels\n                SET\n                    " . $parentSql . "\n                    `show_entries`='" . $intShowEntries . "',\n                    `show_sublevels`='" . $intShowSublevels . "',\n                    `show_categories`='" . $intShowCategories . "',\n                    `picture`='" . $strPicture . "',\n                    `active`='" . $intActive . "'\n                WHERE\n                    `id`='" . $intId . "'\n            ");
         if ($objUpdateAttributes !== false) {
             $objDatabase->Execute("DELETE FROM " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_level_names WHERE level_id='" . $intId . "'");
             foreach ($this->arrFrontendLanguages as $key => $arrLang) {
                 if (empty($arrName[0])) {
                     $arrName[0] = "[[" . $_ARRAYLANG['TXT_MEDIADIR_NEW_LEVEL'] . "]]";
                 }
                 if (empty($arrDescription[0])) {
                     $arrDescription[0] = isset($arrDescription[$_LANGID]) ? $arrDescription[$_LANGID] : '';
                 }
                 $strName = $arrName[$arrLang['id']];
                 $strDescription = $arrDescription[$arrLang['id']];
                 if (empty($strName)) {
                     $strName = $arrName[0];
                 }
                 if (empty($strDescription)) {
                     $strDescription = $arrDescription[0];
                 }
                 $objInsertNames = $objDatabase->Execute("\n                        INSERT INTO\n                            " . DBPREFIX . "module_" . $this->moduleTablePrefix . "_level_names\n                        SET\n                            `lang_id`='" . intval($arrLang['id']) . "',\n                            `level_id`='" . intval($intId) . "',\n                            `level_name`='" . contrexx_raw2db(contrexx_input2raw($strName)) . "',\n                            `level_description`='" . contrexx_raw2db(contrexx_input2raw($strDescription)) . "'\n                    ");
             }
             if ($objInsertNames !== false) {
                 return true;
             } else {
                 return false;
             }
         } else {
             return false;
         }
     }
 }